texts:
I have written the following code to get ImageColorPicker child:

foreach (CustomTabItem customTabItem in SelectedWindowsTabControl.Items)
{
    TabItem ti = tabControl.ItemContainerGenerator.ContainerFromItem(customTabItem) as TabItem;
    Popup popup = (Helpers.FindVisualChild<Popup>(ti) as Popup);
    ImageColorPicker icp = (popup.Child as StackPanel).Children[0] as ImageColorPicker;

    ...
}

public class Helpers
{
    /// <summary>
    /// Return the first visual child of element by type.
    /// </summary>
    /// <typeparam name="T">The type of the Child</typeparam>
    /// <param name="obj">The parent Element</param>
    public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is T)
                return (T)child;
            else
            {
                T childOfChild = FindVisualChild<T>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
        }
        return null;
    }
}

Here's the control template XAML of the TabItem (the relevant part):

<ControlTemplate TargetType="{x:Type local:CustomTabItem}">
    <Grid Height="26" Background="{TemplateBinding Background}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <ContentPresenter Margin="5,0" HorizontalAlignment="Left" VerticalAlignment="Center" ContentSource="Header">
        </ContentPresenter>
        <StackPanel Grid.Column="1" Height="16" Margin="0,0,1,0" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
            <ToggleButton x:Name="Edit" Width="16" Content="&#xE104;" Style="{StaticResource CustomizedMetroTabItemToggleButton}" ToolTip="Edit" />
            <Popup HorizontalOffset="{Binding Width, ElementName=Edit}" IsOpen="{Binding IsChecked, Mode=TwoWay, ElementName=Edit}" Placement="Left" PlacementTarget="{Binding ElementName=Edit}" PopupAnimation="Slide" StaysOpen="False" VerticalOffset="{Binding ActualHeight, ElementName=Edit}">
                <StackPanel>
                    <local:ImageColorPicker x:Name="ColorPicker" Width="100" Height="100" HorizontalAlignment="Center" Source="Images/ColorWheel.png" />
                </StackPanel>
            </Popup>
        </StackPanel>
    </Grid>
</ControlTemplate>

Is there a better way to get the ImageColorPicker than what I've done? (getting the TabItem, then the Popup and then the ImageColorPicker, I am sure there's a shorter way)


texts: Python program to find the substring with concatenation of all words

texts:
This is a Leetcode problem:

  You are given a string, S, and a list of words, L that are all of the same lengths. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

Here is my solution to the problem:

class Solution:

    def __init__(self, S, L):
        self.S = S
        self.L = L

    def findSubstring(self, S, L):
        res = []      # result list
        num = len(L)  # length of the str list
        ls = len(S)
        if num == 0:
            return []
        str_len = len(L[0]) # length of each str

        #creating the map: counting the occurrence of each string

        map_str = dict((x,L.count(x)) for x in set(L))
        i = 0
        while i + num * str_len - 1 < ls:
            map_str2 = {}
            j = 0
            while j < num:
                subs = S[i + j * str_len:i + j * str_len + str_len ]
                if not subs in map_str:
                    break
                else:
                    map_str2[subs] = map_str2.get(subs, 0) + 1
                    if map_str2[subs]>map_str[subs]:
                        break
                    j = j + 1
            if j == num:
                res.append(i)
            i = i + 1

        return res

S = "barfoothefoobarman"
L = ["bar","foo"]

index = Solution(S, L)
print(index.findSubstring(S, L))

Here are some example inputs/outputs:

S = "barfoothefoobarman"

L = ["bar", "foo"]

>>> [0, 9]

-------------------------------------------------------------------

S = "lingmindraboofooowingdingbarrwingmonkeypoundcake"

L = ["fooo", "barr", "wing", "ding", "wing"]

>>> [13]

So I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts:
I've made a Python Steganographer using the Python Imaging Library. It basically encodes the binary text in the last 'n' bits of the red content in each pixel of the image. Here is my code, please suggest some improvements.

from PIL import Image

import os

def str2bin(message):
    binary = bin(int.from_bytes(message.encode('utf-8'), 'big'))
    return binary[2:]

def bin2str(binary):
    n = int(binary, 2)
    return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()

def hide(filename, message, bits=2):
    image = Image.open(filename)
    binary = str2bin(message) + '00000000'

    if (len(binary)) % 8 != 0:
        binary = '0'*(8 - ((len(binary)) % 8)) + binary

    data = list(image.getdata())

    newData = []

    index = 0
    for pixel in data:
        if index < len(binary):
            pixel = list(pixel)
            pixel[0] >>= bits
            pixel[0] <<= bits
            pixel[0] += int('0b' + binary[index:index+bits], 2)
            pixel = tuple(pixel)
            index += bits

        newData.append(pixel)

    image.putdata(newData)
    image.save('\\'.join(filename.split('\\')[0:-1]) + '/coded-'+os.path.basename(filename), 'PNG')

    return len(binary)

def unhide(filename, bits=2):
    image = Image.open(filename)
    data = image.getdata()

    binary = ''

    index = 0

    while not (len(binary) % 8 == 0 and binary[-8:] == '00000000'):
        value = '00000000' + bin(data[index][0])[2:]
        binary += value[-bits:]
        index += 1

    message = bin2str(binary)
    return message

if __name__ == '__main__':

    file = open('tmiab.txt', encoding='utf-8')

    hide('E:\\Python\\Steganography\\img.png', file.read(), 2)
    print(unhide('E:\\Python\\Steganography\\coded-img.png', 2)[:10000])

I am able to encode the novel Three Men In A Boat in a 1600 by 1200 pixel image by just replacing the last two bits.

I am looking for some improvements like reducing time consumption.

Please help. Thanks.


texts:
Is there any way I can simplify this re-sizable solution? It seems too difficult and messy to me.

Working example

$.ui.plugin.add("resizable", "alsoResizeReverse", {

    start: function (event, ui) {

        var self = $(this).data("resizable"),
            o = self.options;

        var _store = function (exp) {
            $(exp).each(function () {
                $(this).data("resizable-alsoresize-reverse", {
                    width: parseInt($(this).width(), 10),
                    height: parseInt($(this).height(), 10),
                    left: parseInt($(this).css('left'), 10),
                    top: parseInt($(this).css('top'), 10)
                });
            });
        };

        if (typeof (o.alsoResizeReverse) == 'object' && !o.alsoResizeReverse.parentNode) {
            if (o.alsoResizeReverse.length) {
                o.alsoResize = o.alsoResizeReverse[0];
                _store(o.alsoResizeReverse);
            } else {
                $.each(o.alsoResizeReverse, function (exp, c) {
                    _store(exp);
                });
            }
        } else {
            _store(o.alsoResizeReverse);
        }
    },

    resize: function (event, ui) {
        var self = $(this).data("resizable"),
            o = self.options,
            os = self.originalSize,
            op = self.originalPosition;

        var delta = {
            height: (self.size.height - os.height) || 0,
            width: (self.size.width - os.width) || 0,
            top: (self.position.top - op.top) || 0,
            left: (self.position.left - op.left) || 0
        },

        _alsoResizeReverse = function (exp, c) {
            $(exp).each(function () {
                var el = $(this),
                    start = $(this).data("resizable-alsoresize-reverse"),
                    style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left'];

                $.each(css || ['width', 'height', 'top', 'left'], function (i, prop) {
                    var sum = (start[prop] || 0) - (delta[prop] || 0);
                    if (sum && sum >= 0) style[prop] = sum || null;
                });

                //Opera fixing relative position
                if (/relative/.test(el.css('position')) && $.browser.opera) {
                    self._revertToRelativePosition = true;
                    el.css({
                        position: 'absolute',
                        top: 'auto',
                        left: 'auto'
                    });
                }

                el.css(style);
            });
        };

        if (typeof (o.alsoResizeReverse) == 'object' && !o.alsoResizeReverse.nodeType) {
            $.each(o.alsoResizeReverse, function (exp, c) {
                _alsoResizeReverse(exp, c);
            });
        } else {
            _alsoResizeReverse(o.alsoResizeReverse);
        }
    },

    stop: function (event, ui) {
        var self = $(this).data("resizable");

        //Opera fixing relative position
        if (self._revertToRelativePosition && $.browser.opera) {
            self._revertToRelativePosition = false;
            el.css({
                position: 'relative'
            });
        }

        $(this).removeData("resizable-alsoresize-reverse");
    }
});

$(function () {

    $("#resizable").resizable({
        alsoResizeReverse: ".myframe"
    });

});
#resizable, .myframe {
    border:1px solid black;
    padding:10px;
    margin-bottom:20px;
    width:50%;
    height: 150px
}

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/base/jquery-ui.css" rel="stylesheet"/>

This is the resizable content...

This must resize in reverse direction...


texts: Backbone.Collection - Ensure that at most one model has property set to true

texts:
I have a Backbone.Collection which has some models in it. Each model has a boolean property called 'special.' Only one model should be special at any given time.

I've got the following to enforce this, but I'm wondering if it could be clearer or if there is a more appropriate way to enforce such behavior:

//  Ensure that only 1 model is ever special.
this.on('change:special', function (changedModel, special) {

    if (special) {
        this.each(function (model) {
            if (model !== changedModel) {
                model.set('special', false);
            }
        });
    }

});

I don't like this because it seems overly verbose and also gives a period of time where two items are special.


texts: Python - Hexadecimal to Decimal conversions

texts:
I have written a python 2 program for a school project to convert from hexadecimal to decimal without using built-in functions and vice versa in python. I would like to know how I can make my code more concise - specifically, the "d_func" function.

d_dict = {"0" : 0, "1" : 1, "2" : 2, "3" : 3, "4" : 4, "5" : 5, "6" : 6, "7" : 7, "8" : 8, "9" : 9, "A" : 10, "B" : 11, "C" : 12, "D" : 13, "E" : 14, "F": 15}

def d_func(digit, mode):
    if mode == 1:
        for x in range(len(d_dict.keys())):
            if digit == list(d_dict.keys())[x]:
                return x
    else:
        for y in range(len(d_dict.values())):
            if digit == list(d_dict.values())[y]:
                return list(d_dict.keys())[y]

def hd_func(h_num):
    d_num, p = 0, 0

    for digit in range(len(h_num), 0, -1):
        d_num = d_num + 16 ** p * d_func(h_num[digit - 1], 1)
        p += 1

    return str(d_num)

def dh_func(d_num):
    f_list, h_num, p = [], "", 0

    while d_num > 0:
        f_list.append(d_num % 16)
        d_num //= 16

    for f in f_list[::-1]:
        h_num += d_func(f, 2)

    return h_num

func_dict = {"h": hd_func, "d": dh_func}
u_choice, u_num = input("Enter [H] for Hexadecimal to Decimal, [D] for Decimal to Hexadecimal"), input("Enter the number: ")
print(func_dict[u_choice.lower()](u_num))


texts:
I'm starting up a new project, and I've always had an issue getting vertical alignment right in CSS. Is there anything I could do better that what I've currently come up with? Replacing the header and nav with divs, and changing the rgba values to hex values this seems to work all the way back to IE7 which I'm happy with.

CSS

html, * {
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
    -ms-box-sizing:border-box;
    -o-box-sizing:border-box;
    box-sizing:border-box;
}

body {
    margin:0;
    padding:0;
}

nav {
    background-color:rgba(0, 0, 0, 0.1);
}

nav a.tab {
    text-align:center;
    padding:0 15px;
    color:#FFFFFF;
    display:inline-table;

    vertical-align:middle;  text-decoration:none;
}

nav a.tab > span {
    display:table-cell;
    vertical-align:middle;
}

nav a.tab:hover {
    background-color:rgba(0, 0, 0, 0.1);
    text-decoration:underline;
}

header {
    background-color:#27AE60;
    font-size:1.2em;
    color:#FFF;
    display:table;
    width:100%;
}

header, header h1, header nav, header nav a.tab {
    height:80px;
    vertical-align:middle;
}

header nav {
    display:inline-block;
}

header h1 {
    margin:0 20px;
    display:inline;
    text-shadow:2px 2px 2px #333333;
}

HTML

Projects

            Home

            Projects

            Contact

jsFiddle


texts: Writing a metaclass to ensure a class is thread-safe

texts:
Python allows the creation of classes to be modified via metaclasses. They can perform all sorts of operations that might appear to be magical to languages that do not have the capability. The goal of the following metaclass is to automatically add a mutex to all method calls.

It is easy to write such a metaclass if the possibility of inheritance is ignored. When base classes implemented in Python are used, their methods must also be considered, but those written in C can usually be safely ignored. This means the metaclass must be somewhat recursive.

Does the code shown below accomplish the goal of making the classes it builds thread-safe, and can the metaclass be improved for clarity?

class AtomicMeta(type):
    """AtomicMeta(name, bases, dictionary) -> new thread-safe class"""
    __REGISTRY = {}

    def __new__(mcs, name, bases, dictionary, parent=None):
        """Create a new class while fixing bases and all callable items."""
        final_bases = []
        # Replace bases with those that are safe to use.
        for base in bases:
            fixed = mcs.__REGISTRY.get(base)
            if fixed:
                final_bases.append(fixed)
            elif base in mcs.__REGISTRY.values():
                final_bases.append(base)
            elif base in vars(builtins).values():
                final_bases.append(base)
            else:
                final_bases.append(mcs(
                    base.__name__, base.__bases__, dict(vars(base)), base
                ))
        class_lock = threading.Lock()
        # Wrap all callable attributes so that they are thread-safe.
        for key, value in dictionary.items():
            if callable(value):
                dictionary[key] = mcs.__wrap(value, class_lock)
        new_class = super().__new__(mcs, name, tuple(final_bases), dictionary)
        # Register the class and potentially replace parent references.
        if parent is None:
            mcs.__REGISTRY[object()] = new_class
        else:
            mcs.__REGISTRY[parent] = new_class
            source = inspect.getmodule(parent)
            *prefix, root = parent.__qualname__.split('.')
            for name in prefix:
                source = getattr(source, name)
            setattr(source, root, new_class)
        return new_class

    # noinspection PyUnusedLocal
    def __init__(cls, name, bases, dictionary, parent=None):
        """Initialize the new class while ignoring any potential parent."""
        super().__init__(name, bases, dictionary)

    @staticmethod
    def __wrap(method, class_lock):
        """Ensure that all method calls are run as atomic operations."""

        @functools.wraps(method)
        def atomic_wrapper(self, *args, **kwargs):
            with class_lock:
                try:
                    instance_lock = self.__lock
                except AttributeError:
                    instance_lock = self.__lock = threading.RLock()
            with instance_lock:
                return method(self, *args, **kwargs)

        return atomic_wrapper


texts:
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?

Swift Code:
import Foundation

let numberOfRequiredFactors = 500

func nthTriangularNumber( n:Int ) -> Int {
    var number = 0

    for iterator in 0...n {

        number += iterator

    }

    return number
}

func findNumberOfFactors( number:Int ) -> Int {
    var numberOfFactors = 0

    for iterator in 1...number {
        if number % iterator == 0 {
            numberOfFactors++
        }
    }

    return numberOfFactors
}

var countOfTriangularNumbers = 1
var found = false
var foundNumber = 0

while !found {

    var numberOfFactors = findNumberOfFactors(nthTriangularNumber(countOfTriangularNumbers))

    if numberOfFactors > numberOfRequiredFactors {
        found = true
        foundNumber = nthTriangularNumber(countOfTriangularNumbers)
    }

    countOfTriangularNumbers++

}

println("The number is: \(foundNumber)")

Comments on making this code more efficient, making it more cleaner or violations of best practices would be highly appreciated. However, it did work for smaller numbers, which is how I tested if the logic is right.


texts: Deleting nodes having greater value on right side

texts:
Problem Summary:

  Given a singly linked list, remove all the nodes which have a greater value on right side.

  Example: The list 12->15->10->11->5->6->2->3->NULL should be changed
  to 15->11->6->3->NULL. Note that 12, 10, 5 and 2 have been deleted
  because there is a greater value on the right side.

Full problem statement

My logic follows Method 2 mentioned in the solution to that problem.

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

struct node
{
    int data;
    struct node* next;
};

void printList (struct node* head)
{
    struct node* current;
    for (current = head; current != NULL; current = current->next)
        printf ("%d\n",current->data);
}

void appendNode (struct node** headRef, int data)
{
    struct node* newNode = malloc(sizeof(struct node));

    newNode->data = data;
    newNode->next = *headRef;
    *headRef = newNode;
}

void reverseList (struct node** head)
{
    struct node* past = NULL;
    struct node* present;
    struct node* future;

    for (present = *head; present != NULL; )
    {
        future = present->next;
        present->next = past;
        past = present;
        present = future;
    }
        *head = past;
}

void removeGreater (struct node** head)
{
    struct node* current;
    struct node* prev;
    int max;

    if (*head != NULL)
    {
        max = (*head)->data;
        prev = *head;
        for (current = (*head)->next; current != NULL;)
        {

            if (current->data >= max)
            {
                max = current->data;
                prev = current;
                current = current->next;
            }
            else
            {
                if (current->next != NULL)
                {
                    struct node* temp = current->next;
                    current->data = temp->data;
                    current->next = temp->next;
                    free (temp);
                }
                else
                {
                    prev->next = NULL;
                    free (current);
                    break;
                }
            }
        }
    }
}

int main(void)
{

    struct node* head = NULL;
    struct node* tail;
    struct node* current;

    int input,num,num1;

    printf ("Enter no. of inputs \n");
    scanf ("%d",&num);
    num1 = num;
    printf ("\n");
    printf ("Enter the numbers\n");

    do
    {
        scanf("%d",&input);
        if (head == NULL)
        {
            appendNode (&head, input);
            tail = head;
        }
        else
        {
            appendNode (&tail->next, input);
            tail = tail->next;
        }
        num--;
    } while (num > 0);

    printf ("\n Before Reversing :\n");
    printList (head);

    reverseList(&head);

    printf ("\n After Reversing :\n");
    printList (head);

    removeGreater (&head);
    printf ("\n After Removing :\n");
    printList (head);

    reverseList(&head);
    printf ("\n Final Output :\n");
    printList (head);

    return 0;
}


texts:
I wanted to write a function that when invoked, will scroll the page downwards in a smooth fashion.

Comments and criticism welcome. I don't like, for example that determining whether it is done is not based on the scroll position.

const EASING = BezierEasing(0, .1, .1, 1); // Example values.
const DURATION = 1000; // ms.

document.addEventListener('DOMContentLoaded',
  () =>  {
    document.querySelector('#foo')
      .addEventListener('click', onClick, false);
});

function onClick(e) {
  scroll(400); // px.
  e.preventDefault();
  return false;
}

function scroll(distance) {
  var start, travelled, html;

  start = performance.now();
  travelled = 0;
  html = document.querySelector('html');

  (function move(now) {
    var fractionDone, dy, toMove;

    fractionDone = (now-start) / DURATION;

    if((1 - fractionDone) <= 0) {
      return; // Done!
    }

    if(window.scrollY + window.innerHeight
      === html.offsetHeight) {
      return; // At bottom of page.
    }

    dy = ((EASING.get(fractionDone)) * distance);
    toMove = Math.floor((dy - travelled)); // `scrollBy` only accepts integers.

    if(toMove > 0) {
      window.scrollBy(0, toMove);
      travelled += toMove;
    }

    requestAnimationFrame(move);
  }(start));
}
<!DOCTYPE html>
<html>
  <head>
    <script src="https://rawgit.com/gre/bezier-easing/master/build.js"></script>
  </head>

  <body>
    <a href id="foo">Click Me!</a>
    <script>
      var body = document.querySelector('body');
      for(var x = 0; x < 50; x++) {
        var div = document.createElement("div");
        var text = document.createTextNode(x);
        div.appendChild(text);
        body.appendChild(div);
      }
    </script>
  </body>
</html>


texts: Avoiding code duplication for attribute-removal code

texts:
I need to use the same code in different jQuery attributes.  Is it possible to put this if in a external function and call it inside a change event?  I would like avoid duplicating code.

$("#Max").change(function () {
var max = $("#Max").val();
var min = $("#Min").val();

if (max != min) {
    $("#Result").attr("disabled", "disabled");
}
else {
    $("#Result").removeAttr("disabled");
}
});

$("#Min").change(function () {
var max = $("#Max").val();
var min = $("#Min").val();

if (max != min) {
    $("#Result").attr("disabled", "disabled");
}
else {
    $("#Result").removeAttr("disabled");
}
});


texts:
I created a program that determines how many years you have left before retiring, and in a year when you can retire.

This is my code below:

$(function(){
 const currentYear = (new Date).getFullYear();
 var convert = function(a){
     return parseInt(a.val());
 }
 var result = function(a, b){
     $('.currentYear').text(currentYear);
     if (b>a){
  $('.newAge').text(b - a);
  $('.retireYear').text(currentYear + (b - a));
  message1.dialog("open");
  return message1
     } else {
  $('.newAge').text(a - b);
  $('.retireYear').text(currentYear - (a - b));
  message2.dialog("open");
  return message2
     }
 }
 const message1 = $("#message1").dialog({autoOpen: false});
 const message2 = $("#message2").dialog({autoOpen: false});
        const form = $("#form").dialog({
            autoOpen: false,
            modal: true,
            buttons:[{
             text: "Сount",
             icon: "ui-icon-contact",
             click: function(){
                 $( this ).dialog( "close" );
                    var str1 = convert($('#currentAge'));
                    var str2 = convert($('#retireAge'));
                    result(str1, str2);
             }
            }]
        });
        $("#btn").click(function(){
         form.dialog("open");
     });
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

 <button type="button" class="btn btn-primary" id="btn">Retirement Calculator</button>

<form id="form">

        What is your current age?
        <input type="number" class="form-control" id="currentAge" oninput="validity.valid||(value='');" min="0" style="width: 90px">

        At what age would you like to retire?
        <input type="number" class="form-control" id="retireAge" oninput="validity.valid||(value='');" min="0" style="width: 90px">

</form>

You have  years left until you can retire.

It's , so you can retire in .

You could retire  years ago.

It's , so you could retire in .

I will appreciate any advice about code.


texts:
I wrote a function for checking if a Map[(String, String)] contains an element with a matching key and value:

  def findDupes(map: Map[String, String], key: String, value: String):
                           Option[(String, String)] = {
    val dupes = map.collect { case (x, y) if(x == key && y == value) => key }
    dupes match {
      case Nil     => None
      case x :: _  => Some(key, value)
    }
  }

Testing

scala> map
res10: scala.collection.immutable.Map[String,String] = Map(1 -> HELLO, 2 -> WORLD)

scala> findDupes(map, "1", "HELLO")
res8: Option[(String, String)] = Some((1,HELLO))

scala> findDupes(map, "1", "FOO")
res9: Option[(String, String)] = None


texts: Printing the start and end dates of the most recent eight weeks

texts:
I have a table with columns dated by week that changes dynamically each day. Currently, I am using the following php code to get the proper dates for the past eight weeks:

$currentDate = date('Y-m-d');
$weekOneStart = strtotime("-56 day", strtotime($currentDate));
$weekOneStart = date("m/d/Y", $weekOneStart);
$weekOneEnd = strtotime("-49 day", strtotime($currentDate));
$weekOneEnd = date('m/d/Y', $weekOneEnd);
$weekTwoStart = strtotime("-49 day", strtotime($currentDate));
$weekTwoStart = date("m/d/Y", $weekTwoStart);
$weekTwoEnd = strtotime("-41 day", strtotime($currentDate));
$weekTwoEnd = date('m/d/Y', $weekTwoEnd);
$weekThreeStart = strtotime("-41 day", strtotime($currentDate));
$weekThreeStart = date("m/d/Y", $weekThreeStart);
$weekThreeEnd = strtotime("-34 day", strtotime($currentDate));
$weekThreeEnd = date('m/d/Y', $weekThreeEnd);
$weekFourStart = strtotime("-34 day", strtotime($currentDate));
$weekFourStart = date("m/d/Y", $weekFourStart);
$weekFourEnd = strtotime("-27 day", strtotime($currentDate));
$weekFourEnd = date('m/d/Y', $weekFourEnd);
$weekFiveStart = strtotime("-27 day", strtotime($currentDate));
$weekFiveStart = date("m/d/Y", $weekFiveStart);
$weekFiveEnd = strtotime("-20 day", strtotime($currentDate));
$weekFiveEnd = date('m/d/Y', $weekFiveEnd);
$weekSixStart = strtotime("-20 day", strtotime($currentDate));
$weekSixStart = date("m/d/Y", $weekSixStart);
$weekSixEnd = strtotime("-13 day", strtotime($currentDate));
$weekSixEnd = date('m/d/Y', $weekSixEnd);
$weekSevenStart = strtotime("-13 day", strtotime($currentDate));
$weekSevenStart = date("m/d/Y", $weekSevenStart);
$weekSevenEnd = strtotime("-6 day", strtotime($currentDate));
$weekSevenEnd = date('m/d/Y', $weekSevenEnd);
$weekEightStart = strtotime("-6 day", strtotime($currentDate));
$weekEightStart = date("m/d/Y", $weekEightStart);
$weekEightEnd = $currentDate;

and echoing the results in my table like so:

$weekOneStart - $weekOneEnd
$weekTwoStart - $weekTwoEnd
$weekThreeStart - $weekThreeEnd
$weekFourStart - $weekFourEnd
$weekFiveStart - $weekFiveEnd
$weekSixStart - $weekSixEnd
$weekSevenStart - $weekSevenEnd
$weekEightStart - $weekEightEnd

This works find and gives me the info I need, but I feel like there must be a simpler way to do this. I tried (with my variables, just posting the generic code here since I already deleted my version):

$date = '2009-12-06';
// End date
$end_date = '2020-12-31';

while (strtotime($date) <= strtotime($end_date)) {
            echo "$date\n";
            $date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
 }

But this didn't work for me. Any other suggestions for cleaning/simplifying my code?


texts: UNIX cp multithreaded implementation in C

texts:
I recently finished a high school project of mine for a class revolving around creating my own multithreaded implementation of the "cp" terminal command in UNIX systems.
I am seeking for help by experienced people in C to help me make my code better, offering constructive criticism all while improving myself at the same time.
Specifically:

Can my code become faster than it currently is?
Are there any potential runtime errors in my code? ( I have tested it with multiple examples and all would work fine, I'm just trying to find the ones I didn't think of)
Does my code have a good overall structure?

Points of interest:
src/crawler.c
#include "../headers/crawler.h"

int dircrawler(char* path, char* dest, int pathsize)
{
   // dirent variables and structures
   DIR* dp;
   struct dirent* entry;
   // buffers
   size_t bufsize;
   char *buf1, *buf2;
   buf1 = buf2 = NULL;
   struct cp_thr_args* args = NULL;

   if ((dp = opendir(path)) != NULL) {
      while ((entry = readdir(dp)) != NULL) {
         // skip over . and ..
         if (!(strcmp(entry->d_name, ".")) || !(strcmp(entry->d_name, "..")))
            continue;

         if (buf1 != NULL)
            free(buf1);
         if (buf2 != NULL)
            free(buf2);

         // printf("%s\n",entry->d_name);

         // buf1: absolute new path, buf2: relative destination path
         bufsize = snprintf(NULL, 0, "%s/%s", path, entry->d_name) + 1;
         mmalloc(&buf1, bufsize); // buf1
         snprintf(buf1, bufsize, "%s/%s", path, entry->d_name);

         bufsize = snprintf(NULL, 0, "%s%s/%s", dest, (path + pathsize - 1), entry->d_name) + 1;
         mmalloc(&buf2, bufsize); // buf2
         snprintf(buf2, bufsize, "%s%s/%s", dest, (path + pathsize), entry->d_name);

         if (entry->d_type == DT_DIR) {
            // make new directory in dest
            mkdir(buf2, 0755);
            if (dircrawler(buf1, dest, pathsize))
               closedir(dp);

         } else {
            // thread copying section
            int found = 1;
            while (1) { // ((Point of interest))
               // trying to find a non occupied thread
               // using status[]
               for (int i = 0; i < THREADCOUNT; ++i) {
                  if (status[i] == 1) {
                     cp_thr_init(&args, buf1, buf2, &status[i]);
                     pthread_create(&cpthr[i], NULL, cp_thr, (void*)args);
                     pthread_barrier_wait(&can_free);
                     cp_thr_free(args);
                     found = 0;
                     break;
                  }
               }
               if (!found)
                  break;
            }
         }
      }
      if (buf1 != NULL)
         free(buf1);
      if (buf2 != NULL)
         free(buf2);
      closedir(dp);
      return 0;
   }
}

src/threads.c
#include "../headers/threads.h"

int status[THREADCOUNT] = { 1, 1, 1, 1 };
pthread_mutex_t cp_lock = PTHREAD_MUTEX_INITIALIZER;

void* cp_thr(void* args)
{
   // extract args data before it gets rewritten
   struct cp_thr_args* temp = args;
   char* from;
   mmalloc(&from, return_size(temp->from) + 1);
   char* dest;
   mmalloc(&dest, return_size(temp->dest) + 1);
   int* status = temp->status;
   strcpy(from, temp->from);
   strcpy(dest, temp->dest);
   // send signal to release barrier and free args from crawl
   pthread_barrier_wait(&can_free); // ((Point of interest))

   // assign status to 0 to mark thread as occupied
   pthread_mutex_lock(&cp_lock);
   *status = 0;
   pthread_mutex_unlock(&cp_lock);

   copy_file(from, dest);

   free(from);
   free(dest);

   // assign status to 1 to mark thread as free to use
   pthread_mutex_lock(&cp_lock);
   *status = 1;
   pthread_mutex_unlock(&cp_lock);

   return (void*)0;
}


texts:
I've written the larger part of an emulator for a 6502 CPU but my method of op-code decoding is giving me concern, mainly because of how long the method is getting but also because I need a variable for each code, I need to declare them three times and I've stuck them all in a very non-OO class.  I wouldn't mind some scathing critique.

I've written it in a TDD fashion (in an effort to understand pure TDD) which has led to the simplest implementation with refactors only when necessary.  Even though I think this is probably the most efficient solution (making full use of the benefits of a switch statement), I'm thinking there's maybe a better way.

Extract:-

public void step() {
    System.out.println("\n*** STEP >>>");

    int accumulatorBeforeOperation = registers.getRegister(Registers.REG_ACCUMULATOR);
    int opCode = nextProgramByte();

    //Execute the opcode
    System.out.println("Instruction: " + InstructionSet.getOpCodeName(opCode) + "...");
    switch (opCode){
        case InstructionSet.OP_ASL_A: {
            int newFakeByte = registers.getRegister(Registers.REG_ACCUMULATOR) << 1;
            setCarryFlagBasedOn(newFakeByte);
            registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, newFakeByte);
        }
        break;

        case InstructionSet.OP_ASL_Z: {
            int location = nextProgramByte();
            int newFakeByte = memory.getByte(location) << 1;
            setCarryFlagBasedOn(newFakeByte);
            registers.setFlagsBasedOn(newFakeByte);
            memory.setByteAt(location, newFakeByte);
        }
        break;
        ...
        case InstructionSet.OP_DEY:
            registers.decrementRegisterWithFlags(Registers.REG_Y_INDEX);
            break;

        case InstructionSet.OP_LDX_I:
            registers.setRegisterAndFlags(Registers.REG_X_INDEX, nextProgramByte());
            break;

        case InstructionSet.OP_LDX_Z:
            registers.setRegisterAndFlags(Registers.REG_X_INDEX, getByteOfMemoryAt(nextProgramByte()));
            break;
        ...
        default:
            throw new UnknownOpCodeException("Unknown 6502 OpCode:" + opCode + " encountered.", opCode);
    }

Thoughts

I've looked at storing op-codes as Enums but it means reading bytes (in Javas case this is int represented bytes) and writing conversion code from raw byte to Enum but that seems unnecessary for the small maintainability improvement.

It seems excessive and not very OO to do it with a class per op-code.


texts: Looking for any enhancements to avoid a stackoverflow exception in a C# program

texts:
The program below results in a stackoverflow exception in C# for the input provided. I am trying to see if there are any enhancements that can be made to avoid the stack-overflow.

When using BFS approach the program works which is obvious as there's no recursion. The BFS approach is also provided below.

    public class NetworkDelayTimeDFS
    {
        Dictionary<int, int> visited;
        public int NetworkDelayTime(int[][] times, int N, int K)
        {
            var graph = new Dictionary<int, List<Tuple<int, int>>>();
            visited = new Dictionary<int, int>();

            foreach (var t in times)
            {
                if (graph.ContainsKey(t[0]))
                    graph[t[0]].Add(new Tuple<int, int>(t[1], t[2]));
                else graph.Add(t[0], new List<Tuple<int, int>> { new Tuple<int, int>(t[1], t[2]) });
            }

            var keys = graph.Keys.ToList();
            foreach (var key in keys)
            {
                graph[key] = graph[key].OrderBy(u => u.Item2).ToList();
            }

            for (int node = 1; node <= N; ++node)
                visited.Add(node, Int32.MaxValue);

            DFS(graph, K, 0);

            var maxTimeTaken = 0;
            foreach (var item in visited.Values)
            {
                if (item == Int32.MaxValue) return -1;
                maxTimeTaken = Math.Max(maxTimeTaken, item);
            }

            return maxTimeTaken;
        }

        private void DFS(Dictionary<int, List<Tuple<int, int>>> graph, int destNode, int time)
        {
            if (visited[destNode] < time)
                return;

            visited[destNode] = time;
            if (graph.ContainsKey(destNode))
            {
                var neighbours = graph[destNode];
                foreach (var neighbour in neighbours)
                {
                    DFS(graph, neighbour.Item1, time + neighbour.Item2);
                }
            }
        }
    }

Here is the link to the test for which the program encounters Stackoverflow exception:

https://github.com/AashishUpadhyay/Codesthenics/blob/master/UnitTestProject/NetworkDelayTimeTests.cs

Check test named TestMethod5

BFS:

  public class NetworkDelayTimeBFS
    {
        public int NetworkDelayTime(int[][] times, int N, int K)
        {
            var visited = new Dictionary<int, int>();
            var graph = new Dictionary<int, List<Tuple<int, int>>>();
            foreach (var t in times)
            {
                if (graph.ContainsKey(t[0]))
                    graph[t[0]].Add(new Tuple<int, int>(t[1], t[2]));
                else graph.Add(t[0], new List<Tuple<int, int>> { new Tuple<int, int>(t[1], t[2]) });
            }

            var queue = new Queue<int>();
            visited.Add(K, 0);
            queue.Enqueue(K);
            while (queue.Count != 0)
            {
                var node = queue.Dequeue();
                if (graph.ContainsKey(node))
                {
                    foreach (var neighbour in graph[node])
                    {
                        if (!visited.ContainsKey(neighbour.Item1) ||
                            visited[neighbour.Item1] > visited[node] + neighbour.Item2)
                        {
                            if (visited.ContainsKey(neighbour.Item1))
                                visited[neighbour.Item1] = visited[node] + neighbour.Item2;
                            else visited.Add(neighbour.Item1, visited[node] + neighbour.Item2);
                            queue.Enqueue(neighbour.Item1);
                        }
                    }
                }

            }

            return visited.Count == N ? visited.Max(v => v.Value) : -1;
        }
    }
```


texts:
I want to write a Python script where the input is a genotype (e.g. "CCDd") based upon the following Punnett square. The output should be the phenotype (e.g. "seal").

My code works, but doesn't look that 'pythonic' at all.

def colour(input):

    if len(set(input)) == 2 and input[0] != 'C' and input[2] != 'D':
        return('lilac')
    elif len(set(input[2::])) == 1 and input[2] != 'D':
        return('blue')
    elif len(set(input[0:2])) == 1 and input[0] != 'C':
        return('chocolate')
    else:
        return('seal')


texts:
I want to test my CRUD operation to a MySql database (I use dapper as my ORM).
This is what I wrote with xUnit:
    private IPaymentRepository paymentRepository;
    private Payment testPayment;
    private string connectionString = "Database=..."; //Test DB

    public PaymentRepositoryTest()
    {
        paymentRepository = new PaymentRepository(connectionString);
        //My model has private setters so I have a builder to initialize the object.
        testPayment = new Payment.Builder()
            .Id(0)
            .Description("Test")
            .Type(1)
            .WithPercentageDiscount(10)
            .WithAdvancePercentageDiscount(0)
            .WithInstallments(new int[] { 30 }).Build;
    }

CREATE
[Fact]
    public void Insert_Payment_ReturnId()
    {
        long id = 0;
        using(var transaction = new TransactionScope())
        {
            id = paymentRepository.Insert(testPayment);
        }

        Assert.True(id > 0);
    }

READ
[Fact]
    public void Get_Payment_ReturnPaymentFromDb()
    {
        using (var transaction = new TransactionScope())
        {
            long id = paymentRepository.Insert(testPayment);
            var payment = paymentRepository.GetById(id);

            Assert.NotNull(payment);
        }
    }

UPDATE
I don't really like this code, having private setter here is unfortunate because I have to recreate the object. I'm also not really sure about checking only one field.
    public void Update_Payment()
    {
        long id = 0;

        const string UPDATED_DESCRIPTION = "Test2";

        using (var transaction = new TransactionScope())
        {
            id = paymentRepository.Insert(testPayment);

            var updatedPayment = new Payment.Builder()
            .Id(id)
            .Description(UPDATED_DESCRIPTION)
            .Type(1)
            .WithPercentageDiscount(10)
            .WithAdvancePercentageDiscount(0)
            .WithInstallments(new int[] { 30 }).Build();

            paymentRepository.Update(updatedPayment);

            updatedPayment = paymentRepository.GetById(id);

            Assert.Equal(UPDATED_DESCRIPTION, updatedPayment.Description);
        }
    }

DELETE
Just like the update, I don't like having to recreate the object just to have the proper ID.
[Fact]
    public void Delete_Payment_ReturnNull()
    {
        using (var transaction = new TransactionScope())
        {
            long id = paymentRepository.Insert(testPayment);

            var paymentToDelete = new Payment.Builder()
            .Id((int)id)
            .Description("Test")
            .Type(1)
            .WithPercentageDiscount(10)
            .WithAdvancePercentageDiscount(0)
            .WithInstallments(new int[] { 30 }).Build();

            paymentRepository.Delete(paymentToDelete);

            var payment = paymentRepository.GetById(id);

            Assert.Null(payment);
        }
    }

The code of course works and I get the proper results, but I feel I'm repeating basically the same test over and over especially in Update and Delete.
Is this integration code good ? How can I make it better ?


texts:
I'm working on a personal project to practice my programming skills and I came to this problem. I tried to create a program that will find the missing number in a array.

I'm looking forward to upgrading this program and am trying to find the missing numbers in a array. Yes, with an 's'.

/********************************
*A sample program that will solve
*for a missing integer in a given sorted array.
********************************/

public class MissingInteger{

  public static void PrintArray(){
    int []fArrayDuplicate = {1,2,3,4,5,7,8,9,10};
    System.out.println("\nGiven the incomplete array:");
    System.out.print("[");
      for(int a = 0 ; a<fArrayDuplicate.length ; a++)
        System.out.print(" " + fArrayDuplicate[a] + " ");
    System.out.print("]");
    }

  public static void FindMissing(){
    int []finalArray = {1,2,3,4,5,7,8,9,10};
    int len = finalArray.length; //First, I took the length of the array.
    int sum = 0;
      for(int x=0;x<len;x++)
         sum+=finalArray[x]; //Second, I took the sum of the given array.
    int totalNumber = ((len + 1) * (len + 2)) / 2; //Third, I used this formula to get the total number.
    int missingInt = totalNumber - sum; // Fourth, I subtract the sum to total number to get missing integer.
    System.out.println("\nTherefore, the missing integer is " + missingInt + ".");
 }

  public static void main(String[] args){
      PrintArray();
      FindMissing();
    }
}


texts:
I am running this query and it takes several minutes to complete.  How can I tune it (unfortunately I don't have the privileges to run an SQL tuning advisor)?

select 'Master' || d.ntt_id || '_' || d.deal_nummas, p.prof_currency,
sum(p.prof_ts1), sum(p.prof_ts2), sum(p.prof_ts3), sum(p.prof_ts4), sum(p.prof_ts5),
sum(p.prof_ts6), sum(p.prof_ts7), sum(p.prof_ts8), sum(p.prof_ts9), sum(p.prof_ts10),
sum(p.prof_ts11), sum(p.prof_ts12), sum(p.prof_ts13), sum(p.prof_ts14), sum(p.prof_ts15),
sum(p.prof_ts16), sum(p.prof_ts17), sum(p.prof_ts18), sum(p.prof_ts19), sum(p.prof_ts20),
sum(p.prof_ts21), sum(p.prof_ts22), sum(p.prof_ts23), sum(p.prof_ts24), sum(p.prof_ts25),
sum(p.prof_ts26), sum(p.prof_ts27), sum(p.prof_ts28), sum(p.prof_ts29), sum(p.prof_ts30),
sum(p.prof_ts31), sum(p.prof_ts32), sum(p.prof_ts33), sum(p.prof_ts34), sum(p.prof_ts35),
sum(p.prof_ts36), sum(p.prof_ts37), sum(p.prof_ts38), sum(p.prof_ts39), sum(p.prof_ts40),
sum(p.prof_ts41), sum(p.prof_ts42), sum(p.prof_ts43), sum(p.prof_ts44), sum(p.prof_ts45),
sum(p.prof_ts46), sum(p.prof_ts47), sum(p.prof_ts48), sum(p.prof_ts49), sum(p.prof_ts50),
sum(p.prof_ts51), sum(p.prof_ts52), sum(p.prof_ts53), sum(p.prof_ts54), sum(p.prof_ts55),
sum(p.prof_ts56), sum(p.prof_ts57) from profiles p
join deals d on d.deal_id = p.deal_id and d.deal_scope='Y'
join runs r on r.deal_cnt_id = d.deal_cnt_id
where r.run_id=7 and d.deal_nummas!=0 and d.deal_nummas is not null
group by d.ntt_id, d.deal_nummas, p.prof_currency;

Some explanation on what I am doing:

I want to compute the sum on each timestep of a deal's profile, with deals being grouped by the node they belong to (identified by their deal_nummas). I only take into account deals which are in scope, and in the specified run.

The execution plan:

SELECT STATEMENT                                                                                3540470
    |_ HASH                                                                 GROUP BY            3540470
        |_ HASH JOIN                                                                            2957025
        |   |_ Access Predicates
        |   |   |_ D.DEAL_ID = P.DEAL_ID
        |   |_ HASH JOIN                                                                        624679
        |       |_ Access Predicates
        |       |   |_ R.DEAL_CNT_ID = D.DEAL_CNT_ID
        |       |_ TABLE ACCESS                                 RUNS        BY INDEX ROWID      1
        |       |   |_ INDEX                                    PK_RUN_ID   UNIQUE SCAN         0
        |       |       |_ Access Predicates
        |       |           |_ R.RUN_ID = 7
        |       |_ TABLE ACCESS                                 DEALS       FULL                624091
        |           |_ Filter Predicates
        |               |_ AND
        |                   |_ D.DEAL_SCOPE = 'Y'
        |                   |_ TO_NUMBER(D.DEAL_NUMMAS) <> 0
        |                   |_ D.DEAL_NUMMAS IS NOT NULL
        |_ TABLE ACCESS                                         PROFILES    FULL                922142

The table profiles stores what we could call curves, each with an identifier and 57 points (y-axis values), the columns being the x-axis values.


texts: Find the value nearest to k in the sorted array

texts:
Given a sorted array, return the 'closest' element to the input 'x'.

I do understand the merits of unit testing in separate files, but I deliberately added it to the main method for personal convenience, so don't consider that in your feedback.

I'm looking for request code review, optimizations and best practices.

public final class ClosestToK {

    private ClosestToK() { }

    /**
     * Given a sorted array returns the 'closest' element to the input 'x'.
     * 'closest' is defined as Math.min(Math.abs(x), Math.abs(y))
     *
     * Expects a sorted array, and if array is not sorted then results are unpredictable.
     *
     * If two values are equi-distant then the greater value is returned.
     *
     * @param a  The sorted array a
     * @return   The nearest element
     */
    public static int getClosestK(int[] a, int x) {

        int low = 0;
        int high = a.length - 1;

        while (low <= high) {
            int mid = (low + high) / 2;

            // test lower case
            if (mid == 0) {
                if (a.length == 1) {
                    return a[0];
                }

                return Math.min(Math.abs(a[0] - x), Math.abs(a[1] - x)) + x;
            }

            // test upper case
            if (mid == a.length - 1) {
                return a[a.length - 1];
            }

            // test equality
            if (a[mid] == x || a[mid + 1] == x) {
                return x;
            }

            // test perfect range.
            if (a[mid] < x  && a[mid + 1] > x) {
                return Math.min(Math.abs(a[mid] - x), Math.abs(a[mid + 1] - x)) + x;
            }

            // keep searching.
            if (a[mid] < x) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }

        throw new IllegalArgumentException("The array cannot be empty");
    }

    public static void main(String[] args) {
        // normal case.
        int[] a1 = {10, 20, 30, 40};
        assertEquals(30, getClosestK(a1, 28));

        // equidistant
        int[] a2 = {10, 20, 30, 40};
        assertEquals(30, getClosestK(a2, 25));

        // edge case lower boundary
        int[] a3 = {10, 20, 30, 40};
        assertEquals(10, getClosestK(a3, 5));
        int[] a4 = {10, 20, 30, 40};
        assertEquals(10, getClosestK(a4, 10));

        // edge case higher boundary
        int[] a5 = {10, 20, 30, 40};
        assertEquals(40, getClosestK(a5, 45));
        int[] a6 = {10, 20, 30, 40};
        assertEquals(40, getClosestK(a6, 40));

        // case equal to
        int[] a7 = {10, 20, 30, 40};
        assertEquals(30, getClosestK(a7, 30));

    }
}


texts: Matrix problem, the path that is the flattest

texts:
So in this problem I am given an NxN matrix, in which each value of the matrix represents an altitude. I need to find the best path from the top-left corner to the bottom-right one, my moves being limited to down and right.
Also, the path needs to be chosen in such way that the differences in altitude are the smallest, basically finding the path that has the smallest sum of differences in altitude.
I think I am using dynamic programming in my solution.(I am still a beginner, I am not so sure of this)

First I begin by creating another matrix that has the sums of the differences in altitude of the edges of the matrix, being the easiest to calculate because there is a single way that those sums can be computed. (S is the new matrix, while A is the matrix that is given)

 S[0][0]=0;
 for(int i=1;i<=n-1;i++)
        {S[0][i]=S[0][i-1]+abs(A[0][i]-A[0][i-1]);
        S[i][0]=S[i-1][0]+abs(A[i][0]-A[i-1][0]);}

Secondly, I am traversing the matrix by comparing the sums of the already calculated paths(the edges at first)+ the two ways (up or down). Whichever one is smallest, will be put in the new matrix.

for(int i=1;i<=n-1;i++)
    for(int j=1;j<=n-1;j++)
        if(S[i-1][j]+abs(A[i][j]-A[i-1][j])<S[i][j-1]+abs(A[i][j]-A[i][j-1]))
                S[i][j]=S[i-1][j]+abs(A[i][j]-A[i-1][j]);
        else
                S[i][j]= S[i][j-1]+abs(A[i][j]-A[i][j-1]);

This problem worked for the examples that I tried, but I am wondering if there is a more efficient way. Also, i could have made a mistake (or many :) ), so please feel free to tell me if you think it is a good solution, a bad one and if you have any advice for me.

Thank you for the attention anyways!

The complete code:

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
ifstream fin("data.in");
ofstream fout("data.out");

int A[21][21],n,S[21][21],D[42][4];

int main()
{   //reading the matrix
    fin>>n;
    for(int i=0;i<=n-1;i++)
        for(int j=0;j<=n-1;j++)
            fin>>A[i][j];
    //computing the edges of the new matrix
    S[0][0]=0;
    for(int i=1;i<=n-1;i++)
        {S[0][i]=S[0][i-1]+abs(A[0][i]-A[0][i-1]);
        S[i][0]=S[i-1][0]+abs(A[i][0]-A[i-1][0]);}
    //comparing the sums
    for(int i=1;i<=n-1;i++)
        for(int j=1;j<=n-1;j++)
            if(S[i-1][j]+abs(A[i][j]-A[i-1][j])<S[i][j-1]+abs(A[i][j]-A[i][j-1]))
                S[i][j]=S[i-1][j]+abs(A[i][j]-A[i-1][j]);
            else
                S[i][j]= S[i][j-1]+abs(A[i][j]-A[i][j-1]);

//a new matrix to identify the path and memorize the down/right moves
    int i,j,x;
    i=n-1;
    j=n-1;
    x=1;
    D[0][0]=A[n-1][n-1];
    while(i!=0&&j!=0)
    {if(S[i-1][j]<S[i][j-1])
        {
        D[x][0]=A[i-1][j];
        D[x][1]=1;   //1 for down
        x++;
        i=i-1;}
    else
    {
        D[x][0]=A[i][j-1];
        D[x][1]=2;    //2 for right
        x++;
        j=j-1;
    }}
    if(S[1][0]>S[0][1])
        D[x][1]=2;
    else
        D[x][1]=1;
    D[x][0]=A[0][0];

 //showing the path
fout<<"The path:"<<endl;
    for(i=x;i>=0;i--)
        { fout<<endl<<D[i][0];
        if(i!=0)
           {if(D[i][1]==1)
                fout<<endl<<"down";
            else
                if(D[i][1]==2)
                fout<<endl<<"right";}
        }

    return 0;
}


texts: Scale object based on distance between 2 vertices

texts:
I made this script so that I can scale objects for 3D printing from Maya.
I had fun making it and I'm sure it could be cleaned up or improved. If it can be cleaned up please let me know.

##  ((Ax - Bx)**2 + (Ay - By)**2 + (Az - Bz)**2)**0.5

import maya.cmds as mc

def defineParameters():
    selPoints = mc.ls(sl = True)
    objName = selPoints[0].split('.')[0]
    print objName
    vtxCoordList = mc.xform(selPoints, q = True, translation = True, ws = True)
    Ax, Ay, Az = vtxCoordList[:-3]
    Bx, By, Bz = vtxCoordList[3:]
    d = float(((Ax - Bx)**2 + (Ay - By)**2 + (Az - Bz)**2)**0.5) #direct distance between both points
    return d

def getDist():
    d = defineParameters()
    #selPoints = mc.ls(sl = True)

    #vtxCoordList = mc.xform(selPoints, q = True, translation = True, ws = True)
    #Ax, Ay, Az = vtxCoordList[:-3]
    #Bx, By, Bz = vtxCoordList[3:]
    #d = float(((Ax - Bx)**2 + (Ay - By)**2 + (Az - Bz)**2)**0.5) #direct distance between both points
    '''
    dx = ((Ax - Bx)**2)**0.5
    print "Distance on X axis is: {0}".format(dx) #distance on X axis
    dy = ((Ay - By)**2)**0.5
    print "Distance on Y axis is: {0}".format(dy) #distance on Y axis
    dz = ((Az - Bz)**2)**0.5
    print "Distance on Z axis is: {0}".format(dz) #distance on Z axis
    '''
    mc.textFieldButtonGrp("currentLength", edit = True, tx = "{0}".format(d))
    print "the distance between points is {0}".format(d)
    return d

def refreshScaleFactor(sf):
    userInput = sf
    scaleFactor = (float(sf))/(float(d))
    print "dist btwn pnts is d: {0} ".format(d)
    print "sf is {0}".format(sf)
    print "user input is {0}".format(userInput)
    print "scale factor is {0}".format(scaleFactor)
    print "-"*10
    return float(scaleFactor)

## scale object to match measurement
def scaleDist():
    b = (float(mc.textFieldButtonGrp("desiredLength",q = True, tx = True))) / defineParameters()
    mc.makeIdentity(objName, apply = True, t = 1, r = 1, s = 1, n = 0, pn = 1)#freeze transformations
    mc.DeleteAllHistory()
    mc.scale(float(b), float(b), float(b), objName)
    print "you scaled by {0}".format(b)
    mc.makeIdentity(objName, apply = True, t = 1, r = 1, s = 1, n = 0, pn = 1)#freeze transformations

defineParameters()

## window
mc.window("Distance Tool", t = "Distance Tool")
mc.rowColumnLayout(numberOfColumns = 2, columnAttach = (1, 'left', 0), columnWidth = [(1,100), (2,300)])
mc.text(l = "Current length")
currentLength = mc.textFieldButtonGrp("currentLength", ed = False, tx = "{0}".format(d), buttonLabel = "Refresh", bc = getDist)

mc.text(l = "Desired length")
desiredLength = mc.textFieldButtonGrp("desiredLength", buttonLabel = "Scale",  bc = scaleDist, tcc = refreshScaleFactor )
mc.showWindow()


texts: A config file handler I made for a game with Monogame

texts:
The reason I used fields instead of automatic properties is because I am using tryparse which can not use properties... I know the Title setting could have been an automatic property but I decided to go with consistency and create a field for it. Is it ok to do so?

Do you see anything else that could go wrong?

Is it ok to format string the way I did in this file?

I do plan on adding a lot more settings in this file.

internal class Configurator
{
    private Game1 _game;

    // The error message to display if the config file can not load settings properly.
    private string ErrorMessage = ("Config file corrupted, {0} could not be loaded properly. {0} will be set to default");

    private readonly XmlDocument _document = new XmlDocument();
    private XmlNode _node;

    private int _windowWidth;
    private int _windowHeight;
    private string _title;
    private bool _allowAltF4;
    private bool _isMouseVisible;

    // The default values will be loaded if the config file can not be loaded.
    public Configurator(Game1 game)
    {
        _game = game;
        _windowWidth = 960;
        _windowHeight = 540;
        _title = "Title";
        _allowAltF4 = true;
        _isMouseVisible = true;
    }

    public int WindowWidth
    {
        get => _windowWidth;
        set => _windowWidth = value;
    }

    public int WindowHeight
    {
        get => _windowHeight;
        set => _windowHeight = value;
    }

    public string Title
    {
        get => _title;
        set => _title = value;
    }

    public bool AllowAltF4
    {
        get => _allowAltF4;
        set => _allowAltF4 = value;
    }

    public bool IsMouseVisible
    {
        get => _isMouseVisible;
        set => _isMouseVisible = value;
    }

    public void LoadSettings(string configFilePath)
    {
        _document.Load(configFilePath);

        {
            // Window width
            _node = _document.SelectSingleNode("Settings/Window/Dimensions/Width");
            if (_node == null || !int.TryParse(_node?.InnerText, out _windowWidth))
                Logger.Log(string.Format(ErrorMessage, "WindowWidth"), LoggerType.Error);

            // Window height
            _node = _document.SelectSingleNode("Settings/Window/Dimensions/Height");
            if (_node == null || !int.TryParse(_node?.InnerText, out _windowHeight))
                Logger.Log(ErrorMessage, LoggerType.Error);

            // Title
            _node = _document.SelectSingleNode("Settings/Window/Title");
            if (_node != null)
                _title = _document.SelectSingleNode("Settings/Window/Title")?.InnerText;
            else Logger.Log(ErrorMessage, LoggerType.Error);

            // Allow Alt F4
            _node = _document.SelectSingleNode("Settings/Window/AllowAltF4");
            if (_node == null || !bool.TryParse(_node?.InnerText, out _allowAltF4))
                Logger.Log(ErrorMessage, LoggerType.Error);

            // Is mouse visible
            _node = _document.SelectSingleNode("Settings/Mouse/IsVisible");
            if (_node == null || !bool.TryParse(_node?.InnerText, out _isMouseVisible))
                Logger.Log(ErrorMessage, LoggerType.Error);
        }
    }

    public void ApplySettings()
    {
        _game.GraphicsDeviceManager.PreferredBackBufferWidth = _windowWidth;
        _game.GraphicsDeviceManager.PreferredBackBufferHeight = _windowHeight;
        _game.Window.Title = _title;
        _game.Window.AllowAltF4 = _allowAltF4;
        _game.IsMouseVisible = _isMouseVisible;
    }
}

}


texts:
I'm making a really simple html website with CSS and I was hoping on some feedback. A few notes:

There will be more content under this, but I want the starting screen to take up the full page and then scroll under it.
I've used a bit of a hack to remove the padding from the first list element
I've used a bit of a hack to remove spacing between list elements
I'm a bit unsure if I have to clear floats for the menu bar as it has no height at the moment. If so, clear:float didn't seem to work.

* {
  padding: 0;
  margin: 0;
}
html,
body {
  height: 100%;
}
a {
  text-decoration: none;
}
.header {
  height: 100%;
  width: 100%;
  background: lightgray;
  position: relative;
  text-align: center;
  min-height: 350px;
}
li {
  list-style: none;
}
.nav {
  display: block;
  padding: 20px;
}
.nav img {
  float: left;
}
.nav ul {
  float: right;
  font-size: 0;
}
.nav ul li {
  display: inline-block;
  font-size: 16px;
  padding-left: 10px;
}
.nav ul li:first-child {
  padding-left: 0px
}
.nav ul li a {
  padding: 0 10px;
}

Services

Contact

    Hello!

Test


texts: Refactoring a function to return all scores above a certain threshold

texts:
I am currently learning JavaScript and wanted to fellow coders to review a function that I had written. I am looking for feedback particularly on:

Whether I have followed best practice and JavaScript conventions
Any suggestion on doing it better.

Things I know I need to implement but don't know how:

Validate if array values are numbers

Purpose of function: Return all scores above a certain threshold. Function accepts two arguments. First is an array of scores and second argument is the threshold.

My code:

UPDATED code after putting it through JS lint - I have ignored some erros like moving vars in the loops to the top or not declaring vars in the for loop etc (before JSLint code is here http://jsbin.com/UtOMAyU/1/)

function scoresAbove(scoresArg, thresholdArg) {
    "use strict";
    var output = [],
        nums = scoresArg,
        threshold = thresholdArg;
    //check if scores Arg provided is an array
    if (typeof nums !== "object" || !nums.hasOwnProperty('length')) {
        return "Error: Number(s) not in the expected format. Please provid number(s) in an array format";
    }else if (typeof threshold !== "number") { //check if threshold Arg provided is an array
        return "Error: Threshold number not in the expected format. Please provid a threshold";
    }
    for (var i = 0, len = nums.length; i < len; i++) {
        var currentNum = nums[i];
        if (currentNum > threshold) {
            output.push(currentNum);
        }
    }
    //What to return from func
    if (output == "") {
        return "No scores were above the " + " threshold you set as " + threshold;
    }
    return "The following scores were above the threshold: " + output.join(", ");
}


texts:
I am very new to Laravel. I am building a website where multiple users can have one or more roles. I have a users table and a user_roles table. Each user_roles column has a user_id and an enum field where they can be a "referee", "coach", or "player". Whenever I want to check if the User is a certain member of a role I call a referee, coach, or player function in my model from the controller. Is my structure and code efficient, or is there any way to clean it up?

User.php

public function roles()
{
    return $this->hasMany('App\Role');
}

public function getRoles()
{
    $roles_collection = $this->roles;
    $roles = [];
    foreach ($roles_collection as $role) {
        $roles[] = $role['role'];
    }
    return $roles;
}

public function referee()
{
    if (in_array('referee', $this->getRoles())) {
        return true;
    } else {
        return false;
    }
}

public function player()
{
    if (in_array('player', $this->getRoles())) {
        return true;
    } else {
        return false;
    }
}

public function coach()
{
    if (in_array('coach', $this->getRoles())) {
        return true;
    } else {
        return false;
    }
}

Example of checking the User role, called from the controller:

if (Auth::user()->referee()) {
       echo 'referee';
}


texts:
Question 7 from Lab 3 of Berkeley's CS61A course says:

The following examples of recursive functions show some examples of common recursion mistakes. Fix them so that they work as intended. [...]
def even_digits(n):
    """Return the percentage of digits in n that are even.

    >>> even_digits(23479837) # 3 / 8
    0.375
    """
    if n == 0:
        return num_digits / num_evens
    num_digits, num_evens = 0, 0
    if n % 2 == 0:
        counter += 1
    num_evens += 1
    return (even_digits(n // 10) + num_evens) / counter

As per the assignment, below code is suppose to solve this problem, recursively (MUST not be non-recursive).
def even_digits(n, count_even = 0, count = 0):
    """Return the percentage of digits in n that are even.

    >>> even_digits(23479837) # 3 / 8
    0.375
    """
    if n == 0:
        return count_even / count
    if (n % 2) == 0:
        return even_digits(n // 10, count_even + 1, count + 1)
    else:
        return even_digits(n // 10, count_even, count + 1)

Is this code readable? Can we improve this solution?


texts:
Here is a Bitcoin address validator I am looking to have reviewed in C.  Normally I would have the enum and function prototypes declared in a header file, but I decided for the purpose of this question to integrate them into one for easy copying and compilation.

/**
 * @file bitcoin.c
 * @brief Bitcoin address validation
 */

#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>

typedef enum {VALID, BAD_CHAR, BAD_LENGTH, BAD_DIGEST} BitcoinAddressState;

/**
 * @fn BitcoinAddressState unbase58(const char *s, unsigned char *out)
 * @brief Takes a base58 encoded address and decodes it into the receiver. Errors are returned if the argument is not valid base58 or if the decoded value does not fit in the 25 byte address.
 * @param addr The Bitcoin address
 * @param out The receiver of the decoded address
 * @return The state of decoding the Bitcoin address
 */
BitcoinAddressState unbase58(const char *addr, unsigned char *out)
{
    /* A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters 0, O, I and l. */
    const char *tmpl = "123456789"
                       "ABCDEFGHJKLMNPQRSTUVWXYZ"
                       "abcdefghijkmnopqrstuvwxyz";
    const char *p;

    memset(out, 0, 25);
    for (int i = 0; addr[i]; ++i)
    {
        if (!(p = strchr(tmpl, addr[i]))) return BAD_CHAR;

        size_t c = p - tmpl;
        for (int j = 25; --j; )
        {
            c += 58 * out[j];
            out[j] = c % 256;
            c /= 256;
        }
        if (c) return BAD_LENGTH;
    }
    return VALID;
}

/**
 * @fn BitcoinAddressState validateAddress(const char *s)
 * @brief Takes a Bitcoin address as argument, and checks whether or not the address is valid.
 * @param addr The Bitcoin address
 * @return The state of the Bitcoin address
 */
BitcoinAddressState validateAddress(const char *addr)
{
    unsigned char dec[32];
    unsigned char d1[SHA256_DIGEST_LENGTH];
    unsigned char d2[SHA256_DIGEST_LENGTH];
    BitcoinAddressState val = unbase58(addr, dec);

    if (val) return val;

    SHA256(SHA256(dec, 21, d1), SHA256_DIGEST_LENGTH, d2);

    if (memcmp(dec + 21, d2, 4)) return BAD_DIGEST;

    return VALID;
}

int main (void) {
    const char *addresses[] =
    {
        "1EYDqUKuLKF9di1pSEtEfNA8pj2CgL7Wne", // my actual Bitcoin wallet address
        "1EYDqUKuLKF9di1pSEtEfNA8pj3CgL7Wne", // bad digest
        "1EYDqUKuLKF9di1pSEtEfNA8pj2CgL0Wne", // bad char
        "1EYDqUKuLKF9di1pSEtEfNA8pj2cgL7Wnef", // bad length
        0
    };
    for (int i = 0; addresses[i]; ++i)
    {
        printf("%s: ", addresses[i]);
        switch (validateAddress(addresses[i]))
        {
            case VALID:
                puts("Okay");
                break;
            case BAD_CHAR:
                puts("Invalid character in address");
                break;
            case BAD_LENGTH:
                puts("Address length is incorrect");
                break;
            case BAD_DIGEST:
                puts("Bad digest");
                break;
            default:
                puts("An unknown error occurred");
                break;
        }
    }
}


texts: Separating items into ordered and unordered lists

texts:
I'm trying to group all the types which have ordered-list-item & unordered-list-item into new object.

How can I simplify the function and reduce multiple return statements?

const data = {
  data: [{
    areas: [{
        sections: [{
          rjf: [{
              "type": "heading-1",
              "text": "A title",
            },
            {
              "type": "ordered-list-item",
              "text": "Ordered Item A",
            },
            {
              "type": "unordered-list-item",
              "text": "Ordered Item B",
            },
            {
              "type": "heading-1",
              "text": "A title",
            }
          ]
        }]
      },
      {
        sections: [{
          rjf: [{
              "type": "heading-1",
              "text": "Block 2 A title",
            },
            {
              "type": "ordered-list-item",
              "text": "Block 2 Ordered Item A",
            },
            {
              "type": "unordered-list-item",
              "text": "Block 2 Ordered Item B",
            },
            {
              "type": "heading-1",
              "text": "Block 2 A title",
            }
          ]
        }]
      }
    ]
  }]
};

function parseAreas() {
  data[0].areas.forEach(area => {
    this.moveToNewObject(area);
  })
}

function moveToNewObject(data) {
  const areas = data[0].areas;
  //console.log(data[0].areas)
  const listItemTypes = ['unordered-list-item', 'ordered-list-item'];
  return areas.map((area) => {
    var sec = area.sections;
    return sec.map((section) => {
      let lastHeadingIndex = -1;
      return section.rjf.reduce((acc, current, index) => {
        if (!current.type || !listItemTypes.includes(current.type)) {
          lastHeadingIndex = acc.length;
          return [...acc, current]
        } else {
          let listObject = acc.find((el, i) => i > lastHeadingIndex && i < index && el.type === 'list');
          if (!listObject) {
            listObject = {
              type: 'list',
              items: [current]
            }
            return [...acc, listObject];
          }
          listObject.items = [...listObject.items, current];
          return acc;
        }
      }, [])
    });
  });
}
console.log('sections', moveToNewObject(data.data));


texts:
I would like someone review this code and tell if it can be done better, or if the code is elegant and simple enough for the task at hand.

I used code climate and I got 4/4 and my test coverage is 96%, yet I would like a professional opinion about it.

'use strict';

var PromisePolyfill = require('promise');
var http = require('http');

var twitterCountURL = 'http://urls.api.twitter.com/1/urls/count.json?url=';

/**
 * Gets the numbers of tweets of a given url.
 * @param {string} validUrl - The url to query
 * @returns {Number} Number of tweets
*/
exports.getCount = function(validUrl) {
    return new PromisePolyfill(function(resolve, reject) {
        if (validUrl) {
            http.get(twitterCountURL + validUrl, function(res) {
                var body = '';
                res.on('data', function(chunk) {
                    body += chunk;
                });
                res.on('end', function() {
                    var twResponse = JSON.parse(body);
                    if (!twResponse.count) {
                        twResponse.count = 0;
                    }
                    // console.log(twResponse.count);
                    resolve(twResponse.count);
                });

            }).on('error', function(e) {
                reject(e.message);
            });

        }else {
            resolve(0);
        }
    });
};

And its respective test file:

'use strict';

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var sinon = require('sinon');
var http = require('http');
var PassThrough = require('stream').PassThrough;
var twitterCount = require('../../modules/twitterCount');

var response,
  responsePT;

chai.should();
chai.use(chaiAsPromised);

describe('twitterCount Module', function() {

    beforeEach(function(done) {
        response = new PassThrough();
        responsePT = new PassThrough();
        sinon.stub(http, 'get');
        done();
    });

    afterEach(function(done) {
        http.get.restore();
        done();
    });

    it('should return valid count when a valid url is passed', function(done) {
        var expected = {'count': 234453234, 'url': 'http:\/\/www.google.com\/'};

        response.write(JSON.stringify(expected));
        response.end();

        http.get.callsArgWith(1, response)
                .returns(responsePT);

        twitterCount.getCount('http://www.google.com').should.eventually.equal(234453234).notify(done);
    });

    it('should return 0 when a invalid url is passed', function(done) {
        var expected = {'count': 0, 'url': 'http:\/\/invalidurl.invalid\/'};

        response.write(JSON.stringify(expected));
        response.end();

        http.get.callsArgWith(1, response)
                .returns(responsePT);

        twitterCount.getCount('http://invalidurl.invalid').should.eventually.equal(0).notify(done);
    });

    it('should return 0 when an empty url is passed', function(done) {
        var expected = {'count': 0, 'url': ''};

        response.write(JSON.stringify(expected));
        response.end();

        http.get.callsArgWith(1, response)
                .returns(responsePT);

        twitterCount.getCount('').should.eventually.equal(0).notify(done);
    });
});


texts:
I'm unsure of how to Name and clearly distinguish between methods that deals with comparisons.

I know of the following two established concepts:

.Equals: A method to see if two objects refer to the same instance

.Compare: A method often used when determining sort order among objects

But what to name a method when you are interested to see if two different object instances refer to the same "logical" object, or when comparing values of two different object instances? Let me give you an example with a class named Photo.

public class Photo : IEquatable<Photo>
{
    public string FileName { get; private set; }
    public string InFolder { get; private set; }
    public string FullFilePath { get; private set; }
    public string FileExtension { get; private set; }
    public long FileSize { get; private set; }
    public DateTime FileLastModified { get; private set; }
    public DateTime FileCreated { get; private set; }
    public ExifData EXIF
    {
        get
        {
            if (this._exif == null)
                LoadExtendedProperties();
            return this._exif;
        }
        set { this._exif = value; }
    }
    public Photo(string fullFilePath)
    {
        //...
    }
    public override int GetHashCode()
    {
        return this.FullFilePath.GetHashCode();
    }
    private void LoadExtendedProperties()
    {
        //...
    }
    public bool Equals(Photo other)
    {
        if (object.ReferenceEquals(this, null) || object.ReferenceEquals(other, null))
            return false;
        if (object.ReferenceEquals(this, other))
            return true;
        else
            return false;
    }
    /// <summary>
    /// Do they refer to the same photo (file)
    /// </summary>
    public bool UnnamedCompareMethodA(Photo other)
    {
        if(object.ReferenceEquals(other, null))
            return false;
        if (this.FullFilePath == other.FullFilePath)
            return true;
        else
            return false;
    }
    /// <summary>
    /// Do all properties have the same value?
    /// Usefull when determining if a Photo has been modified since last loaded
    /// </summary>
    public bool UnnamedCompareMethodB(Photo other)
    {
        // Note: Instead of manually adding fields; Reflection might be a better choice.
        // Though that might bring other challenges as some fields should be left out when comparing.

        // If any object is null then they are NOT considered equal
        if (object.ReferenceEquals(this, null) || object.ReferenceEquals(other, null))
            return false;
        if (this.FileLastModified != other.FileLastModified)
            return false;
        if (this.FullFilePath != other.FullFilePath)
            return false;

        if (this.FileSize != other.FileSize)
            return false;
        if (this.EXIF.Title != other.EXIF.Title)
            return false;
        if (this.EXIF.Rating != other.EXIF.Rating)
            return false;
        if (this.EXIF.PictureTaken != this.EXIF.PictureTaken)
            return false;
        if (!this.EXIF.Orientation.Equals(other.EXIF.Orientation))
            return false;
        if (!this.EXIF.Dimensions.Equals(other.EXIF.Dimensions))
            return false;
        if (!this.EXIF.Location.Equals(other.EXIF.Location))
            return false;

        return true;
    }
}

Question:
What to name UnnamedCompareMethodA() and UnnamedCompareMethodB()? I would like to have "Equal" somewhere in the name but I feel like that would create confusion as they are not related at all with .Equals().


texts:
I have created this program and intend to implement it into basic card games that I create. I would like help cleaning up redundant code and overall, make it more concise. For example: I couldn't come up with a better solution for Player inheriting deck and putting card_list as a class variable for Deck. Any help would be appreciated.

import random

class Card():

    def __init__(self, value, suit):
        self.value = value
        self.suit = suit

    def show_card(self):
        print(str(self.value) + " of " + str(self.suit))

class Deck():

    card_list = []

    def __init__(self):
        self.construct_deck()
        self._playing_pile = []
        self._discard_pile = []

    def construct_deck(self):
        for s in ['Clubs', 'Diamonds', 'Hearts', 'Spades']:
            for v in ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']:
                self.card_list.append(Card(v, s))

    def show_deck(self):
        for card in self.card_list:
            card.show_card()

    def show_playing_pile(self):
        for card in self._playing_pile:
            card.show_card()

    def show_discard_pile(self):
        for card in self._discard_pile:
            card.show_card()

    def shuffle_deck(self):
        self.shuffled_cards = random.shuffle(self.card_list)

    def draw_card_from_deck(self):
        self._draw_from_deck = self.card_list.pop()
        return self._draw_from_deck

    def return_card_to_deck(self):
        self._return_to_deck = self.card_list.append(self._draw_from_deck)
        return self._return_to_deck

    def put_card_in_playing_pile(self):
        self._put_in_playing_pile = self._playing_pile.append(self._draw_from_deck)
        return self._put_in_playing_pile

    def put_card_in_discard_pile(self):
        self._put_in_discard_pile = self._discard_pile.append(self._draw_from_deck)
        return self._put_in_discard_pile

class Player(Deck):

    def __init__(self, name):
        self.name = name
        self._players_hand = []

    def player_draws_card_from_deck(self, deck):
        self._players_hand.append(deck.draw_card_from_deck())

    def player_returns_card_from_hand_to_deck(self, deck):
        self.card_list.append(self._players_hand.pop())

    def player_returns_card_from_playing_pile_to_deck(self, deck):
        self.card_list.append(self._playing_pile.pop())

    def player_returns_card_from_discard_pile_to_deck(self, deck):
        self.card_list.append(self._discard_pile.pop())

    def show_players_hand(self):
        for card in self._players_hand:
            card.show_card()


texts: Calculate the rates at which users get stuck at each stage

texts:
I completed an algorithm problem just as a personal study, and I can't help but feel like my solution is a bit needlessly complicated, although I can't figure out a better way to do it. Here's the problem :

  Given a number N, and a list of users currently on a stage, find out the failure rate of each stage up to N, and list the stages in descending order of failure rate. The failure rate is the percentage of users currently stuck on a stage, out of all the users who are currently playing the current stage or higher.

Example :
        stages = [2, 1, 2, 6, 2, 4, 3, 3], N = 5

There is 1 user currently playing stage 1, therefore out of the list of 8 users playing stage 1 or higher the failure rate of stage 1 is 1/8.
There are 3 users currently playing stage 2, therefore out of 7 users playing stage 2 or higher the failure rate is 3/7.
There are 2 users currently playing stage 3, therefore out of 4 users playing stage 3 or higher the failure rate is 2/4.
There is 1 user currently playing stage 4, therefore out of 2 users playing stage 4 or higher the failure rate is 1/2.
There are 0 users currently playing stage 5, therefore out of 1 users playing stage 5 or higher the failure rate is 0/1.

Therefore the result is : [3, 4, 2, 1, 5]

My solution :

public class StageFailureRate {
    private ArrayList<Integer> result;

    public StageFailureRate(int N, Integer[] stages) {
        result = new ArrayList<>();
        Map<Integer, Integer> usersOnStage = new HashMap<>();

        //count how many users are on each stage
        for (int stage : stages) {
            if (!usersOnStage.containsKey(stage)) {
                usersOnStage.put(stage, 1);
            } else {
                usersOnStage.put(stage, usersOnStage.get(stage) + 1);
            }
        }

        //compute the failure rate for each stage, up to N stages
        int total = stages.length;
        Map<Integer, Float> failureRates = new HashMap<Integer, Float>();
        float failureRate = 0;
        for (int i = 1; i <= N; ++i) {
            if (usersOnStage.containsKey(i)) {
                failureRate = (float) usersOnStage.get(i) / (float) total;
                total = total - usersOnStage.get(i);
            } else {
                failureRate = 0 / total;
            }
            failureRates.put(i, failureRate);
        }

        //Sort into descending order and get the result.
        Map<Integer, Float> sortedMap = sortByValue(failureRates);

        for (Map.Entry<Integer, Float> entry : sortedMap.entrySet()) {
            result.add(entry.getKey());
        }
    }

    public ArrayList<Integer> getResult() {
        return result;
    }

    private static Map<Integer, Float> sortByValue(Map<Integer, Float> unsortedMap) {
        List<Map.Entry<Integer, Float>> list =
                new LinkedList<Map.Entry<Integer, Float>>(unsortedMap.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<Integer, Float>>() {
            public int compare(Map.Entry<Integer, Float> o1,
                               Map.Entry<Integer, Float> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });

        Map<Integer, Float> sortedMap = new LinkedHashMap<Integer, Float>();
        for (Map.Entry<Integer, Float> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
       }
        return sortedMap;
    }
}

This solution is correct. Do you think it's the most optimal solution or could this be optimized to be much faster?


texts:
I'm relatively new to Java and decided to make a Memory Match game.

Card.java:

import javax.swing.JButton;

@SuppressWarnings("serial")
public class Card extends JButton{
    private int id;
    private boolean matched = false;

    public void setId(int id){
        this.id = id;
    }

    public int getId(){
        return this.id;
    }

    public void setMatched(boolean matched){
        this.matched = matched;
    }

    public boolean getMatched(){
        return this.matched;
    }
}

Board.java:

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

@SuppressWarnings("serial")
public class Board extends JFrame{

    private List<Card> cards;
    private Card selectedCard;
    private Card c1;
    private Card c2;
    private Timer t;

    public Board(){

        int pairs = 10;
        List<Card> cardsList = new ArrayList<Card>();
        List<Integer> cardVals = new ArrayList<Integer>();

        for (int i = 0; i < pairs; i++){
            cardVals.add(i);
            cardVals.add(i);
        }
        Collections.shuffle(cardVals);

        for (int val : cardVals){
            Card c = new Card();
            c.setId(val);
            c.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent ae){
                    selectedCard = c;
                    doTurn();
                }
            });
            cardsList.add(c);
        }
        this.cards = cardsList;
        //set up the timer
        t = new Timer(750, new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                checkCards();
            }
        });

        t.setRepeats(false);

        //set up the board itself
        Container pane = getContentPane();
        pane.setLayout(new GridLayout(4, 5));
        for (Card c : cards){
            pane.add(c);
        }
        setTitle("Memory Match");
    }

    public void doTurn(){
        if (c1 == null && c2 == null){
            c1 = selectedCard;
            c1.setText(String.valueOf(c1.getId()));
        }

        if (c1 != null && c1 != selectedCard && c2 == null){
            c2 = selectedCard;
            c2.setText(String.valueOf(c2.getId()));
            t.start();

        }
    }

    public void checkCards(){
        if (c1.getId() == c2.getId()){//match condition
            c1.setEnabled(false); //disables the button
            c2.setEnabled(false);
            c1.setMatched(true); //flags the button as having been matched
            c2.setMatched(true);
            if (this.isGameWon()){
                JOptionPane.showMessageDialog(this, "You win!");
                System.exit(0);
            }
        }

        else{
            c1.setText(""); //'hides' text
            c2.setText("");
        }
        c1 = null; //reset c1 and c2
        c2 = null;
    }

    public boolean isGameWon(){
        for(Card c: this.cards){
            if (c.getMatched() == false){
                return false;
            }
        }
        return true;
    }

}

Game.java:

import java.awt.Dimension;
import javax.swing.JFrame;

public class Game{
    public static void main(String[] args){
        Board b = new Board();
        b.setPreferredSize(new Dimension(500,500)); //need to use this instead of setSize
        b.setLocation(500, 250);
        b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        b.pack();
        b.setVisible(true);
    }
}

The code compiles and the game works, which is fine, but how could I improve, if at all, from a stylistic perspective? If it helps, before Java I worked in primarily Python and C.


texts:
class InvitationConfirmationValidator < ActiveModel::Validator
  def validate(record)
    invitation = Invitation.find_by_url_suffix(record.id)
    if invitation
      if invitation.materialized?
        record.erros.clear
        record.errors[:base] << "Invitation already materialized"
      end
    else
      record.erros.clear
      record.errors[:base] << "Invitation does not exist"
    end
  end
end

The above is the code for a Validator. It first checks if an invitation with an ID exists. If it does, it checks whether it has already been used.

The code seems to me more complex than it should be to achieve this simple task. Can its complexity be reduced?


texts:
I'm new in LINQ and Lambda expression. I'm not sure is there a way to shorten the result on this o.z.cust.cust.cust.bintAccountNo.  As you can see below, the more table needed to join the longer the resultselector cust.cust.cust.  Is there better way to shorten this Lambda expression's result selector?

POCO

public class Tbl1
 {
        [Key]
        public long bintAccountNo{ get; set; }
 }

 public class Tbl2
 {
        [Key]
        public int id { get; set; }
        public long bintAccountNo{ get; set; }
 }

 public class Tbl3
 {
        [Key]
        public int id { get; set; }
        public long bintAccountNo{ get; set; }
 }

 public class Tbl4
 {
        [Key]
        public int id { get; set; }
        public long bintAccountNo{ get; set; }
        public int intPartner{ get; set; }
 }

 public class Tbl5
 {
        [Key]
        public int id { get; set; }
        public int intPartner{ get; set; }
 }

var b = (Tbl1
.GroupJoin(Tbl2, cust => cust.bintAccountNo, cust2 => cust2.bintAccountNo, (cust, cust2) => new  { cust = cust, cust2 = cust2 })
.SelectMany(cust => cust.cust2.DefaultIfEmpty(), (cust, cust2) => new { cust = cust.cust, cust2 = cust2 })
.GroupJoin(Tbl3, c => c.cust.bintAccountNo, cust3 => cust3.bintAccountNo, (cust, cust3) => new { cust = cust, cust3 = cust3 })
.SelectMany(c => c.cust3.DefaultIfEmpty(), (cust, cust3) => new { cust = cust.cust, cust3 })
.Join(Tbl4, c => c.cust.cust.bintAccountNo, bp => bp.bintAccountNo, (cust, bp) => new { cust = cust, bp = bp })
.Join(Tbl5, z => z.bp.intPartner, part => part.intPartner, (z, part) => new { z = z, part = part }))
.Select(o => new
  {
      bintAccountNo = o.z.cust.cust.cust.bintAccountNo
  }


texts: Java Palindrome - Time & Space Complexity

texts:
Which of these three methods is the most efficient?

Also, what is the time & space complexity of each?

public class Palindrome {

    public static boolean isStringBased(String word) {
        if (word == null || "".equals(word)) {
            return false;
        }
        String lowerCasedWord = word.toLowerCase();
        int i = 0;
        int j = lowerCasedWord.length() - 1;

        while (i < j) {
            if (lowerCasedWord.charAt(i) != lowerCasedWord.charAt(j))
                return false;
            i++;
            j--;
        }
        return true;
    }

    public static boolean isPalindromeRecursive(String input) {
        if(input.length() == 0 || input.length() == 1) {
            return true;
        }
        if(input.charAt(0) == input.charAt(input.length()-1)) {
            return isPalindromeRecursive(input.substring(1, input.length()-1));
        }
        return false;
    }

    public static boolean isPalindromeIterative(String input) {
        boolean retValue = false;
        int length = input.length();
        for( int i = 0; i < length/2; i++ ) {
            if (input.charAt(i) == input.charAt(length-i-1)) {
                retValue = true;
            }
        }
        return retValue;
    }
}


texts:
Is there a safer/ more readable way of using this code?
I gotta translate this code into a better , safer and more readable sample of code and get my onclick to work.(its currently called from another thread then what it is created from.)

public class TemperaturePresenter
{
    MainView _view;

    // TODO ojoj det blev lite stökigt här
    public TemperaturePresenter(){
        _view = new MainView();
        ThreadPool.QueueUserWorkItem(
             delegate{
        XmlDocument serverDoc = new XmlDocument();
        serverDoc.Load("ServerUrls.xml");
        var location = serverDoc.SelectSingleNode("//servers/server/url");
        string serverUrl = location.InnerText;
        var searchNode = serverDoc.SelectSingleNode("//servers/server/xpath");
        var searchPath = searchNode.InnerText;
        WebRequest req = WebRequest.Create(serverUrl);
        var response = req.GetResponse();
        var a = response;
        Stream stream = response.GetResponseStream();
        XmlDocument responseDoc = new XmlDocument();
        responseDoc.Load(stream);
        var temperatureNode = responseDoc.SelectSingleNode(searchPath);
        string temperature = temperatureNode.Attributes["value"].Value;

        SetTemperature(temperature);
            });
    }

    void SetTemperature(string temperature) {
        //if ( _view.InvokeRequired ){
        //    _view.Invoke( (Action<string>) SetTemperature, temperature);
        //    return;
        //}
        _view.Temperature = temperature;
    }

    public Form Form { get{ return _view; } }

Next page:

public partial class MainView : Form
{
    public MainView()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //fyll

        throw new NotImplementedException("cant press on this button, yet!");
    }

    public string Temperature {
        set {
            tempLbl.Text = String.Format("{0} grader celcius", value);
            Refresh();
        }

Im thinking i need to do some "this.thread" stuff, but i dont know how.


texts:
I have a program that calculates some values and saves them to an array. Before save a value, program checks if there is already an identical value in array:

 string someData = GetData();
 bool newItem = true;
 int arrayDataLength = arrayData.Length;
 for (int x = 0; x < arrayDataLength; x++)
 {
     if (arrayData[x] == someData)
     {
         newItem = false;
         arrayDataCount[x]++;
         break;
     }
  }
  if (newItem == true)
  {
       Array.Resize(ref arrayData, (arrayDataLength + 1));
       Array.Resize(ref arrayDataCount, (arrayDataLength + 1));
       arrayData[arrayDataLength] = someData;
       arrayDataCount[arrayDataLength]++;
  }

Sometimes arrays with data become big, and program works a bit slow.
How can I optimize perfomance of this action?


texts:
I'm trying to practice some functional techniques. I haven't worked much in Haskell, so any language-specific tips would be very appreciated, but what I care for even more are general tips towards my approach that I can carry between functional languages. Performance is not a big concern of mine right now.
I implemented the winner-checking algorithm for the connect-four game. Basically, given a 6x7 grid, I need to be able to determine if a player has successfully placed four consecutive tiles down (horizontally, vertically, or diagonally). If so, I need to return which player it was.
Here is my implementation:
module Logic (Player(..), Board, getWinner) where
import qualified Control.Monad as Monad

data Player = Player1 | Player2

type BoardEntry = Maybe Player

type Board = [[BoardEntry]]

type Coord a = (a, a)

instance Eq Player where
  Player1 == Player1 = True
  Player2 == Player2 = True
  x == y = False

map2dList :: (a -> b) -> [[a]] -> [[b]]
map2dList fn = map (map fn)

getElementAt :: [a] -> Int -> Maybe a
getElementAt (el:_) 0 = Just el
getElementAt (_:rest) n = getElementAt rest (n - 1)
getElementAt [] _ = Nothing

getBoardEntryAt :: Board -> Coord Int -> Maybe BoardEntry
getBoardEntryAt board (x, y) =
  getElementAt board y >>= flip getElementAt x

getBoardDimensions :: Board -> (Int, Int)
getBoardDimensions board =
  ((length . head) board, length board)

addCoords :: Coord Int -> Coord Int -> Coord Int
addCoords (x1, y1) (x2, y2) =
  (x1 + x2, y1 + y2)

isCoordInRegion :: (Int, Int) -> Coord Int -> Bool
isCoordInRegion (width, height) (x, y) =
  x >= 0 && x < width &&
  y >= 0 && y < height

getAllCoordsInRegion :: (Int, Int) -> [Coord Int]
getAllCoordsInRegion (width, height) =
  [(x,y) | x <- [0..width-1], y <- [0..height-1]]

getWinner :: Board -> Maybe Player
getWinner board =
  let
    fourInRowsFromOrigin =
      [
        [(0, 0), (1, 0), (2, 0), (3, 0)],
        [(0, 0), (1, 1), (2, 2), (3, 3)],
        [(0, 0), (0, 1), (0, 2), (0, 3)],
        [(0, 0), (-1, 1), (-2, 2), (-3, 3)]
      ]
    playerPieceAt = Monad.join . getBoardEntryAt board
    results = concat $ do
      coord <- (getAllCoordsInRegion . getBoardDimensions) board
      fourInRow <- map2dList (addCoords coord) fourInRowsFromOrigin
      player <- [Player1, Player2]
      return [player | all ((== Just player) . playerPieceAt) fourInRow]
  in case results of
    [winner] -> Just winner
    [] -> Nothing
    _ -> undefined

And here is a sample driver, to help see that it works:
import Logic (Player(Player1, Player2), Board, getWinner)

getWinnerAsString :: Maybe Player -> [Char]
getWinnerAsString Nothing = "No one has won"
getWinnerAsString (Just Player1) = "Player 1"
getWinnerAsString (Just Player2) = "Player 2"

printWinner :: Board -> IO ()
printWinner = putStrLn . getWinnerAsString . getWinner

exampleBoard :: Board
exampleBoard =
  let
    __ = Nothing
    p1 = Just Player1
    p2 = Just Player2
  in [
    [__, __, __, __, __, __, __],
    [__, __, __, __, __, __, __],
    [__, __, p2, p1, __, __, __],
    [__, __, p1, p2, __, __, __],
    [__, p1, p1, p2, p1, __, __],
    [p1, p2, p2, p2, p1, __, __]
  ]

main :: IO ()
main = printWinner exampleBoard


texts:
Basically, this program takes a decimal number from 1 to 10, that is the index of power of 2. And turns into an array with \$2^n\$ combinations.

For example: If my decimal is 1, I'll have 2 arrays, [0] and [1], and if my decimal is 2, I'll have 4 combinations, [0 0]; [0 1]; [1 0]; [1 1], and so on. I cannot use break conditions.

#include <stdio.h>

int main() {
    int n, q = 1, i, f, d, p, vet[10]; // n: index; q: combinations; i, f, d, p: ints for operations;

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

    for (i = 0; i < n; i++){ // getting total number of comb
        q *= 2;
    }
     n--;

    for (i = 0; i < q; i++){
        f = i;

        for (p = 0; p < 10; p++){   //setting array to 0
            vet[p] = 0;
        }

        while ( f > 0){
           p = 1;
           d = 0;

            while (f >= 2*p){
                p *= 2;
                d++;
            }

            vet[d] = 1; //changing position 'd' on array for 1.
            f -= p;
        }

        // printing results
        printf ("f: %d bin:", i);

        for (p = 0; p < 10; p++)
            printf ("%d", vet[9-p]);

        printf ("\n");
    }
    return 0;
}