texts: Python beginner looking for feedback on simple dice game

texts:
Dice "Game"
So, just started python a weeks time ago, so I'm looking for feedback/critique on things i can do to improve my code. I wrote a little user/pc dice rolling game. Any feedback at all is appreciated!

def dice(n: int) -> tuple:
    """
    Simple function to roll 'n' number of dices.
    Returns numbers of each roll and a total.

    :param n: number of dices to roll
    :return: dices_numbers, total
    """
    numbers = []
    total = 0
    for dices in range(n):
        number = random.randint(1, 6)
        numbers.append(number)
        total += number
    dices_numbers = ", ".join(map(str, numbers))
    return dices_numbers, total

def dice_check(user_total: int = 0, pc_total: int = 0) -> None:
    """
    Function to check whether user or pc won dice roll.

    :param user_total: user's total roll
    :param pc_total:  pc's total roll
    :return: None
    """
    if user_total > pc_total:
        print("Congratulations! You won")
    elif user_total < pc_total:
        print("Sorry, BOT wins!")
    else:
        print("Tie!")

number_of_dices = ""
user_roll = ""
pc_roll = ""
while True:
    number_of_dices = int(input("How many dices would you like to roll?"
                                " (0 to quit) >"))
    if number_of_dices == 0:
        break
    else:
        user_roll = dice(number_of_dices)
        pc_roll = dice(number_of_dices)
        print(f"You: Roll: {user_roll[0]}, a total of: {user_roll[1]}")
        print(f"BOT: Roll: {pc_roll[0]}, a total of: {pc_roll[1]}")
        dice_check(user_roll[1], pc_roll[1])


texts:
I am trying to remove duplicates from a string without using additional buffers.
This seems to work correct, I think. Can this be improved? Should I be doing it differently?

private static String removeDuplicates(char[] chars) {

        if(chars == null)
            return null;

        int len = chars.length;
        for(int i = 0; i < len; i++){
            for(int j = i + 1; j < len;){
                if(chars[i] == chars[j]){
                    int temp = j;
                    while(temp < len - 1){
                        chars[temp] = chars[temp + 1];
                        temp++;
                    }
                    len--;
                }
                else
                    j++;
            }
        }

        return new String(chars, 0, len);
    }


texts:
I want to do insert sort in a linked list without using dummy nodes.

This is my code. How can this be improved? Any input is appreciated.

public static Node insertSort(Node node){

   Node sortedList = null;
   while(node != null){
    Node current = node;
    node = node.next;
    Node x;
    Node previous = null;
    for(x = sortedList; x != null; x = x.next){
        if(current.value < x.value){
                break;
         }
         previous = x;
    }
    if(previous == null){
          current.next = sortedList;
          sortedList = current;
    }
    else{
       current.next = previous.next;
       previous.next = current;
    }
  }
  return sortedList;
}


texts: Binary string to integer and integer to binary string

texts:
I am working through K&R for review and I thought that I would write some of my own routines for conversion of binary strings to int and int to binary string. I realize this is reinvetning the wheel; I am just doing this for fun. Also, I am attempting to follow this coding style CodingStyle.txt. Any and all critiques are welcomed.

#include <mybin.h>
#include <limits.h>
#include <errno.h>

/*
Parameters:
s   - String with a maximum of 63 binary digits
Return:
    - Decimal value of the binary string pointed to by s
Error:
    - Negative returned on error check errno
*/
signed long binstr2int(char *s)
{
    signed long rc;
    for (rc = 0; '\0' != *s; s++) {
        if (rc > (LONG_MAX/2)) {
            errno = ERANGE;
            return -1;
        } else if ('1' == *s) {
            rc = (rc * 2) + 1;
        } else if ('0' == *s) {
            rc *= 2;
        } else {
            errno = EINVAL;
            return -1;
        }
    }
    return rc;
}

/*
Parameters:
num - The number to convert to a binary string
s   - Pointer to a memory region to return the string to
len - Size in bytes of the region pointed to by s
Return:
    - Pointer to the beginning of the string
Error:
    - NULL returned on error check errno
*/
char *int2binstr(unsigned long num, char *s, int len)
{
    if (len < 2) {
        errno = ERANGE;
        *s = '\0';
        return s;
    } else if (0 == num) {
        s[--len] = '\0';
        s[--len] = '0';
        return s + len;
    } else {
        for (s[--len] = '\0'; 0 != num; num >>= 1) {
            if (0 == len) {
                errno = ERANGE;
                *s = '\0';
                return s;
            } else if (num & 1) {
                s[--len] = '1';
            } else {
                s[--len] = '0';
            }
        }
    }
    return s + len;
}

Edit 1:
Okay, here is the revised code. Most of the suggestions I agree with. I did retain filling the buffer from end to beginning because it seems like a logical flow to me and requires one less variable to deal with.

The do while suggestion was spot on. The for loop was unusual and the do while consumed one of the conditionals making the code easier to read.
The names of the functions have been revised so they are not misleading
The functions now handle unsigned long ints
ul2binstr now returns NULL on error. So this needs to be checked.
Also the string parameter was in binstr2ul was made const
The len parameter was changed to size_t type

/*
Parameters:
s   - String with a maximum of log2(ULONG_MAX) binary characters
num - Memory address to store the result in
Return:
    - Status integer
Error:
    - Negative returned on error check errno
*/
int binstr2ul(const char *s, unsigned long *num)
{
    unsigned long rc;
    for (rc = 0; '\0' != *s; s++) {
        if (rc > (ULONG_MAX/2)) {
            errno = ERANGE;
            return -1;
        } else if ('1' == *s) {
            rc = (rc * 2) + 1;
        } else if ('0' == *s) {
            rc *= 2;
        } else {
            errno = EINVAL;
            return -1;
        }
    }
    *num = rc;
    return 0;
}

/*
Parameters:
num     - The number to convert to a binary string
s       - Pointer to a memory region to return the string to
len     - Size in bytes of the region pointed to by s
Return:
        - Pointer to the beginning of the string
Error:
        - NULL returned on error check errno
*/
char *ul2binstr(unsigned long num, char *s, size_t len)
{
    if (0 == len) {
        errno = EINVAL;
        return NULL;
    } else {
        s[--len] = '\0';
    }

    do {
        if (0 == len) {
            errno = ERANGE;
            return NULL;
        } else {
            s[--len] = ((num & 1) ? '1' : '0');
        }
    } while ((num >>= 1) != 0);

    return s + len;
}


texts:
I made this query to create a graph of a user's popular questions and the view count on that question. It allows for a minimum of 500 views, and a score of 3.

DECLARE @allowed_min_views INT = 500;
DECLARE @allowed_min_score INT = 3;

DECLARE @user_id INT = ##UserId:int?-1##;
DECLARE @min_views INT = ##MinimumViews:int?500##;
DECLARE @min_score INT = ##MinimumScore:int?3##;
DECLARE @question INT = 1;

IF (@min_views < @allowed_min_views)
BEGIN
  PRINT '@MinimumViews must be larger than 499.'
END

IF (@min_score < @allowed_min_score)
BEGIN
  PRINT '@MinimumScore must be larger than 2.'
END

IF (@min_views >= @allowed_min_views AND @min_score >= @allowed_min_score)
BEGIN
  SELECT
      ViewCount
    , Score
    FROM Posts WHERE
      PostTypeId = @question
      AND OwnerUserId = @user_id
      AND ViewCount >= @min_views
      AND Score >= @min_score
    ORDER BY ViewCount ASC;
END

Finally, here's some sample input (I'm using @Mat'sMug's user ID):

@user_id:   23788
@min_views: 500
@min_score: 7


texts: Split an array of items into several arrays, given a condition

texts:
The question is very simple : I have an array of items, that all have a date. According to the date, I would like to split this array into several arrays.

In my case, I would like to split the array into 3 arrays : one that contains result of the last 24h, the other 48h, then the last one on the week.

Here is a minimal reproduction of the case, with the final solution.

const now = Date.now();
const day = 1000 * 3600 * 24;

const todayTime = now - day;
const yesterdayTime = now - day * 2;
const weekTime = now - day * 7;

const arr = [
  { id: 1, date: todayTime + 100 },
  { id: 2, date: yesterdayTime + 100 },
  { id: 3, date: weekTime + 100 },
];

const today = arr.filter(item => item.date - todayTime > 0);
const yesterday = arr.filter(item => item.date - yesterdayTime > 0 && item.date - todayTime < 0);
const week = arr.filter(item => item.date - weekTime > 0 && item.date - yesterdayTime < 0);

console.log(today, yesterday, week);

Is there a way to make it more concise ? I'm talking about code length : I would like to reduce it to the maximum, especially the definition of the 3 arrays. I tried with reduce, but the syntax is pretty ugly.

Any ideas ?


texts:
I am still learning OOP and I need a little help, I don't really know how to properly make this not look so terrible.

Any thoughts?

<?php

class Noti {

    public static $app;
    public static $user;
    public static $url;
    public static $result;
    public static $data;
    public static $title;
    public static $text;

    public static function status($title = null, $text = null) {

        // Error check
        if(empty($title)) return false;
        if(empty($text)) return false;

        // Set
        self::$title = $title;
        self::$text = $text;

        // Get the NOTI config
        self::$app  = Config::get('noti.app_id');
        self::$user = Config::get('noti.user_token');
        self::$url  = Config::get('noti.url');

        // Format
        self::$data = self::format();

        // Url
        $ch = curl_init(self::$url.'add'); // Append add to url for status update
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, self::$data);

        self::$result = curl_exec($ch);

        // Close
        curl_close($ch);

        return self::$result;
    }

    private static function format() {
        $data = array(
            'app' => self::$app,
            'user' => self::$user,
            'notification[title]' => self::$title,
            'notification[text]' => self::$text
        );

        return http_build_query($data);
    }

}


texts: Make Simultaneous HTTP Requests That Resolve Into a Single Return

texts:
This week, in an ongoing job search, I was tasked with the following pre-screening question:

  Make two simultaneous http requests. Use the language and library of your choice. Make sure the results are combined and resolve into a single return.

For this I chose JavaScript and jQuery, culminating in the following Gist and jsFiddle.

fiddle.js:

var gistID = '275cd1b76574497327761b33fb08ad4d';

function Source(url){
 this.url = url;
};

var source = new Source("/gh/gist/response.html/" + gistID + "/");
var sources = [source,source];

function asyncGroup() {

 var promises = [];

 sources.forEach(function(source,index,sources){

  var deferred = jQuery.Deferred();

  promises.push(deferred.promise());

  $.ajax({url: source.url, processData: false}).always(function(data){
   sources[index].element = '<img src="data:image/png;base64,' + data + '"/>';
   deferred.resolve();
  });
 });
 return promises;
}

$.when.apply(null, asyncGroup() ).done(function( status ) {

 sources.forEach(function(source){$("#myDiv").append($(source.element));});
 $("#myDiv").show();
});

One thing I would like to change is to accredit Fiddle Author Casiano Rodriguez-Leon for their base64 testing image, provided it remains in the implementation. Perhaps this is best done in fiddle.manifest, I am not sure.

Beyond that, I know that much can be improved, and I'm all ears.


texts: Retrieving first non-private ip for local system in elixir

texts:
I've recently started learning elixir, and the following is my attempt at fetching the local IP address of the system.
It can definitely be improved further, but as this would be my first ever project in a functional language; I'd be open to any criticisms.
defmodule Systemip do
  def private_ipv4() do
    {:ok, addrs} = :inet.getif()

    filtered =
      Enum.filter(
        addrs,
        fn address ->
          ip = elem(address, 0)
          is_private_ipv4(ip)
        end
      )

    elem(hd(filtered), 0)
  end

  defp is_private_ipv4(ip) do
    case ip do
      {10, _x, _y, _z} ->
        true

      {192, 168, _x, _y} ->
        true

      {172, 16, _x, _y} ->
        true

      {172, 32, _x, _y} ->
        true

      _ ->
        false
    end
  end
end

This would be part of a larger project, which is still under construction. The IPs are fetched using the erlang call to :inet.getif, the formatting was done by mix format command.


texts:
I have the case of repeated very similar logic that is used to check if a boolean value was changed from the initial value and prevent it from changing back, or to summarize multiple boolean return values like:

bool SomeMethod()
{
    bool endResult = true;
    foreach(var obj in objs)
    {
        bool result = obj.Method();
        if(!result)
            endResult = false;
    }
    return endResult;
}

I reworked the logic into a class where a boolean can only be changed from the initial value, so that the boolean logic is all in one place. The IsChanged property is for LINQ queries.

public class OneUseBool
{
    private readonly bool _initValue;

    public OneUseBool(bool init)
    {
        _initValue = init;
        _currentValue = init;
        _isChanged = false;
    }

    private bool _currentValue;
    public bool CurrentValue
    {
        get { return _currentValue; }
        set
        {
            if (_initValue != value)
            {
                _currentValue = value;
                IsChanged = true;
            }
        }
    }

    private bool _isChanged;
    public bool IsChanged
    {
        get { return _isChanged; }
        private set
        {
            if(!_isChanged)
                _isChanged = value;
        }
    }
}

So the original code gets changed to:

bool SomeMethod()
{
    OneUseBool endResult = new OneUseBool(true);
    foreach(var obj in objs)
    {
        endResult.CurrentValue = obj.Method();
    }
    return endResult.CurrentValue;
}

Is this a good way to do this sort of logic with bools, or am I just overcomplicating a simple problem?


texts: C function to fully consume a Python iterator

texts:
I was reading into the proper way to consume an iterator on this question as well as here and I notices there is no actual proper function for this that clearly explains itself.

Using:

collections.deque(maxlen=0).extend(iterable)

isn't exactly very descriptive whereas making a properly named method for this that just uses the deque approach is good I wanted to do my own research as well as learn some c (which I've rarely ever actually dealt with) along the way.

So.. Using the approach that is used in _collectionsmodule.c I have come up with this:

#include "Python.h"
#include <ctype.h>

static PyObject *
consume(PyObject *self, PyObject *iterable)
{
    PyObject *(*iternext)(PyObject *);
    PyObject *item;

    if (PyObject_GetIter(iterable) == NULL)
        return NULL;

    iternext = *Py_TYPE(iterable)->tp_iternext;
    while ((item = iternext(iterable)) != NULL)
        Py_DECREF(item);

    if (PyErr_Occurred()) {
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
            PyErr_Clear();
        else
            return NULL;
    }
    Py_RETURN_NONE;
}

static PyMethodDef consumeMethods[] = {
    {"consume", (PyCFunction)consume, METH_O,
      "Run an iterator to exhaustion."},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef _consumemodule = {
    PyModuleDef_HEAD_INIT,
    "_consumemodule",
    "Consume Module",
    -1,
    consumeMethods,
    NULL,
    NULL,
    NULL,
    NULL
};

PyMODINIT_FUNC
PyInit__consumemodule(void)
{
    return PyModule_Create(&_consumemodule);
}

It performs marginally better than the deque approach which is expected as it's using almost the same approach although I was wondering if any of the c guru's out there could see if I'm missing anything or if something could be done better as all it's doing it exhausting the iterator. I tried using METH_FASTCALL but that doesn't perform as well as METH_O and in the while loop I tried usingwhile ((Py_XDECREF(iternext(iterable))) != NULL) the only way I could find to eliminate the need for the variable item was by making a macro like this:

static inline int _Ret_DECREF(PyObject *op)
{
    if (op == NULL)
        return 0;
    Py_DECREF(op);
    return 1;
}

#define Ret_DECREF(op) _Ret_DECREF(op)

Then just looping through like this:

while (1) {
    if (Ret_DECREF(iternext(iterable)))
        break;
}

But something just feels off doing that.


texts:
I have a model with a number of complex/simple properties that has a corresponding strongly typed view, that calls EditorFor to a custom editor template view for the model.

One of the form's requirements is to auto fill the form based on a choose of values from a database.

Previously, I had the selectors on the selection popup do a post back to an action with the additional value needed to prepopulate the model, and then the model is bound like normal.

I wanted to see if I could alter the form to do the prefill with Ajax:

I have a JsonResult Action that accepts a unique Id, and returns the JSON version of the model.

When you click the selection button this action is invoked via jQuery $.ajax post.

Each input on the form has an Id in the form Id="ModelName_PropertyName" so parse the keys in the JSON object, using the keys to look up the field in a given selector, and set the values from JSON.

Here is how I invoke from Ajax in CoffeeScript (I can post the JavaScript if requested):

$.ajax
    type: "POST"
    url: $("#SelectFromPolicyContainer").data "url"
    data: vin
    success: (response) ->
        $("#PropertyInfo").bindFormToJson response.Data.Vehicle, true
        $("#SelectFromPolicyResponse").dialog "close"

The Action looks like this:

[HttpPost]
public JsonResult VehicleByVIN(string VinNumber)
{
    return AjaxJsonResponse.Create(UserNotice.NoNotice, new
    {
        Vehicle = Policy.Vehicles.SingleOrDefault(p=>p.Info.Vin.Number==VinNumber)
    });
}

And the definition of bindFormToJson:

$ -> $.fn.bindFormToJson = (JsonObject, OverwritePopulatedFields) ->

    selector = $(this).selector

    iterateJson = (JSonObject, FullKey, Seperator, func) ->
        for key, value of JSonObject
            newKey = ""
            if FullKey == ""
                newKey = key
            else
                newKey = FullKey + Seperator + key

            if typeof(value) == "object"
                iterateJson value, newKey, Seperator, func
            else
                func newKey, value

    iterateJson JsonObject, "", "_", (key,value) ->
        field = $(selector + " #" + key)
        currentValue = field.val()
        if (currentValue and OverwritePopulatedFields) or not currentValue
            field.val(value)

Any tips, or things I may have missed or potential problems I might have overlooked would be wonderful.  In my test environment right now though, this is working beautifully.


texts:
#loop to get input that is not blank, strips input of whitespace
def ckin(a):
    while a=='':
        a=input().strip()
    return  a

#creates list with includes user admin
user_names = ['admin']

#Ask for 5 names to store as usernames
print('Please enter 5 user names: ')

#if username is valid, add to list
for i in range(0,5)
    lib_name=input().strip()
    lib_name=ckin(lib_name)
    user_names.append(lib_name)

#asks for login name, must be valid
print('Enter login name:')
log_name=input().strip()
log_name=ckin(log_name)

#Create a test list that is lower case to compare login
#against without altering the cases used by user to creat username list

test=[name.lower() for name in user_names]

#if login name not in list continue to prompt
while log_name.lower() not in test:
    print('Enter login name:')
    log_name=input().strip()
    log_name=ckin(log_name)

#find login name in test, then return either response for admin, or login    name using
#case formatting that original used for original entry
for i in range(len(test)):
    if log_name.lower() == 'admin':
        print('Hello admin, would you like to see a status report?')
        break
    elif log_name.lower() == test[i]:
        print('Hello '+user_names[i]+', thank you for logging in again')
        break

Looking for general review self-teaching, Day 4

I haven't learned much but I keep attempting to do what I'm learning with user inputs instead of set entries

My goal here was to be able to create a list that keeps the original entry cases to be used for responding. I created a second list in lower cases to compare to and then responded using the cases the entries were stored as.

Any comments are greatly appreciated!


texts: Comparing two integers without logical, relational or bitwise operators

texts:
I answered a question on SO today, however it did't receive any up-votes, so I want to know what's wrong with my code.

The requirement is to compare the input numbers(granted to be positive) without logical, relational or bitwise operators, and insert the corresponding comparison sign between them. For example:

input:  4 6
output: 4 < 6
input:  10 2
output: 10 > 2
input:  2 2
output: 2 = 2

Here is my posted code:

#include <stdio.h>

int main(void)
{
    unsigned a, b;
    scanf("%u %u", &a, &b);
    printf("%u ", a);
    char relationship[] = {'<', '=', '>'};
    putchar(relationship[!!(a/b) - !!(b/a) + 1]);
    printf(" %u", b);
    return 0;
}

That OP wants to know how to insert a comparison sign(<, >, =) between the two numbers. But my emphasis is on how to determine the relationship of the two numbers.

See: https://stackoverflow.com/q/35532123/5399734 for the original question.


texts: Swift solution to Leetcode “Longest Substring Without Repeating Characters”

texts:
From LeetCode medium 3. Longest Substring Without Repeating Characters:

  Given a string, find the length of the longest substring without repeating characters.

  Examples:

  Given "abcabcbb", the answer is "abc", which the length is 3.

  Given "bbbbb", the answer is "b", with the length of 1.

  Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Here is my solution, but the online judge told me "Time Limit Exceeded". Is there a better solution to this problem?

private extension String
{
    subscript (index:Int) -> Character
    {
        return (self[self.startIndex.advancedBy(index)])
    }
}

class Solution
{
    func lengthOfLongestSubstring(s: String) -> Int
    {
        var str:String = ""
        var longest:Int = Int.min

        if s.isEmpty
        {
            return 0
        }

        for i in 0...s.characters.count-1
        {
            if !str.characters.contains(s[i])
            {
                str += String(s[i])
            }

            else
            {
                longest = max(longest, str.characters.count)
                str = ""

            }
        }

        return longest
    }
}


texts: Pure Python script that saves an HTML page with all images

texts:
Here is a pure Python script that saves an HTML page without CSS but with all images on it and replaces all hrefs with a path of an image on the hard drive.

I know that there are great libraries like BeautifulSoup and others but I would like to try myself with pure Python.

Actually there is no practical usage of this script, it was just test task from one of companies where I applied.

Once again what it does:

This script can pre-launched from command line, which takes 2 arguments:

Address of web page to save (this one is required)
Name of folder where images from page should be saved (this one is optional)
Script saves html content of page(without CSS) and also it looks for all images on page and save them too, replacing their href attribute to actual path of image on hard drive.

How can I improve it?

import random
import string
import sys
import urllib2
import os
import re
from urlparse import urlparse

def page_loader(url_name, dir_name='imgs'):

    page_to_open = urllib2.urlopen(url_name)
    target_page = page_to_open.read()
    base_dir = os.path.dirname(os.path.realpath(__file__))
    dir_to_save = os.path.join(base_dir, dir_name)
    new_file_name = '%s.html' % ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(10))
    if not os.path.exists(dir_to_save):
        os.makedirs(dir_to_save)

    images_on_page = re.findall('img .*?src="(.*?)"', target_page)
    internal_images = [img for img in images_on_page if img.startswith('/')]
    external_images = [img for img in images_on_page if not img.startswith('/')]

    for image in internal_images:
        image_url = '%s%s' % (page_to_open.geturl()[:-1], image)
        new_image_name = urlparse(image_url).path.split('/')[-1]
        with open(os.path.join(dir_to_save, new_image_name), 'w') as new_image:
            new_image.write(urllib2.urlopen(image_url).read())
            target_page = re.sub(image, new_image.name, target_page)

    for image_url in external_images:
        new_image_name = urlparse(image_url).path.split('/')[-1]
        with open(os.path.join(dir_to_save, new_image_name), 'w') as new_image:
            new_image.write(urllib2.urlopen(image_url).read())
            target_page = re.sub(image_url, new_image.name, target_page)

    with open(os.path.join(base_dir, new_file_name), 'w') as new_file:
        new_file.write(target_page)

if __name__ == '__main__':
    target_url = sys.argv[1]
    if len(sys.argv) > 2:
        dir_name = sys.argv[2]
        page_loader(target_url, dir_name)
    else:
        page_loader(target_url)


texts:
I've written this code but it's really long. I really need it to be shorter so can someone please help me! Any suggestions will be helpful.

choice=raw_input("What type of quiz do you want to do: maths or science? ")
topic=open("topic.txt", "a+")
topic.write(choice + '\n')
topic.close()
difficulty=raw_input("What difficulty do you want to play on: easy, medium or hard? ")
diff=open("difficulty.txt", "a+")
diff.write(difficulty + '\n')
diff.close()

score = 0

def answercheck(score, str_answer, int_answer):
    user_answer=raw_input("Select your answer. ")
    if user_answer.upper() == str(str_answer) or user_answer.upper() == str(int_answer):
        print("Well done, that's correct")
        score+=1
        print("Your score is " +str(score))
    else:
        print ("Wrong, it was "+str(int_answer))
        print("Your score is " +str(score))
    raw_input("Press enter to continue")
    return score

def report(score):
    print("Your final score is "+str(score))
    per=str(score)*(100/5)
    print("You achieved "+per+"%")
    if score==5:
        print("You achieved an A*")
    elif score==4:
        print("You acieved a grade B")
    elif score==3:
        print("You achieved a grade C")
    elif score==2:
        print("You achieved a grade D")
    elif score<=1:
        print("You failed")

if choice.lower() == "maths" and difficulty.lower() == "easy":
    easym=open("mathseasy.txt" , "r")
    lines = easym.readlines()
    print lines[0]
    print lines[1]
    print("A. 4"+'\n'+"B. 6")
    str_answer_one="A"
    int_answer_one=4
    first_score=answercheck(score, str_answer_one, int_answer_one)

    print lines[2]
    print("A. 5"+'\n'+"B. 6")
    str_answer_two="A"
    int_answer_two=5
    second_score=answercheck(first_score, str_answer_two, int_answer_two)

    print lines[3]
    print("A. 15"+'\n'+"B. 20")
    str_answer_three="B"
    int_answer_three=20
    third_score=answercheck(second_score, str_answer_three, int_answer_three)

    print lines[4]
    print("A. 13"+'\n'+"B. 15")
    str_answer_four="A"
    int_answer_four=13
    fourth_score=answercheck(third_score, str_answer_four, int_answer_four)

    print lines[5]
    print("A. 100"+'\n'+"B. 110")
    str_answer_five="B"
    int_answer_five=110
    fifth_score=answercheck(fourth_score, str_answer_five, int_answer_five)
    report(fifth_score)

if choice.lower() == "maths" and difficulty.lower() == "medium":
    mediumm=open("mathsmedium.txt" , "r")
    lines = mediumm.readlines()
    print lines[0]
    print lines[1]
    print("A. 30"+'\n'+"B. 35")
    str_answer_one="A"
    int_answer_one=30
    first_score=answercheck(score, str_answer_one, int_answer_one)

    print lines[2]
    print("A. 100"+'\n'+"B. 110")
    str_answer_two="B"
    int_answer_two=110
    second_score=answercheck(first_score, str_answer_two, int_answer_two)

    print lines[3]
    print("A. 13"+'\n'+"B. 15")
    str_answer_three="A"
    int_answer_three=13
    third_score=answercheck(second_score, str_answer_three, int_answer_three)

    print lines[4]
    print("A. 30"+'\n'+"B. 32")
    str_answer_four="B"
    int_answer_four=32
    fourth_score=answercheck(third_score, str_answer_four, int_answer_four)

    print lines[5]
    print("A. 21"+'\n'+"B. 29")
    str_answer_five="B"
    int_answer_five=29
    fifth_score=answercheck(fourth_score, str_answer_five, int_answer_five)
    report(fifth_score)

Here is the data in mathseasy.txt:

Welcome to the easy maths quiz.
What's 2+2?
What's 11-6?
What's 5*4?
What's 26/2?
What's 11*10?

Here is the data in mathsmedium.txt:

Welcome to the medium maths quiz.
What's 5*6?
What's 79+31?
What's 26/2?
What's 4*8?
What's 50-21?


texts: Many to many (n to m) relationship without insert duplication php

texts:
I managed to make a many to many relationship work correctly using mysql, doctrine 2 and symfony 3.4.

When a new element A that contains 0 to m element Bs is inserted, the B elements that already have the same content are reused, instead of creating new ones.

This is not the default doctrine 2 behaviour in a ManyToMany context with cascade={"persist", "remove"}.

The relationship uses an intermediate / join table, that contains id of table A and id of table B.

What I did is after deserializing the element A that contains m B elements, I check for each element B if a similar already exist in database.

If yes, I reuse it, if not I let doctrine cascade persist / insert new elements B.

Pseudocode, inside element A repository.

function useExistingDatabaseElementsBForNewElementA($elementA) {
    $elementsBs = $elementA->getElementsBs()
    // use existing elements B if available in database
    foreach ($elementsBs as $B) {

        /** @var B $matchingB*/
        $matchingB= $this->elementBRepository->findOneBy(['data' => $B->getData()]);

        if ($matchingB) {
            $elementA->removeElementB($B);
            $elementA->addElementB($matchingB);
        }
    }
}

I do this in the element A repository, by calling the findOne method of the element B repository and checking the result.

Is this is an acceptable / correct design choice / implementation.

How can it be better, for example using doctrine 2 configuration / annotations instead of my custom method in the element A repository ?

Could it be cleaner to implement it elsewhere or another way ?


texts:
I've written an ActiveAdmin mixin, such that you can include it and call simple_menu_for Foo, to reduce duplicate code when working with simple models.  Here is the main part, which will connect all others.  It works, but code looks little bit ugly. Maybe there is an alternative to using the class_variable_set method?

In case of differences of starting time I used a class variable on the ActiveAdmin class, instead of an instance variable on the controller. Is there a better way to handle that?

module ActiveAdminSimpleMenu

def simple_menu_for(klass, options = {})
  ActiveAdmin.register klass do
    permit_params(*(klass.main_fields + (options[:permitted_params] || [])))
    controller.class_variable_set(:@@permitted_params, options[:permitted_params])
    controller.class_variable_set(:@@klass, klass)

    controller do
      def scoped_collection
        permitted_params = self.class.class_variable_get :@@permitted_params
        self.class.class_variable_get( :@@klass).includes(*(permitted_params.map(&:cut_id)))
      end
    end if options[:permitted_params]

    index_for_main_fields klass
    filter_for_main_fields klass
    form_for_main_fields klass
  end
end


texts: Finding max z-index featuring in the current page

texts:
I have to display a cache layer on the whole viewport (to then display a kind of dialog box).
Without surprise I create a
 element with {position: fixed; top: 0 left: 0; width: 100%; height: 100%: background-color: #...; opacity: ...}.

But I faced the issue that I may encounter pages where some elements have a z-index other than 0 or auto.
So I must add a z-index property which surpasses the maximum one currently featuring in the page.

I'm currently using the following snippet:

var zMax = 0;
$('body *').each(function() {
  var zIndex = +$(this).css('zIndex'); // ("+" casts to number or NaN)
  if (zIndex > zMax) {
    zMax = zIndex;
  }
});

It works fine, but I'm not really happy with it: merely based on brute-force, it appears as "too easy" and a bit overkill.
I googled for other solutions and found a lot (notably on SO), but no one seems simpler than mine.

TL;DR; Is there some smarter alternative?

EDIT: to be more clear, here is an example of how the "cache layer" works:

$(document).ready(function() {
  $('#go, #goz').click(showDialog);

});
function showDialog() {
  $('body').append('
');
  $('body').append('

<button id="cancel">Cancel</button>
');
  $('#cancel').click(cancel);
  var text = 'Without z-index, cache doesn\'t cover image';
  if (this.id == 'goz') {
    $('#cache').css({zIndex: 101});
    $('#dialog').css({zIndex: 102});
    text = 'With z-index, cache covers all';
  }
  $('#text').html(text);
}
function cancel() {
  $('#dialog, #cache').remove();
}
#cache {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #444;
  opacity: .7;
}
img {
  position: relative;
  z-index: 100;
}
#dialog {
  position: fixed;
  left: 100px;
  top: 50px;
  width: auto;
  border: 1px solid #000;
  background-color: #fff;
  padding: 1em;
}

Longe glabro ortus tempus crimina perquam notarius Magnentio odorandi in membra quos a perquam supergressus.

Batnae municipium in Anthemusia conditum Macedonum manu priscorum ab Euphrate flumine brevi spatio disparatur.

<button id="go">Go (simple)</button>
<button id="goz">Go (with z-index)</button>

Using the "Go (simple)" button, you see that the image is not covered by the cache (in this case, because it both has position: relative and a given z-index).
Using the "Go (with z-index)" button, we have set z-index of the cache and dialog layers to a sufficient value to overstrip any other element's ones (here it's hard coded).

The important point is that my tool snippet may be included everywhere, notably in the context of an existing app (like a CMS).
Since I obviously have no control over such an app, I must discover which is the current max z-index: then the cache and dialog layers will get this max value +1 (respectively +2).


texts:
I'm trying to solve a challenge where you need to calculate the median every time you add a number.

say you have a list of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

When you scan in the first number (1), you calculate the median of that.
When you scan in the second number (2), you calculate the median of 1 and 2, and so on.

My code is working, but is having timeout issues on the larger test cases:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();

        PriorityQueue<Integer> pq = new PriorityQueue<>();

        while(n-- > 0) {
            pq.add(s.nextInt());
            System.out.println(calculateMedian(pq));
        }
    }

    public static float calculateMedian(PriorityQueue<Integer> pq) {
        PriorityQueue<Integer> temp = new PriorityQueue<>(pq);
        int index = 0;
        float number = 0.0f;
        int halfQueueSize = (temp.size() >> 1);

        if(temp.size() % 2 != 0) {
            while(index++ <= halfQueueSize) {
                number = temp.poll();
            }
            return number;
        } else {
            while(index++ < halfQueueSize) {
               number = temp.poll();
            }
            return ((number+temp.poll())/2.0f);
        }
    }
}

Any tips as to how this can be optimized would be much appreciated!


texts: Processor that would process an Object (say a message you received)

texts:
Sorry for being a little abstract but I have attempted to concoct something simple but it seems to spiral out of control. So I was thinking maybe I am taking the wrong approach.

Here's what I am trying to do:

  When I get a message it gets de-serialized into its own class. I would like to use a strategy pattern to choose a message processor that would be able to process the message

How would you do it?

Here are my attempts at this that got very convoluted the closer I got to the goal. I mean, it works but I would have thought it would be cleaner than this so just thinking I must be going about this wrong:

https://stackoverflow.com/questions/35801156/cant-seem-to-get-generic-covariance-contravariance-to-work
https://stackoverflow.com/questions/35784981/why-is-thisinterfacet-not-of-type-interfacet-using-an-is-keyword-comparison
https://stackoverflow.com/questions/35777762/cant-convert-from-abstractgeneric-to-concreteabstractconcretegeneric

Here's my code (but I am looking for ideas to avoid the MessageProcessorWrapper). How would you re-write it?:

public interface IBaseMessage {
   public int ID() { get; set; }
}

public interface IMessageProcessor<in T> where T : IBaseMessage {
            void Process(T msg);
        }

public class RRMessage : IBaseMessage {
          public string Text {get; set;}
          public DateTime RRProcessDate {get; set; }
        }

public class BaseMessageProcessor {
         public int MessageProcID{ get; set; }
         public BaseMessageProcessor(int mid) {
            MessageProcID = mid;
         }
      }

public class RRMessageProcessor : BaseMessageProcessor, IMessageProcessor<RRMessage> {
            public void Process(RRMessage msg) {
                WriteToDatabase(msg);
                UpdateInternalTrackers(msg);
                Console.WriteLine("Processed RRMessage");
            }
        }

public class ProcessorWrapper<T> : IMessageProcessor<IBaseMessage> {
    private readonly IMessageProcessor<T> inner;
    public ProcessorWrapper(IMessageProcessor<T> inner) { this.inner = inner; }

    public void Process(IBaseMessage msg)
    {
        if(msg is T) { inner.Process((T)msg); }
        else throw new ArgumentException("Invalid message type");
    }
}

[TestFixture]
public class MyTestFixture {
    public Dictionary<Type, IMessageProcessor<IBaseMessage>> MessageProcessors = new Dictionary<Type, IMessageProcessor<IBaseMessage>>();

    [Test]
    public void Test1() {
         var msgProcessor = new RRMessageProcessor();
         MessageProcessors.Add(typeof(RRMessage), new ProcessorWrapper<RRMessage>(msgProcessor);
         }
   }


texts:
I am using Dr.Racket, Intermediate Student with Lambda. I was wondering if there was any way I can simplify this code using any sort of method like lambda, abstraction, map, filter, etc.

 ; alien-at-edge?: alien --> boolean
(define (alien-at-edge? an-alien)
(or (alien-at-right-edge? an-alien)
(alien-at-left-edge? an-alien)))

; any-alien-at-edge?: loa --> boolean
(define (any-alien-at-edge? a-loa)
(cond [(empty? a-loa) false]
[else (or (alien-at-edge? (first a-loa))
      (any-alien-at-edge? (rest a-loa)))]))

;alien-at-left-edge?: alien --> boolean
(define (alien-at-left-edge? an-alien)
 (<= (- (posn-x an-alien) ALIEN-DELTA-X) alien-half))

;alien-at-right-edge?: alien --> boolean
(define (alien-at-right-edge? an-alien)
(>= (+ (posn-x an-alien) ALIEN-DELTA-X) (- WIDTH alien-half)))

;any-alien-at-right-edge?: loa --> boolean
(define (any-alien-at-right-edge? a-loa)
(cond [(empty? a-loa) false]
[else (or (alien-at-right-edge? (first a-loa))
      (any-alien-at-right-edge? (rest a-loa)))]))

;any-alien-at-left-edge?: loa --> boolean
(define (any-alien-at-left-edge? a-loa)
(cond [(empty? a-loa) false]
[else (or (alien-at-left-edge? (first a-loa))
      (any-alien-at-left-edge? (rest a-loa)))]))


texts: Assigning values to a particular table column

texts:
I have a set of Excel data which I read and assign to corresponding columns of an Excel table.  In our Excel we have provided the user the option to rearrange the Excel column fields at runtime.

int rowIndex =int.Parse(ExcelSettingManager.ItemLine);

int lastItem = numberOfFilledRows();

numberOfFilledRows();

int maxIndex = rowIndex + lastItem;

MSExcel.Range cell = null;
while (rowIndex < maxIndex)
{
    DataRow dataRow = ExcelDataManager.Instance.DocumentItemTable.NewRow();
    cell = this.worksheet.Range[ExcelSettingManager.LineItemNo + rowIndex.ToString()];
    if (cell.Value2 == null)
    {
        return;
    }

    dataRow["LineItemNo"] = cell.Value;
    ExcelUtilities.ReleaseResources(cell);

    if (ExcelSettingManager.CostCenter != string.Empty)
    {
        cell = this.worksheet.Range[ExcelSettingManager.CostCenter + rowIndex.ToString()];
        dataRow["CostCenter"] = cell.Value;
        ExcelUtilities.ReleaseResources(cell);
    }

    if (ExcelSettingManager.GLAccount != string.Empty)
    {
        cell = this.worksheet.Range[ExcelSettingManager.GLAccount + rowIndex.ToString()];
        dataRow["GeneralLedgerAccount"] = cell.Value;
        ExcelUtilities.ReleaseResources(cell);
    }

    if (ExcelSettingManager.Description != string.Empty)
    {
        cell = this.worksheet.Range[ExcelSettingManager.Description + rowIndex.ToString()];
        dataRow["ItemText"] = cell.Value;
        ExcelUtilities.ReleaseResources(cell);
    }
}

internal int numberOfFilledRows()
{
    int noft = 0;
    string sNextCell = ExcelSettingManager.LineItemNo ExcelSettingManager.ItemLine;
    MSExcel.Range cell = this.worksheet.Range[sNextCell];

    while(!string.IsNullOrEmpty(cell.Value))
    {
        ExcelUtilities.ReleaseResources(cell);
        noft++;
        sNextCell = ExcelSettingManager.LineItemNo + (int.Parse(ExcelSettingManager.ItemLine) + noft).ToString();
        cell = this.worksheet.Range[sNextCell];
    }
    return noft;
}

If my Excel has 10 rows according to the current logic, it will read cell by cell each row and will assign to the corresponding Excel table column.

This is having a lot of performance impact. When there are more rows, the performance is worse.

How can I increase performance of this code?


texts: Password generator + storage console app

texts:
This is my code to generate and store password localy hashed in txt file.
I would like to kindly ask you whether you could review my code. Btw it is coded as console app. I am currently working on making GUI. Thanks in advance.

import random
import hashlib

class randomPass():
    action = ''
    def __init__(self):
        # SETUP
        self.passdic = {}

        self.num_lines = sum(1 for line in open('passwords.txt'))
        with open('passwords.txt', 'r') as rf:
            for i in range(self.num_lines):
                self.content = rf.readline()
                self.content = list(self.content.split())
                self.passdic[self.content[0]] = self.content[1]

        self.leng = 14
        self.action = ''
        self.gPass = ''
        # work as i want to
        self.myPass = ''

        print('perform one of the actions')
        while self.action != 'break':
            print('new action please')
            self.action = input()
            if self.action == 'generate':
                print('determine your generated password length, We recommend above 14 characters')
                self.leng = int(input())
                self.gPass = self.generateRandomPassWord(self.leng)
                print('generated')
            elif self.action == 'read':
                self.passRead()
            elif self.action == 'save':
                    self.savePass(self.gPass)
            else:
                print(self.action + 'is not a valid action')

    def generateRandomPassWord(self, lengthOfPassword=14):
        znaky = ['"', "'", '!', '#', '$', '%', '&', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3',
                 '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
                 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[',
                 ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
                 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~']

        pword = ''.join([znaky[random.randint(0, len(znaky) - 1)] for i in range(lengthOfPassword)])
        return pword

    def savePass(self, generatedPassword):
        print('to save the generated pass word type your key password')
        self.myPass = hashlib.md5((input().encode('utf-8'))).hexdigest()
        if self.myPass in self.passdic:
            print('your key password already exists!')
        else:
            with open('passwords.txt', 'a') as af:

                af.write(self.myPass + ' ' + generatedPassword + '\n')

            self.passdic[self.myPass] = generatedPassword
            print('password stored')

    def passRead(self):
        print('to read the generated pass word type your key password')
        self.myPass = hashlib.md5((input().encode('utf-8'))).hexdigest()
        if self.myPass in self.passdic:
            print(self.passdic[self.myPass])
        else:
            print('we are sorry your password is non existant')

a = randomPass()
print('fin')


texts: A simple Dice Game Using only Static methods

texts:
This is a simple dice game that requires you  to get two numbers from the user and then it generates 15 other numbers and checks if the generated numbers are the same as the numbers typed in.

Try to run it on your IDE it will look more cool.

As seen below  I have  used only static methods:

import java.util.Random;

import java.util.Scanner;

public class DiceGame{

    static int first,second,dice;
    static int elments[] = new int [15];

    public static void main(String [] args){

        /*
        Hello Guys this is a simple dice game that requires you  type  two numbers from the user and then it
        generates 15 other numbers and checks if generated numbers are the same with your numbers typed in
        Try to run it on your IDE it will look more cool.
        As seen below  I have  used only static methods
        */

        getFirstNumberInput();
        getSecondNumberInput();
        validateFirstNumber();
        validateSecondNumber();
        generateDice();
        printAllelments();
        checkFirstNumberifSameAsGenerated();
        checkSecondNumberifSameAsGenerated();

    }

    static void getFirstNumberInput(){

        Scanner sc = new Scanner(System.in);

        System.out.print("\n type your first number from 1 to 6: ");
        first = sc.nextInt();
    }
    static void getSecondNumberInput(){
        Scanner sc = new Scanner(System.in);

        System.out.print("\n type your second number from 1 to 6 :");
        second = sc.nextInt();
    }
    static void validateFirstNumber(){
        if(first > 6){
            System.out.print("\nyou cant type a number greater than 6");
            getFirstNumberInput();
        }else if(first < 0){
            System.out.print("\n you cant type a negative number ");
            getFirstNumberInput();
        }else{
            validateSecondNumber();
        }
    }

    static void validateSecondNumber(){
        if(second> 6){
            System.out.print("\nyou cant type a number greater than 6");
            getSecondNumberInput();
        }if(second < 0) {
                System.out.println("\nyou cant type a negative number");
                getSecondNumberInput();
            }else {
                generateDice();
            }
        }

    static void generateDice(){
        Random generate = new Random();

        for(int iterator = 0; iterator < 15; iterator++){
            dice = 1+generate.nextInt(6);
            elments[iterator] = dice;

            }

    }

    static void printAllelments(){
        for(int i = 0;i<=14;i++){
            System.out.print(elments[i]+"\t");

            if(i % 5 == 0){
                System.out.println("\n\n\n\n");
            }

        }
    }

    static void checkFirstNumberifSameAsGenerated(){

            int same = 1;
        for(int i = 0 ;i< elments.length;i++){
            if(elments[i] == first){
                System.out.println();
                System.out.println("your  first number that you typed : [ "+first+" ] is the same as this [ "+elments[i]+" ] that was generated  { "+
                                    same+++" } similar numbers");

            }
        }
    }
    static void checkSecondNumberifSameAsGenerated(){

            int same = 1;
        for(int i = 0 ; i< 15;i++){
            if(elments[i] == second){
                System.out.println();
                System.out.println("your second number that you typed : [ "+second+" ] is the same as this [ "+elments[i]+" ] that was generated  { "+
                                    same+++" } similar numbers");

            }
        }
    }

}


texts: Bresenham's line algorithm implementation

texts:
May there be any performance and/or code standard improvements on the following LineOfSight code?

static List<Coordinate> getIntersects(Coordinate c1, Coordinate c2) {
    //  Bresenham's line algorithm from http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm#C.2B.2B

    List<Coordinate> returningVector = new List<Coordinate>();
    double y1 = c1.y, x1 = c1.x, y2 = c2.y, x2 = c2.x;

    bool steep = (Math.Abs(y2 - y1) > Math.Abs(x2 - x1));
    if(steep)
    {
        double _t;
        _t = x1;
        x1 = y1;
        y1 = _t;
        _t = x2;
        x2 = y2;
        y2 = _t;
    }

    if(x1 > x2)
    {
        double _t;
        _t = x1;
        x1 = x2;
        x2 = _t;
        _t = y1;
        y1 = y2;
        y2 = _t;
    }

    double dx = x2 - x1;
    double dy = Math.Abs(y2 - y1);

    double error = dx / 2.0f;
    int ystep = (y1 < y2) ? 1 : -1;
    int y = (int)y1;

    int maxX = (int)x2;

    for(int x=(int)x1; x<maxX; x++)
    {
        if(steep)
        {
            Coordinate tc = new Coordinate(y, x);
            returningVector.Add(tc);
        }
        else
        {
            Coordinate tc = new Coordinate(x,y);
            returningVector.Add(tc);
        }

        error -= dy;
        if(error < 0)
        {
            y += ystep;
            error += dx;
        }
    }
    if(steep)
    {
        Coordinate tc = new Coordinate(y2, x2);
        returningVector.Add(tc);
    }
    else
    {
        Coordinate tc = new Coordinate(x2,y2);
        returningVector.Add(tc);
    }
    return returningVector;
}

static bool isObstacle(Coordinate c1, Coordinate c2, Coordinate c3) {
    double heightOn_c3 = Math.Abs(((c1.height - c2.height) * Tools.distanceXY(c2, c3)) / Tools.distanceXY(c2, c1));
    return (heightOn_c3 + c2.height) < c3.height;
}

public static bool calculateLOS(Coordinate c1, Coordinate c2, Map map) {
    List<Coordinate> intersects = getIntersects(c1, c2);
    for(int i=0; i<intersects.Count; i++) {
        if(isObstacle(c1, c2, map.points[(int)intersects[i].x][(int)intersects[i].y].coordinates)){
            return false;
        }
    }
    return true;
}


texts:
When people migrate from Python to C++, they're often bothered by the fact that C++ strings don't support multiplication like Python's strings do.

std::string does have a constructor that supports creating a string with one character repeated a specified number of times. But, if the pattern to be repeated is more than one character long, C++ provides no convenient solution.

This is an attempt at providing such a solution:

#include <string>

std::string operator*(std::string const &in, size_t m) {
    std::string ret;

    for (size_t i = 0; i < m; i++)
        ret += in;
    return ret;
}

std::string operator*(size_t m, std::string const &in) {
    std::string ret;

    for (size_t i = 0; i < m; i++)
        ret += in;
    return ret;
}

For example, using these, the typical "print a Christmas tree of asterisks" task could be written something like this:

int main() {
    using namespace std::literals;

    std::cout << "Width: ";
    int width;

    std::cin >> width;

    for (int i = 1; i < width; i+=2)
        std::cout << " "s * ((width - i-1)/2) << "*"s * i << "\n";
}

[Of course, in this particular case, we're only multiplying single-character strings, so the std::string ctor would work as well.]

Note that the trailing s to make the string literal an std::string rather than a char const * is necessary--at least one operand of a user-defined operator must be a class or enumeration (or reference to a class or enumeration).


texts: Is it possible to DRY these 2 methods of a tailrec Node Tree?

texts:
I have a Tree structure composed by Node class.

I have to @tailrec method that are visiting up to the root.

Those 2 methods are completely similar, but 1 of those is manipulated a "stats" variable to check the visit and return the root, the other just return the root node.

Here the code sample:

class Node(parent: Option[Node], var visited: Int)
@tailrec
def asc(): Node = {
  parent match {
    case None => this
    case Some(x) => x.asc()
  }
}

@tailrec
def ascVisited(deltaInc: Inc): Node = {
  visited += deltaInc

  parent match {
    case None => this
    case Some(x) => x.ascVisited(deltaInc)
  }
}

Is there any way to reuse the logic of the parent checking and then call recursively the method? I thought with a higher-order function should be possible, but I am not sure is possible with different input argument in the functions.

Any suggestion?

Is it possible somehow to DRY out these 2 bits :

parent match {
  case None => this
  case Some(x) => x.asc()
 }
// and
parent match {
  case None => this
  case Some(x) => x.ascVisited(deltaInc)
}


texts:
Inspired by this r/dailyprogrammer post, the task is too calculate which records to use in order to serve the most records without any of the records having overlapping time spans.

I accomplish this goal by sorting the list of records by their total days spanned, then by iterating over each element and adding it to a new list as long as that record does not overlap with any records already within the "optimized" list.

The source,

internal class Program
{
    private static void Main(string[] args)
    {
        var rentalRecords = RentalRecordLoader.Load("rentals.txt");
        var result = RentalRecordOptimizer.CalculateMostEfficientRecords(rentalRecords);

        Console.WriteLine($"Total Records: {result.Count}");
        result.ForEach(r => Console.WriteLine($"{r.StartDay} : {r.EndDay}"));
    }
}

public class RentalRecord
{
    public int StartDay { get; set; }
    public int EndDay { get; set; }

    public RentalRecord(int startDay, int endDay)
    {
        StartDay = startDay;
        EndDay = endDay;
    }

    public int TotalDays()
    {
        return EndDay - StartDay;
    }

    public bool Overlapping(RentalRecord rentalRecord)
    {
        return StartDay <= rentalRecord.EndDay &&
            rentalRecord.StartDay <= EndDay;
    }
}

public abstract class RentalRecordLoader
{
    public static List<RentalRecord> Load(string path)
    {
        int recordCount;
        int[] startDays;
        int[] endDays;
        using (var reader = new StreamReader(path))
        {
            recordCount = int.Parse(reader.ReadLine());
            startDays = ConvertStringToIntArray(reader.ReadLine());
            endDays = ConvertStringToIntArray(reader.ReadLine());
        }

        var rentalList = new List<RentalRecord>();
        for (var i = 0; i < recordCount; i++)
        {
            rentalList.Add(new RentalRecord(startDays[i], endDays[i]));
        }

        return rentalList;
    }

    // Load() helper method
    private static int[] ConvertStringToIntArray(
        string value, string delimeter = " ")
    {
        return value.Trim().Split(delimeter)
                .Select(x => int.Parse(x))
                .ToArray();
    }
}

public abstract class RentalRecordOptimizer
{
    public static List<RentalRecord> CalculateMostEfficientRecords(
        List<RentalRecord> rentals)
    {
        var efficientRentals = new List<RentalRecord>();
        foreach (var rental in rentals.OrderBy(x => x.TotalDays()))
        {
            // Cant have any overlapping days.
            // The car cant be in two places at once.
            if (efficientRentals.Any(x => x.Overlapping(rental)))
            {
                continue;
            }
            efficientRentals.Add(rental);
        }
        return efficientRentals;
    }
}

The input used (stored in rentals.txt)

10
1 2 5 12 13 40 30 22 70 19
23 10 10 29 25 66 35 33 100 65

And the output:

Total Records: 5
5 : 10
30 : 35
13 : 25
40 : 66
70 : 100

Optimizations and better code design is obviously welcome, but I also had a specific question as well.

What would be the best way to handle incorrectly formatted data in
rentals.txt? Just catch the exception in the Load function?


texts:
I parse a big source code directory (100k files). I traverse every line in every file and look for function calls via regex matching.

I know that using regex to parse languages is a terrible idea. However, I'm looking for simplicity and not interested in the whole parse tree. Moreover, the regex pattern is generic and applies to all languages with the func(arg) syntax.

Following some profiling that I did, my hotspot is of course the function that responsible of processing a single line and search matches in that line. In big code projects, this function is called about 25 million times.
I was wondering weather there is room for optimization in the following 9 lines, or is this as good as it gets:

def get_line_symbols(self, line):
    symbols = []
    matches = self.index_pattern.finditer(line)
    for match in matches:
        while match:
            symbols.append(match.group(1))
            symbol_args = match.group(2)
            match = self.index_pattern.search(symbol_args)
    return symbols

self.index_pattern is re.compile('(\w+)(\([^\)]*\)?)')


texts:
I'm writing a function to append 5-10 bytes (count is random) at the beginning of a byte array, and 5-10 random bytes at the end:

func padWithRandomBytes(b []byte) []byte {
    startBytes := make([]byte, 10-rand.Intn(5))
    endBytes := make([]byte, 10-rand.Intn(5))
    newSlice := make([]byte, len(startBytes)+len(b)+len(endBytes))
    copy(newSlice[:len(startBytes)], startBytes)
    copy(newSlice[len(startBytes):len(startBytes)+len(b)], b)
    copy(newSlice[len(startBytes)+len(b):], endBytes)
    return newSlice
}

This feels pretty inefficient. Is there a more intuitive way to write this in Go?


texts:
I watched a YouTube video and completed the Todo List using Pure JavaScript.

Below is the code I wrote. I want to improve this code, but it 's not clear how.

I want to change this code to constructor function, but it's not easy. I think that the addItemTodo code is not bad, but the code in removeItem and completeItem are not good.

function TodoList(todo) {
    this.todo = todo;
}

function UI() {

    this.addItemTodo = function(todo) {
        var list = document.getElementById('todo');
        var item = document.createElement('li');
        item.innerText = todo.todo;

        var buttons = document.createElement('div');
        buttons.classList.add('buttons');

        var remove = document.createElement('button');
        remove.classList.add('remove');
        remove.innerHTML = removeSVG;
        remove.addEventListener('click', this.removeItem);

        var complete = document.createElement('button');
        complete.classList.add('complete');
        complete.innerHTML = completeSVG;
        complete.addEventListener('click', this.completeItem);

        buttons.appendChild(remove);
        buttons.appendChild(complete);
        item.appendChild(buttons);
        list.insertBefore(item, list.childNodes[0]); // 최신 순으로 목록 삽입
    };

    this.removeItem = function(e) {
        console.log(e.target);
        var item = this.parentNode.parentNode;
        var parent = item.parentNode;
        parent.removeChild(item);
    };

    this.completeItem = function() {

        var item = this.parentNode.parentNode;
        var parent = item.parentNode;
        var id = parent.id;
        var target = (id === 'todo') ? document.getElementById('completed') : document.getElementById('todo');
        parent.removeChild(item);
        target.insertBefore(item, target.childNodes[0]);

    };

    this.clearFields = function() {
        document.getElementById('item').value = "";
    }

}

var addBtn = document.getElementById('add');
addBtn.addEventListener('click', function() {

    var value = document.getElementById('item').value;
    var todoList = new TodoList(value);
    var ui = new UI();

    if(value) {
        ui.addItemTodo(todoList);
        ui.clearFields();
    } else {
        console.log("리스트를 입력해 주세요")
    }

});


texts: Program to calculate Hash and Size of a torrent

texts:
I wrote this small program to open a .torrent file, retrieve its info-hash and size. I'm still a beginner at Python so the main focus of this program was to try and utilize classes and objects instead of having just a bunch of functions. It works but I wanted to know if this is a good design. Also, I feel some of the code I wrote is redundant especially the number of times self is used.

import hashlib, bencode

class Torrent(object):

    def __init__(self, torrentfile):
        self.metainfo = bencode.bdecode(torrentfile.read())
        self.info = self.metainfo['info']
        self.files = self.metainfo['info']['files']
        self.md5hash = self.md5hash(self.info)
        self.size = self.size(self.files)

    def md5hash(self, info):
        return hashlib.sha1(bencode.bencode(info)).hexdigest()

    def size(self, files):
        filesize = 0
        for file in files:
            filesize += file['length']
        return filesize

torrentfile = Torrent(open("test.torrent", "rb"))
print(torrentfile.md5hash)
print(torrentfile.size)


texts:
So we're starting to use Typescript for a new project at work. Part of the application allows a user to retrieve their future availabilities (present/absent/possibly present), for planning purposes.

This is the get function of the service right now.

getMyAvailabilities(startDate: Moment, endDate : Moment): Observable<Map<Moment, Availability>>
{
    let params = new URLSearchParams();
    params.set('startDate', startDate.format(this.formatDateString));
    params.set('endDate', endDate.format(this.formatDateString));
    return this.http.get(this.resourceUrl, {search: params})
        .map((res: Response) =>
             {
                 let serializedResult = new Map<Moment, Availability>();
                 let result = res.json();
                 for (let key of Object.keys(result))
                 {
                     let availability = result[key];
                     serializedResult.set(moment(key),
                                          availability);
                 }
                 return serializedResult;
             });
}

You provide a startDate, and an endDate to the API, and the API will give you a map of availabilities with the date as a key.

I wrote a functional variant because it seemed suitable to functional code. We're using a lot of functional-style code in our project, because it's very suited for transforming lists of objects.

getMyAvailabilities(startDate: Moment, endDate: Moment): Observable<Map<Moment, Availability>>
{
    let params = new URLSearchParams();
    params.set('startDate', startDate.format(this.formatDateString));
    params.set('endDate', endDate.format(this.formatDateString));
    return this.http.get(this.resourceUrl, { search: params }).map((res: Response) => {
        let result = res.json();
        return Object.keys(result)
            .reduce((map: Map<Moment, Availability>, key: string) => {
                map.set(moment(key), result[key]);
                return map;
            }, new Map<Moment, Availability>());
    });
}

So, the functional variant is shorter. It's not likely that this function will need to map a large amount of objects - right now, we're estimating about 10-60 objects.

Most of us have a Java background - we're used to programming in Java, we're new or new-ish to the functional style of programming, so when presented with a procedural-style snippet of code and a functional-style snippet of code which do the same, perform the same and are of the same length, we tend to pick the procedural-style code.

But for this new project, making heavy use of procedural code would clash with the functional style used throughout the rest of the project.

Thus, the dilemma:

If we're not sure whether a piece of code is better as functional or procedural, should we go with the procedural code, which is easier to understand and probably more performant, even although we don't need that performance? Or should we go with the functional code, which is harder to understand, but follows the style of the rest of the project and is shorter in LoC?

And for the bonus question:

Is that a proper use of .reduce? Usually reduce gives a single value back. In this case, it returns... a collection. Is there another way by which we can go from Object (which has string keys and Availability values) to Map<Moment, Availability>?


texts: Windows autoclicker with a console interface

texts:
I have recently started coding in c++ and have made a simple console application. When executed the program asks the user to position their cursor wherever they want continuous repeating clicks, after 7 seconds it then asks the user to set an interval for the clicks. Since I am fairly new I am wondering if there is anything I could have done better to optimise the performance of the code or any other tips and tricks I can use, much appreciated

my code is (main.cpp):

#include <iostream>
#include <Windows.h>

using namespace std;

void leftClick(double mouse_x, double mouse_y){
        INPUT input;
        input.type=INPUT_MOUSE;
        input.mi.dx=(mouse_x * 65536) / GetSystemMetrics(SM_CXSCREEN) + 1;
        input.mi.dy=(mouse_y * 65536) / GetSystemMetrics(SM_CYSCREEN) + 1;
        input.mi.dwFlags=(MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_MOVE|MOUSEEVENTF_LEFTDOWN|MOUSEEVENTF_LEFTUP);
        input.mi.mouseData=0;
        input.mi.time=0;
        SendInput(1,&input,sizeof(INPUT));
}

int main(){
    cout << "Place the cursor where you want to click..." << endl;
    Sleep(7000);

    POINT p;
    GetCursorPos(&p);

    cout << "Set the interval to click: ";

    int cinterval {0};
    cin >> cinterval;

    cout << "Current Interval: " << cinterval * 1000 << endl;

    while(true){
        leftClick(p.x, p.y);
        Sleep(cinterval * 1000);
    }

     return 0;
}


texts: Pythonic way to manipulate arrays: a case study

texts:
I just spent almost one day to figure out the following code, which analyzes the output data from material science programs called VASP and Bader. As a Python beginner, I earnestly ask some aces to help me make this code more pythonic, or efficient. Because I know that although the code can run smoothly, it definitely needs more modification from professionals. The code is listed below, with the data file ACF.dat after it.

#!/usr/bin/python
import numpy as np

def charge(x): # function to calculate charge difference
    if x<4:
        return 4-x # atom1
    else:
        return 6-x # atom2

# read from file ACF.dat
f = open('ACF.dat', 'r')
lines = []
for row in f.readlines():
    tmp = row.split()
    lines.append(tmp)

lines = lines[2:-4] # remove unecessary rows
lines = np.array(lines, dtype=float)
lines = lines[:,0:5] # remove unecessary columns

# calculate residual charge
chg = np.vectorize(charge)
lines[:,4] = chg(lines[:,4])

# calculate interatomic distances
dist = []
for i in range(0,len(lines)):
    d = np.sqrt(np.sum((lines[i,1:4]-lines[0,1:4])**2))
    dist.append(d)

lines = np.column_stack((lines, dist)) # attach dist to lines
lines = lines[lines[:,5].argsort()]

for row in lines:
     print '{0:<3.0f} {1:12.6f} {2:12.6f}'.format( row[0], row[5], row[4])

f.close()

ACF.dat

The structure of the file is seen as the heading. What I need are the first five columns: the atomic index, the x, y, z coordinates of each atom, the atomic charge.

#         X           Y           Z        CHARGE     MIN DIST    ATOMIC VOL
--------------------------------------------------------------------------------
1      7.5119      7.5119      7.5119      2.9875      1.1144     20.7692
2     18.0286     18.0286     18.0286      2.8514      1.3688     23.0095
3      6.0058     18.0205     18.0205      2.8500      1.3599     22.9265
4     12.0323     18.0342     18.0342      2.8480      1.3638     22.9816
5     18.0205      6.0058     18.0205      2.8500      1.3599     22.9265
6      5.9968      5.9968     17.9789      2.7979      1.2317     22.3582
--------------------------------------------------------------------------------
VACUUM CHARGE:               0.0000
VACUUM VOLUME:               0.0000
NUMBER OF ELECTRONS:      1085.9999

What the code does is:

Read in the content of ACF.dat, and removes the first two rows and last four rows. Then saves only the first five columns into array lines.
Calculates the residual charge using function charge(x).
Calculates the interatomic distances using the x, y, z coordinates of the atoms, and attach the array of distances to lines as its last column.
Sorts lines according to the interatomic distances (column #6 of lines).
Prints out the atomic index, interatomic distances, and atomic charges.

I understand that this is a lengthy question, but I still would like to ask someone helping me, and other newbies, learn Python faster by optimizing our own code. Any suggestion is welcomed.


texts:
I have trained a polygon detector neural network to recognize the mask of "quadrilateral" (the mask generates curvy lines so it's not exactly a quadrilateral). I would like to get the corners of the quadrilateral.

I believe the best approach is to get the points in the mask that are closest to the corners of the image. First question is, are these valid assumptions? Second question is, is this the best approach?

Top-Left is minimum distance between (0,0) and mask.
Top-Right is minimum distance between (width, 0) and mask.
Bottom-Left is minimum distance between (0, height) and mask.
Bottom-Right is minimum distance between (width, height) and mask.

The last question is, is my implementation slow? The Neural network generates the mask in .7 seconds, but it's taking my loop ~2 seconds to find the corners. Can this be sped up?

def predict(self,img):
    # Read image
    image = img
    height,width,channels=img.shape

    # Detect objects
    r = self.model.detect([image], verbose=0)[0]
    mask=r['masks']
    print(mask)
    x1=0
    x2=0
    x3=0
    x4=0
    y1=0
    y2=0
    y3=0
    y4=0
    minDistanceTopLeft=999999
    minDistanceTopRight=999999
    minDistanceBottomLeft=999999
    minDistanceBottomRight=999999
    xAverage=0.0
    yAverage=0.0
    for x in range(0, len(mask)):
        for y in range(0, len(mask[x])):
            if(mask[x][y]):
                distToTopLeft=(x-0)*(x-0)+(y-0)*(y-0)
                if(distToTopLeft<minDistanceTopLeft):
                    minDistanceTopLeft=distToTopLeft
                    x1=x
                    y1=y
                distToTopRight=(x-width)*(x-width)+(y-0)*(y-0)
                if(distToTopRight<minDistanceTopRight):
                    minDistanceTopRight=distToTopRight
                    x2=x
                    y2=y
                distToBottomLeft=(x-0)*(x-0)+(y-height)*(y-height)
                if(distToBottomLeft<minDistanceBottomLeft):
                    minDistanceBottomLeft=distToBottomLeft
                    x4=x
                    y4=y
                distToBottomRight=(x-width)*(x-width)+(y-height)*(y-height)
                if(distToBottomRight<minDistanceBottomRight):
                    minDistanceBottomRight=distToBottomRight
                    x3=x
                    y3=y
    toReturn=np.array([x1, y1, x2, y2, x3, y3, x4, y4, 1])
    return [toReturn.tolist()]

Mask is a numpy array of booleans:

[[[False]
  [False]
  [False]
  ...
  [False]
  [False]
  [False]]

 [[False]
  [False]
  [False]
  ...
  [False]
  [False]
  [False]]

 [[False]
  [False]
  [False]
  ...
  [False]
  [False]
  [False]]

  ...

 [[False]
  [False]
  [False]
  ...
  [False]
  [False]
  [False]]

 [[False]
  [False]
  [False]
  ...
  [False]
  [False]
  [False]]

 [[False]
  [False]
  [False]
  ...
  [False]
  [False]
  [False]]]


texts:
I am trying to implement AES CTR encryption mode with HMAC authentication for messages.

It's encrypting and decrypting fine as long as the key length is 64 bytes, since AES key and HMAC key are being derived from this key.

Questions

Is it safe to append IV or nonce to the encrypted messages?
Is it safe to append HMAC digest to append to the messages?
Can you review it for best security coding practices?
I am using Pycryptodome

Code

import os
import zlib
from Crypto.Hash import HMAC
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
from Crypto.Util import Counter
import zlib
def encrypt(full_key, plaintext):

    if len(full_key) != 64:
        raise Exception("FULL key length shall be equal to 64")
    key = full_key[:len(full_key) //2]

    # Use the last half as the HMAC key
    hmac_key = full_key[len(full_key) // 2:]

    if isinstance(plaintext, str):
        plaintext = plaintext.encode()

    compressed = zlib.compress(plaintext, 5)
    print (f"compressed plaintext {compressed}")

    # Choose a random, 16-byte IV.
    iv = os.urandom(16)
    # Convert the IV to a Python integer.
    iv_int = int(binascii.hexlify(iv), 16)
    # Create a new Counter object with IV = iv_int.
    ctr = Counter.new(128, initial_value=iv_int)
    # Create AES-CTR cipher.
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)
    # Encrypt and return IV and ciphertext.
    ciphertext = aes.encrypt(compressed)

    hmac_obj = HMAC.new(hmac_key, compressed, SHA256)
    mac = hmac_obj.digest()

    return iv+ciphertext+mac

def decrypt(key, ciphertext):
    # Initialize counter for decryption. iv should be the same as the output of
    # encrypt().

    if len(full_key) != 64:
        raise Exception("FULL key length shall be equal to 64")

    key = full_key[:len(full_key) //2]

    # Use the last half as the HMAC key
    hmac_key = full_key[len(full_key) // 2:]

    mac_length = 32
    iv_length = 16
    iv = ciphertext[:16]
    mac = ciphertext[-mac_length:]

    _ciphertext = ciphertext[iv_length:-mac_length]

    iv_int = int(iv.hex(), 16)
    ctr = Counter.new(128, initial_value=iv_int)
    # Create AES-CTR cipher.
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)

    ciphertext = aes.decrypt(_ciphertext)

    # Extract the MAC from the end of the file
    hmac_obj = HMAC.new(hmac_key, ciphertext, SHA256)
    computed_mac = hmac_obj.digest()

    if computed_mac != mac:
        raise Exception("Messege integrity violated")

    plaintext= zlib.decompress(ciphertext)

    # Decrypt and return the plaintext.

    return plaintext


texts: Grade of Service Probability Function Python

texts:
Consider the following typical probability scenario:

I defined this function to handle that scenario, I'm curious if Python has a more efficient method to handle this, or if this is the best way:
from scipy.special import binom

def grade_of_service(n, p, c):
    prob = 0
    k = c + 1
    while k <= n:
        prob += binom(n, k)*(p**k)*((1-p)**(n-k))
        k += 1
    return prob

EDIT: Here's an example solution from the author of this example:  "If n = 100, p=0.1, and c=15, the probability of interest turns out to be 0.0399."
My probability does round to this result.  But due to the roundoff error / numerical precision, it doesn't seem to matter if k = n or k = n+1.


texts: Formatting options for a long IF statement?

texts:
I have a somewhat unwieldy IF statement and am wondering if anyone has any suggestions on how to make it more readable.

One one line it was all but impossible to understand, so I broke it up into multiple lines:

if (
        empty($row)                                                            // IF the row doesn't exist
    || (!empty($row)                                                           // OR it does exist
        && (     date('j', time()) != date('j', strtotime($row['date_added'])) // AND hasn't been update this day
             && (   empty($row['ignore'])                                      // AND has never been marked to ignore
                 || time()-strtotime($row['ignore']) > 3600*24*7               // OR was last marked to ignore over a week ago
                )
           )
       )
) {
    return $this->updateRow($id);
}
else {
    return 0;
}

However, it's still kind of hard to decipher. I thought about breaking up it into IF/ELSE statements, which makes it a lot more readable, but it also means having redundant code:

if (empty($row)) { // if the row doesn't exist
    return $this->updateRow($id);
}
else { // the row does exist
    if (date('j', time()) != date('j', strtotime($row['date_added']))) {             // if the row hasn't been updated this day
        if (empty($row['ignore']) || time()-strtotime($row['ignore']) > 3600*24*7) { // if the row has never been marked to ignore OR was last marked to ignore over a week ago
            return $this->updateRow($id);
        }
        else { // the row was marked to ignore within the past week
            return 0;
        }
    } // the row has been updated this day
    else {
        return 0;
    }
}

What is the most readable way to format this IF statement?

The first method as it's more concise and has no redundant code
The second method since it's a little more readable (even though it has a lot of redundant code)
A different formatting method


texts: Merge duplicated cells in bulk per each column VBA

texts:
Need to merge data per column if records in the first column are the same.

I wrote a VBA code and it works but it works very slow as it executes "merge" function per each row no matter if consequent cells are the same or different.

Sub DuplicateValues()

'Declare All Variables:

Dim myCell As Range
Dim myRow As Integer
Dim myRange As Range
Dim myCol As Integer
Dim i As Integer
Dim k As Integer

Dim myFirstRow As Long
Dim myFirstColumn As Long

Dim rngCopy As Range, rngPaste As Range

'Count Number of Rows and Columns:

Application.DisplayAlerts = False

myRow = Range(Cells(3, 1), Cells(3, 1).End(xlDown)).Count + 2 'first two rows are headers
myCol = Range(Cells(2, 1), Cells(2, 1).End(xlToRight)).Count

'Apply formatting to the end of the table:

With ActiveSheet
Set rngCopy = .Range(.Range("A3"), .Cells(myRow, myCol))

 With rngCopy.Borders
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .Weight = xlThin
    End With
End With

'Merge duplicated cells per Row:

myFirstRow = 3
myFirstColumn = 1

Set iRow = Cells(myFirstRow, myFirstColumn)
Set n = Cells(myFirstRow + 1, myFirstColumn)

For i = 1 To myRow

    If iRow <> n Then

                Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).HorizontalAlignment = xlCenter
                Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).VerticalAlignment = xlCenter
                Range(Cells(myFirstRow, 8), Cells(myFirstRow, 8)).WrapText = True
                Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).EntireRow.AutoFit

                iRow = Cells(myFirstRow + i, myFirstColumn)
                n = Cells(myFirstRow + i + 1, myFirstColumn)

                Else
                n = Cells(myFirstRow + i + 1, myFirstColumn)

                    For k = 1 To myCol - 3 'need to merge data per column but don't need to merge data in the last 3 columns

                        Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).Merge
                        Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).HorizontalAlignment = xlCenter
                        Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).VerticalAlignment = xlCenter
                        Range(Cells(myFirstRow + i - 1, 8), Cells(myFirstRow + i, 8)).WrapText = True
                        Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).EntireRow.AutoFit

                    Next

    End If
Next

End Sub

I  tried to create a different logic to initiate "merge" by blocks (skip merging the same value cells in the first column right away):
merging only when the "base/initial" cell is not the same as a "check" cell and merge all appropriate cells all together (not by each row), but I can't find a way to make it work.

Would be very grateful for any code optimizations!


texts: why does this programs speed not increase?

texts:
This is the program I was given, it searches a large array for a max value:

import java.util.Date;
import java.util.Random;

class FindMax {
    private static final int N = 256 * 1024 * 1024;

    public static void main(String args[]) {
        assert(N > 0);

        int array[] = new int [N];

        assert(array != null);

        Random random = new Random(new Date().getTime());

        for (int i = 0; i < N; i++) {
            array[i] = random.nextInt();
        }

        Date start = new Date();

        int max = array[0];

        for (int i = 1; i < N; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }

        Date end = new Date();

        System.out.println("max: " + max);
        System.out.println("time in msec: " + (end.getTime() - start.getTime()));
    }
}

I am to increase the speed by having multiple threads each search part of the array. This is what i did:

import java.util.Date;
import java.util.Random;

class FindMax extends Thread{
    private static final int N = 256 * 1024 * 1024;

    static int array[] = new int [N];
    static int max = array[0];
    int start, end;

    public void run(){

        for (int i = this.start; i < this.end; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }

    }
    public FindMax(int q, int u){
        this.start=q;
        this.end=u;

    }

    public static void main(String args[]) {
        assert(N > 0);
        int ts = Integer.parseInt(args[0]);

        assert(array != null);

        Random random = new Random(new Date().getTime());

        for (int i = 0; i < N; i++) {
            array[i] = random.nextInt();
        }

        Date start = new Date();

        Thread t[] = new Thread[ts];
        int eacht = (256 * 1024 * 1024)/ts;

        for( int p=0; p<ts;p++){
            t[p] = new FindMax(0+p*eacht, (eacht-1)+p*eacht);
            t[p].start();
        }

        Date end = new Date();

        System.out.println("max: " + max);
        System.out.println("time in msec: " + (end.getTime() - start.getTime()));
    }
}

The problem is that is has the opposite effect. The more threads (taken from command line argument) the LONGER the program takes to run. Why is this doing the exact opposite of increasing the programs speed with increased threads created?


texts: Check value existence in two lists and gather the result in a csv

texts:
I have two lists of protein sequences, I have to check every entry's existence in the two lists, say like

list A = [1,2,3,4]
list B= [3,4,5]

result = [
[1, true, false],
[2, true, false],
[3, true, true],
[4, true, true],
[5, false, true]
]

I did it this way. Not sure if it's the right way

def FindDifferences():
    df1 = pd.read_csv('Gmax_v6_annotation_info.txt', names=['name'], usecols=[0], delimiter='\t')
    df2 = pd.read_csv('Gmax_v9_annotation_info.txt', names=['name'], usecols=[2], delimiter='\t')
    v6_set = set(df1['name'])
    v9_set = set(df2['name'])
    result = []
    for val in v6_set:
        if val in v9_set:
            result.append([val, True, True])
        else:
            result.append([val, True, False])
    for val in v9_set:
        if val not in v6_set:
            result.append([val, False, True])
    result_df = pd.DataFrame(result, columns=['name', 'inv6', 'inv9'])
    result_df.to_csv('result_csv.csv', index=False, header=False)
    return


texts: Cards for Monster, Spell and Trap interfaces

texts:
So I wrote a card game in Java/JavaFX but I don't particularly like this solution and I was wondering if you guys have any better solutions:

public static CardNode get(Card card, double nodeWidth, double nodeHeight, double imageWidth, double imageHeight) {
    if (card.isMonster()) {
        MonsterCardNode cardNode = new MonsterCardNode(nodeWidth, nodeHeight, imageWidth, imageHeight);
        cardNode.setCard(card);
        return cardNode;
    } else if (card.isSpell()) {
        SpellCardNode cardNode = new SpellCardNode(nodeWidth, nodeHeight, imageWidth, imageHeight);
        cardNode.setCard(card);
        return cardNode;
    } else if (card.isTrap()) {
        TrapCardNode cardNode = new TrapCardNode(nodeWidth, nodeHeight, imageWidth, imageHeight);
        cardNode.setCard(card);
        return cardNode;
    }
    return null;
}

CardNode and Card are abstract classes. They both implement interfaces Monster, Spell and Trap. Methods isMonster, isSpell, isTrap return a boolean and are essentially instanceof and flag checks. I was wondering if there is any better way to handle this with polymorphism.

Here is the usage of that static method.

model.getPlayer().getHand().addListener((ListChangeListener.Change<? extends Card> change) -> {
    while (change.next()) {
        if (change.wasAdded()) {
            change.getAddedSubList().forEach((card) -> {
            Platform.runLater(() -> {
                    CardNode cardNode = CardNode.get(card, 105, 145, 96, 105);
                    view.getPlayerView().getHand().getChildren().add(cardNode);
                });
            });
        }
    }
});


texts:
This is HtDP Excercise 12.4.2:

  Develop a function insert-everywhere. It consumes a symbol and a list
  of words. The result is a list of words like its second argument, but
  with the first argument inserted between all letters and at the
  beginning and the end of all words of the second argument.

This is what I wrote:

#lang racket

;Data Definition:
;a symbol, list of symbols

;Contract:
;insert-everywhere: symbol, list of symbols -> list of list of symbols
;The function returns a list of list of symbols wherein the symbol is inserted at every position

;Example:
; (insert-everywhere 'a '(b c d)) -> '((a b c d) (b a c d) (b c a d) (b c d a))

;Definition:

(define (insert-everywhere sym los)
  (define lst-len (find-len los))
  (define (iter n)
    (cond ((= n (+ lst-len 1)) '())
          (else (cons (insert n sym los) (iter (+ n 1))))))
  (iter 0))
;The above function first finds the list length.
;Then it itereratively inserts the symbol at every position one by one, including in the end.

;Data Definition:
;list of symbols

;Contract:
;find-len : list of symbols-> number
;find the length of the list

;Example:
;(find-len (list 'b 'c 'd)) -> 3

;Definition:

(define (find-len los)
  (cond ((null? los) 0)
        (else (+ 1 (find-len (cdr los))))))

;Data Definition:
;number , symbol, list of symbols

;Contract:
;insert : position, element, list of symbols-> list of symbols
;insert the element in the given position in the list

;Example:
;(insert 2 'a '(b c d)) -> '(b c a d)

;Definition:

(define (insert pos elm los)
  (cond ((= pos 0) (cons elm los))
        (else (cons (car los) (insert (- pos 1) elm (cdr los))))))

Here is the tests I conducted:

(insert-everywhere 'a '()) ; returns '((a))
(insert-everywhere 'a '(b)) ; returns '((a b) (b a))
(insert-everywhere 'a '(b c d)) ; returns '((a b c d) (b a c d) (b c a d) (b c d a))

It works, but I think this is not the way it was supposed to be solved. In their hint, they ask to use only recursion and append, but I didn't really get it. Could someone suggest a better answer?


texts: Extract Element and its Followers from List

texts:
I wrote the following function to convert List[Int] => List[List[Int]].

Its intended purpose is to extract 1, followed by its non 1 followers, into a group.

input: List(1,2,2,1,3,3)

output: List( List(1,2,2), List(1,3,3) )

Function

def leadingOnesGroup(xs: List[Int]): List[List[Int]] =
        xs match {
          case Nil    => Nil
          case _ :: _ =>
           val (first, rest)          = xs.span(_ == 1)
           val (followers, remainder) = rest.span(_ != 1)
           (first ++ followers) :: leadingOnesGroup(remainder)
      }

Testing

scala> leadingOnesGroup(List(1,2,2))
res19: List[List[Int]] = List(List(1, 2, 2))

scala> leadingOnesGroup(List(1,2,2,1,3,3))
res20: List[List[Int]] = List(List(1, 2, 2), List(1, 3, 3))

scala> leadingOnesGroup(List(1,2,2,1,3,3,1,5,5))
res21: List[List[Int]] = List(List(1, 2, 2), List(1, 3, 3), List(1, 5, 5))


texts: Splitting text into lines from a max width value for CANVAS

texts:
Ok so this works as is, and is not actually slow at all (from what I can see) - However I don't like the taste of nested while loops and was wondering if anyone could give some insight on a different approach? Or how to improve mine to take away the while() { while() {}}

Here it is:

/* takes a string and a maxWidth and splits the text into lines */
 // ctx is available in the parent scope.
function fragmentText(text, maxWidth) {
    var words = text.split(' '),
        lines = [],
        line = "";
    if (ctx.measureText(text).width < maxWidth) {
        return [text];
    }
    while (words.length > 0) {
        while (ctx.measureText(words[0]).width >= maxWidth) {
            var tmp = words[0];
            words[0] = tmp.slice(0, -1);
            if (words.length > 1) {
                words[1] = tmp.slice(-1) + words[1];
            } else {
                words.push(tmp.slice(-1));
            }
        }
        if (ctx.measureText(line + words[0]).width < maxWidth) {
            line += words.shift() + " ";
        } else {
            lines.push(line);
            line = "";
        }
        if (words.length === 0) {
            lines.push(line);
        }
    }
    return lines;
}


texts: Excel VBA: Implementing Box Muller, Zigurrat and Ratio of Uniforms Algorithm

texts:
This is a very specific question mixing up stochastic knowledge and VBA skills. So very exciting!

I'm trying to compare several methods for generating standard, normally distributed numbers given a source of uniformly distributed random numbers. Therefore I'm implementing the Box Muller Algorithm, Ziggurat Algorithm and Ratio of Uniforms Algorithm. Every single implementation works great in terms of generating a clean standard, normally distribution. (checked by Shapiro-Wilk-Test).

What I want to find out: which is the quickest method?

Testing every single program with a total of 10^7 generated numbers these are the run times:

Box-Muller: 3,7 seconds
Ziggurat: 1,28 seconds
Ratio of Uniforms: 10,77 seconds

Actually I am very happy about those readings, because I didn't expect it to be that fast. Of course the run time of every single method also depends on my programming skills and VBA knowledge.

My problem: after doing some research I found out that the Ratio of Uniforms Algorithm should be the quickest (about 3 to 4 times quicker than Box Muller). This information just leans on this stack:

I am curious if this is just a wrong claim of this user or (what I do expect more) if my code is not perfectly implemented. Therefore I'll post my code and hope someone could help me with my question, if my code is just not good enough or if the Ratio of Uniforms just doesn't work that quick as mentioned.

Sub RatioUniforms()

Dim x(10000000) As Double
Dim passing As Long
Dim amount As Long: amount = 10000000
Dim u1 As Double
Dim u2 As Double
Dim v2 As Double

    Do While passing <= amount
        Do
            u1 = Rnd    'rnd= random number(0,1)
        Loop Until u1 <> 0  'u1 musn't become 0
        v2 = Rnd
        u2 = (2 * v2 - 1) * (2 * exp(-1)) ^ (1 / 2)
        If u1 ^ 2 <= exp(-1 / 2 * u2 ^ 2 / u1 ^ 2) Then
            x(passing) = u2 / u1
            passing = passing + 1
        End If
    Loop

 End Sub

Thank you very much helping me on this topic. Maybe some of you have tried those algorithms in VBA or other languages and can help me with there experience about the run time? If you need something else to know about my other implementations just let me know. Have a great day!


texts: Coding standard and Readability: Verbose/Redundant statements vs Short/Compressed

texts:
I have the following 3 different versions of code.
Version 1 is overly verbose and contains redundancy but on the other hand seems easier to read. Version 2 is somewhere in the middle, and Version 3 is shortened and straight to the point.

Their all equivalent in terms of functionality. I am not sure about readability.
According to best practices which is the best? Please add actual pros-cons based on theory.
Is there a chance situations like these are also determined by programming style and hence are opinion based as opposed to having black/white clear guidelines?

Version 1:

for (int i = 0; i < resultsSize; i++)
            {
                bundle = ja.getJSONObject(i).getString(SOLR_BUNDLEID_FIELD);
                app = DataStore.applicationsCache.get(bundle);
                if (app!=null)
                {

                    if(catalogRequest.filter.query_pub==null)
                    {
                        addApp(DataStore.applicationsCache.get(bundle),preparedApps);
                        continue;
                    }

                    if(app.vendor.equalsIgnoreCase(catalogRequest.filter.query_pub))
                        addApp(DataStore.applicationsCache.get(bundle),preparedApps);
                }

            }

Version 2:

for (int i = 0; i < resultsSize; i++)
            {
                bundle = ja.getJSONObject(i).getString(SOLR_BUNDLEID_FIELD);
                app = DataStore.applicationsCache.get(bundle);
                if (app!=null)
                {
                    if(catalogRequest.filter.query_pub==null || app.vendor.equalsIgnoreCase(catalogRequest.filter.query_pub))
                    addApp(DataStore.applicationsCache.get(bundle),preparedApps);
                }

            }

Version 3:

for (int i = 0; i < resultsSize; i++) {
                if ((app = DataStore.applicationsCache.get(ja.getJSONObject(i)
                        .getString(SOLR_BUNDLEID_FIELD))) != null
                        && (catalogRequest.filter.query_pub == null || app.vendor
                                .equalsIgnoreCase(catalogRequest.filter.query_pub)))
                    addApp(app, preparedApps);
            }