texts: Summing different tables values limiting the results

texts:
I have two tables (a and b) which have both one date field of type TIMESTAMP. They represent two different type of actions (records): table a's actions are $200 worth each, while table b's ones worth $500.

I want to calculate the total count of dollars worth of both tables actions limiting the maximum number or dollars per day to $10.000. Is there a more clean or efficient way to do this other than:

SELECT SUM(daily_sum_total) AS total
FROM (
    SELECT CASE WHEN SUM(daily_sum) > 10000 THEN 10000 ELSE SUM(daily_sum) END AS daily_sum_total, day
    FROM (
        SELECT COUNT(date) * 200 AS daily_sum, DATE(date) AS day
        FROM a
        GROUP BY day
        UNION ALL
        SELECT COUNT(date) * 500 AS daily_sum, DATE(date) AS day
        FROM b
        GROUP BY day
    ) AS daily_tmp_table
    GROUP BY day
) as total_tmp_table;


texts:
Here is a JSFiddle of an accordion menu that i've done. I have used :before to add the icons.

My question is, is there a better way to Add different icon to each li item?

My code is as follows:

HTML Structure:

Profile

Messages

Inbox

Sent

Drafts

Settings

Logout

CSS:

    body {
background-image: url(http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tiny_grid.png);
}

ul{
  list-style-type:none;
  padding:0;
  margin:0;
}

#accordion{
  margin: 20% auto 80% auto;
  width:200px;
  height:auto;
  background-color:#212830;
  border-radius:5px;
  color: #BECEDB;
  font-family: 'Maven Pro', sans-serif;
  border: 1px solid #191E24;
  box-shadow: 0px 0px 5px 2px #666666;
}

#accordion > li > div{
  background-color:#383C48;
  font-weight:700;
  -moz-box-shadow:inset 0 1px 1px -1px #A1B3C9;
  -webkit-box-shadow:inset 0 1px 1px -1px #A1B3C9;
  box-shadow:inset 0 1px 1px -1px #A1B3C9;
  border-bottom:1px solid #191E24;
}

#accordion > li > div, #accordion > li > ul > li{
  padding:10px 15px;
}

#accordion li{
  cursor:pointer;
}

#accordion > li:first-child >div{
  border-radius: 5px 5px 0 0;
}

#accordion > li:last-child >div{
  border-radius: 0 0 5px 5px;
}

#profile:before,
#messages:before,
#settings:before,
#logout:before,
.submenu>li:before
{
  font-family:FontAwesome;
}

#profile:before{
  content:"\f007  ";
}
#messages:before{
  content:"\f0e0";
}

#settings:before{
  content:"\f013";
}

#logout:before{
  content:"\f08b";
}

.submenu li:before{
  content:"\f0da"
}

#accordion *:before{
  margin-right:10px;
}

.submenu li{
  margin-left:10px;
}

JS code: (No problem with this)

 $("#accordion > li > div").click(function(){
  if(false == $(this).next().is(':visible')){
        $('#accordion ul').slideUp(400);
    }
  $(this).next().slideToggle(300);
 });

$('#accordion ul:eq(0)').show();

Also I would like to know if there are other areas this can be optimized.
Thank you


texts: Increasing speed of Project Euler #14 - Longest Collatz Sequence

texts:
I'm solving Project Euler problems and uploading my solutions to GitHub. Some of my solutions are just based on math and are thanks to that very fast, but #14 is way too slow, and I have no idea how to optimize it.

"""
Longest Collatz sequence
------------------------

The following iterative sequence is defined for the set of positive integers:
n  n/2 (n is even)
n  3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13  40  20  10  5  16  8  4  2  1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.

Approach:

A function `collatz` which returns the number of terms in the chain, given it's starting position.
It goes trough the sequence, but It also remembers previous ones using a global dictionary.
Get the maximum one.
"""

collatz_counts = {}

def collatz(n):
    count = 1
    start = n
    while n!=1:
        if n in collatz_counts:
            count += collatz_counts[n]
            break
        if n%2==0: n/=2
        else: n = 3*n+1
        count += 1

    collatz_counts[start] = count
    return count

answer = max(((collatz(i),i) for i in range(1,1000000)))
print("The starting position generating the longest sequence is {0}".format(answer[1]))


texts: CRUD operation in controller for different objects

texts:
I am working on AngularJS project. Our project contains lot of controllers and each controller having more functions. I want controllers should be clean and simple. What are the ways to modify the structure of AngularJS application to make it good and simple?

Below controller and service contains the operation for calling MVC action methods to create/retrieve/update and delete the user in database.

controller.js

var adminApp = angular.module('adminApp', ['ngResource', 'angularSpinners']);

adminApp.controller('adminCtrl', function ($scope, $rootScope, AdminService, spinnerService, $q, $window, $location) {

    $scope.deleteUser = function () {
        AdminService.deleteuser({
            id: $scope.currentUserId
        }).$promise.then(function (message) {
            $scope.loadUsers();
        }, function (error) {});
    }

    $scope.updateUser = function (user) {
        var updateddata = {
            "userid": user.UserId,
            "roleid": user.setrole.id
        }
        AdminService.updateUser({
            user: updateddata
        }).$promise.then(function (message) {
            $scope.loadUsers();
        }, function (error) {});
    }

    $scope.saveUser = function () {
        var userData = {
            "email": $scope.useremail,
            "role": $scope.selectedRole.name,
            "roleid": $scope.selectedRole.id
        };
        spinnerService.show('html5spinner');
        AdminService.postUserData({
            user: userData
        }).$promise.then(function (data) {
            if (data.Errors && data.Errors.length > 0) {
                for (var i = 0; i < data.Errors.length; i++) {
                    var error = data.Errors[i].toLowerCase();
                    if (error.indexOf("email") != -1) {
                        $scope.emailAlreadyExist = true;
                    }
                }
            } else if (data.ErrorType && data.ErrorType.toLowerCase() === "invalidad") {
                $scope.invalidActiveDirectory = true;
            } else {
                $scope.reset();
            }
            spinnerService.hide('html5spinner');

        }, function (error) {});
    }

    $scope.loadUsers = function () {
        AdminService.getUsers().$promise.then(function (usersData) {
            $scope.users = usersData;
        });
    };

    /* End DNA Team */
});

service.js

adminApp.factory('AdminService', function ($resource) {
    return $resource('', {}, {

        getUsers: {
            url: '/Admin/GetUsers',
            method: 'GET',
            isArray: true
        },

        postUserData: {
            url: '/Admin/PostUser',
            method: "Post",
            isArray: false,
            params: {
                user: '@userData'
            }
        },
        updateUser: {
            url: '/Admin/UpdateUser',
            method: "Post",
            isArray: false,
            params: {
                user: '@updateddata'
            }
        },
        deleteuser: {
            url: '/Admin/DeleteUser/:id',
            method: "Post",
            isArray: false,
        }
    });
});

Similarly I have lot of other CRUD operation in same controller for different objects. If I push all CRUD operation in the same controller the controller looks big and not well readable. I need suggestion on how to simplify the controller by keeping separate module for each object.


texts:
simpler pattern/extension built on top of telepot (telegram bot api wrapper)

filter usage

from nimmy import Bot
from re import match, search

bot = Bot("TELEGRAM_BOT_API_TOKEN")

# filter model function returns, keys return None on failure
def adminOnly(msg):
    return {
        'admin': match('fatzombi', msg.chat['username'])
    }

def ping(msg):
  return {
    'text': search("^ping\s(.*)", msg.text)
    }

# executes only when filtering contents match takes filter function and check type: any or all
@bot.filter(adminOnly)
@bot.filter(ping)
def handle_this(msg):
  from subprocess import check_output

  hostname = msg.filter['text'].group(1)
  response = check_output(['ping', '-c 1', hostname])

  bot.sendMessage(msg.chat['id'], response)

  # feed the monitor!
  print("ping -> " + hostname)

# takes filtered functions as handle, binded on message_loop
bot.add_handle(handle_this)

# a simple run forever loop, takes message_loop args as loop={}
bot.run_forever()

from telepot import Bot
from functools import wraps
from nimmy.utils import Map

telepot.Bot extended

class Bot(Bot):
    """
    extending telepot.Bot
    """
    bot_functions = {}

    def _filter(self, filter_model, message, check):
        # checks for any exceptions with filters, find None, true or false
        try:
            filters = filter_model(message)

            if check(filters.values()):
                return filters
        except:
            return False

    def filter(self, filter_model, check=all):
        # argumented decoration, returns func with msg
        def decorator(func):
            # prevents cloning
            @wraps(func)
            def wrapper(msg):
                # converts dict to object with utils.Map
                message = Map(**msg)
                filterd = self._filter(filter_model, message, check)

                if filterd:
                    message.filter = filterd
                    return func(message)
            return wrapper
        return decorator

    def run_forever(self, sleep_for=10, **loop):
        # telepot message_loop with dummy_handler
        print('Loading ...')
        self.message_loop(self.dummy_handler, **loop)

        from time import sleep
        # simple loop sleeps: sleep_for
        while 1:
            sleep(sleep_for)

    def add_handle(self, handle):
        # add filter handles to a list
        try:
            Bot.bot_functions[id(self)]
        except KeyError:
            Bot.bot_functions[id(self)] = []

        Bot.bot_functions[id(self)].append(handle)

    def dummy_handler(self, msg):
        # acts like a handle returns a list of handles and execute
        return [h(msg) for h in Bot.bot_functions[id(self)]]


texts: Find non-duplicated integer in a list where every integer occurs three times except for one integer

texts:
The task

  Given an array of integers where every integer occurs three times
  except for one integer, which only occurs once, find and return the
  non-duplicated integer.

  For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13,
  13], return 19.

  Do this in O(N) time and O(1) space.

My solution

const arr = [6, 1, 3, 3, 3, 6, 6];
const findUnique = arr => {
  const set = new Set();
  return arr.reduce((sum, n) => set.has(n) ?
                    sum - n :
                    (set.add(n), sum + 2 * n), 0) / 2;
};

Because of the Set it has O(n) space, I guess. I currently don't know how to solve it with O(1) space.


texts: Dynamically loading CSS files based on URL or URI in PHP

texts:
I have written out the following code in the head section of my document,
which should load 3 separate style sheets for each page based on the URL/URI that the user is visiting. It is working as intended as tested with the comment in the code but I am wondering if there is a more efficient way to do this. I initially started writing out a switch statement, but chose to try if else statements before.

Also I have added this part:

 || $_SERVER['PHP_URL_PATH']

to each statement in case there is an error of some kind with the first expression. It seems to be working whether I use just ['PHP_URL_PATH']
or the full $_SERVER['PHP_URL_PATH'].

My questions are:

Which out of the two would be more efficient (switch or if else)?
Is the second declaration of $_SERVER actually necessary, or will it work without this specificity?

Any improvements that people could point me to would be greatly appreciated.

PS: I have removed all the echo's for including the actually <link>'s to the CSS files.

This has been tested and is showing to work in Firefox Developer Edition so guessing it's ok, but could be improved maybe; what about scalability, or any security concerns? I am new so please advise or help.

// Create Logic here to include various different style sheets.

if($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH']  === "/mainHubV8.1.php"){
    echo "Loading Styles for MainHubV8.1.php";

    }
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/advSearchV8.1.php"){
    echo "Loading Styles for advSearchV8.1.php";

    }
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/loginOrSignUpV8.1.php"){
    echo "Loading Styles for loginOrSignUpV8.1.php";

    }
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/profilePageV8.1.php"){
    echo "Loading Styles for profilePageV8.1.php";

    }
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/chatApllicationV8.1.php"){
    echo "Loading Styles for chatApllicationV8.1.php";

    }
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/onlineUsersV8.1.php"){
    echo "Loading Styles for onlineUsersV8.1.php";

    }
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/index.php"){
    echo "Loading Styles for index.php";

    }
else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/404"){
    echo "Loading Styles for error page";

    }

Is there a better alternative to achieving the same goal? If so could you please provide reference or articles/Question & answers anywhere on Stack Exchange or some other resource. Plus I do not want to use Javascript or JQuery really as these can be turned off and disabled. So PHP seems more appropriate.


texts: Data retrieval from Dynamic HTML page with time-out (Web scraping w. Python)

texts:
The HTML page shows list of a friend network of a person (each Name has anchor <a> tag w. link to list of friend network). Since the page has a timer, I've written a py code to scrap the mth position (friend) of the nth count (page) by traversing through the cycle: (m->n->m->n....). And it works!

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter URL: ')
position = int(input('Enter position: '))  #Name/link Traverse
count = int(input('Enter count: ')) #Page Traverse
print("Retrieving:", url)
for c in range(count):      #returns range of indices
    html = urllib.request.urlopen(url, context=ctx).read() #opening URL
    soup = BeautifulSoup(html, 'html.parser')
    a_tags=soup('a')
    link=a_tags[position-1].get('href', None) #url = href(key) value pair
    content=a_tags[position-1].contents     #name=a_tag.contents
    url=link
    print("Retrieving:", url)

Input:

Enter URL: http://py4e-data.dr-chuck.net/known_by_Kory.html
Enter position: 1
Enter count: 10

Output:

Retrieving: http://py4e-data.dr-chuck.net/known_by_Kory.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Shaurya.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Raigen.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Dougal.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Aonghus.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Daryn.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Pauline.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Laia.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Iagan.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Leanna.html
Retrieving: http://py4e-data.dr-chuck.net/known_by_Malakhy.html

Questions:

Is there a better way to approach this? (libraries, workarounds to delay the timer)
My goals is to make an exhaustive 'list' of friends of all unique Names here; I don't want any code, just suggestions and approaches will do.


texts:
I am quite new in Python and I am starting my journey with sorting algorithms, PEP8 and the Zen of Python. I would like to get some feedback about my BubbleSort algorithm which I wrote.
Also, is there a possibility to change the break statement to something else which will stop the loop?

def bubble_sort(structure):
    """
        Bubble sort.

        Description
        ----------
        Performance cases:
        Worst      : O(n^2)
        Average    : O(n^2)
        Best case  : O(n)

        Parameters
        ----------
        structure : Mutable structure with comparable objects.

        Returns
        -------
        structure : return sorted structure.

        Examples
        ----------
        >>> bubble_sort([7,1,2,6,4,2,3])
        [1, 2, 2, 3, 4, 6, 7]

        >>> bubble_sort(['a', 'c', 'b'])
        ['a', 'b', 'c']

    """

    length = len(structure)

    while True:
        changed = False
        for i in range(length - 1):
            if structure[i] > structure[i + 1]:
                structure[i], structure[i + 1] = structure[i + 1], structure[i]
                changed = True
        if not changed:
            break
    return structure


texts:
I have solved Leetcode climbing-stairs problem which is stated as:

  There are n stairs, a person standing at the bottom wants to reach the
  top. The person can climb either 1 stair or 2 stairs at a time. Count
  the number of ways, the person can reach the top.

I used dynamic programming to solve this like below:

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n==1:
            return 1
        dp = [0 for i in range(n+1)]
        dp[1] = 1
        dp[2] = 2
        for i in range(3,n+1):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[n]

Is there any improvement of this code?
Is there any alternative way rather than dynamic programming?


texts:
I have a class with 3 properties, and I would like to know how I can write my code better. I want to use Single.TryParse so that if any token is unknown string, I could still get 0. But using this method, I need to use a temp variable, and as my properties list increases, I will have more temp variable, and this is not efficient. Is there any way to code this better?

public class GSA : NMEAMsg
{
    public float Pdop { set; get; }
    public float Hdop { set; get; }
    public float Vdop { set; get; }

    protected override void parseTokens(string[] tokens)
    {
        float pdop = 0;
        float hdop = 0;
        float vdop = 0;

        Single.TryParse(tokens[tokens.Length - 3], out pdop);
        Single.TryParse(tokens[tokens.Length - 2], out hdop);
        Single.TryParse(tokens[tokens.Length - 1], out vdop);

        Pdop = pdop;
        Hdop = hdop;
        Vdop = vdop;
    }
}


texts:
I am trying to write a constructor method that takes dd, hh, mm and ss as parameters and change it as a normal type of Time struct (e.g you enter 25 hours as the hh parameter, it changes it to 1 day and 1 hour).

struct Time
{
    public Time(int dd, int hh, int mm, int ss)
    {
        seconds= ss % 60;
        minutes = mm % 60;
        hours = hh % 24;
        days = dd % 7;
        if (ss > 60)
        {
            minutes++;
        }
        if (mm > 60)
        {
            hours++;
        }
        if (hh > 24)
        {
            days++;
        }
    }
    private int days, hours, minutes, seconds;
    public void Write()
    {
        Console.WriteLine("It has been " + days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds.");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Time t = new Time(5, 28, 65, 55);
        t.Write();

        Console.ReadKey();
    }
}

The program works, but it feels very simple and amateurish. Is there anything I could do to make it more robust?


texts: Optimize Sieve of Eratosthenes for big numbers in Python

texts:
I'm solving Euler exercise number 7 and trying to go a bit further on bigger primes.
It is too slow with big numbers. I've been reading ways to optimize the sieve, but I would like to ask people with more experience with this.
import time
from math import log, ceil

start = time.time()
primes = [2]
op_count = 0
limitN = 0
pr_count = 0

def primes_goto(prime_index):
    global primes
    global op_count
    global limitN
    global pr_count

    if prime_index < 6:
        limitN = 100
    else:
        limitN = ceil(prime_index * (log(prime_index) + log(log(prime_index)))) #bound

    not_prime = set()

    while pr_count < prime_index:
        for i in range(3, limitN, 2):
            if i in not_prime:
                continue

            for j in range(i*3, limitN, i*2):
                not_prime.add(j)

            primes.append(i)
            pr_count += 1

    return primes

ind = int(10001)
primes_goto(ind)
ind_prime = primes[ind-1]

end = time.time()

print("Prime number at posizion: {} = {}".format(ind, ind_prime))
print("Runtime: {}".format(end-start))


texts:
Here is a program that will parse and print XML feed URLs. I want to reuse most of it to add post date to each link. This adds a new concern of CLI and output formatting on top of parsing and (poor) error handling. I wonder how much of this code has enough value to put is in a wrapper utility and how much should be simply scrapped and basically left to user.

I also wonder whether Text.Feed has enough value to use it (it's just XML represented by datatype) and I'm just traversing it.

module Main (main, extract) where

import Text.Feed.Import
import Text.Feed.Query (getItemLink, getFeedItems)
import Data.Maybe
import Control.Monad

validate x = case x of
  Nothing -> error
  Just v  -> const v

extract selector feedString = selector $ (flip validate) "feed parsing failed" . parseFeedString $ feedString

main :: IO ()
main = do
  feedString <- getContents
  mapM_ putStrLn $ extract selector feedString
    where
      selector = getFeedItems >=> (maybeToList . getItemLink)


texts:
I created a function that will return 2 dates that depend on an input parameter.

When the parameter is:

1  - return start date of current week and end date of current week
2  - return start date of last week and end date of last week
3  - return start date of current month and end date of current month
4  - return start date of last month and end date of last month

Could you please suggest improvements? And what name would be more appropriate for this function?

CREATE FUNCTION [ufn_GetRangeOfDates]
( @Type int
)
RETURNS @Result TABLE
( StartDate date
, EndDate date
)
AS
BEGIN

  declare @Today date = GetDate()

  -- current weak
  declare @CurrentWeakStart date = dateadd(day, 1-datepart(dw, @Today), CONVERT(date, @Today))
  declare @CurrentWeakEnd date = dateadd(day, 7-datepart(dw,  @Today), CONVERT(date,  @Today))
  -- last week
  declare @LastWeakStart date = DATEADD(dd, DATEPART(DW,@Today)*-1-6, @Today)
  declare @LastWeakEnd date =DATEADD(dd, DATEPART(DW,@Today)*-1, @Today)
  --current month
  declare @CurrentMonthStart date = DateAdd( day, 1 - Day( @Today ), @Today )
  declare @CurrentMonthEnd Date = DateAdd( day, -1, DateAdd( month, 1, @CurrentMonthStart ) )
  -- last month
  declare @LastMonthStart date = DATEADD(MONTH, DATEDIFF(MONTH, 0, @Today)-1, 0)
  declare @LastMonthEnd date = DATEADD(MONTH, DATEDIFF(MONTH, -1, @Today)-1, -1)

  insert into @Result
  select CASE @Type
           WHEN 1 THEN @CurrentWeakStart
           WHEN 2 THEN @LastWeakStart
           WHEN 3 THEN @CurrentMonthStart
           WHEN 4 THEN @LastMonthStart
           ELSE NULL
         END
  ,      CASE @Type
           WHEN 1 THEN @CurrentWeakEnd
           WHEN 2 THEN @LastWeakEnd
           WHEN 3 THEN @CurrentMonthEnd
           WHEN 4 THEN @LastMonthEnd
           ELSE NULL
         END
  RETURN
END -- End of ufn_GetRangeOfDates


texts: Finding the longest word from a list of words

texts:
I have a list of words (with repetitions), and I intend to find out the longest words amongst them, along with their length. My question is to know if my implementation is too verbose, is using too many operators/functions and if so, what are the better, more idiomatic, readable alternatives.

Given the list below, the expected output is

 Max length=3, words are "mnp","pqr","jkl","abc","xyz"

    val line = List("a","ab","abc","xyz","mnp","ac","d","b","ab","bc","bd","be","bf","b","abc","abc","pqr","mnp","jkl","a","b")

    val lengthAndTheWords = line.map(x => (x.length,x)).groupBy(x => x._1).mapValues(x => x.toSet)
    val longest = lengthAndTheWords.toSeq.sortBy(key => -key._1).head

    println("Max length =" +
            longest._1 +
            ", words are" +
            longest._2.map(nextEntry => nextEntry._2).mkString(","))

(With an Ideone running the code)

I consider myself an intermediate level Scala programmer; so, I am looking for all tips to improve my skills in Scala.


texts: Translation function - one word set to another

texts:
I have this Excel VBA function that takes three parameters. It is essentially a translation mechanism with the following parameters:

A sentence which has to be translated.
A range of words to look for and what to translate them to.
Shows in which column the translation is in the range (usually it's 2).

This function works perfect with small 'vocabulary', but when the range gets big and many translations occur, my file can become so difficult it loads in 15 minutes. I have no ideas how to make this code simpler because I'm new to VBA. Could anyone give me advice?

Function FindSubStringAndReplaceRange(sentence As String, range As range, selected As Integer)
    Dim position As Integer
    Dim searchableLength As Integer
    Dim newSentence As String
    Dim intASCII As Integer

    Dim searchable As String
    Dim replaceWith As String

    FindSubStringAndReplaceRange = sentence

    For Each i In range.Rows
        If IsEmpty(i.Cells(1, 1)) = False Then

            searchable = i.Cells(1, 1)

            If IsEmpty(i.Cells(1, selected)) = False Then
                replaceWith = i.Cells(1, selected)
            Else
                replaceWith = vbNullString
            End If

            searchableLength = Len(searchable)
            position = InStr(UCase(FindSubStringAndReplaceRange), UCase(searchable))
            If position <> 0 Then
                intASCII = Asc(Right$(Left$(FindSubStringAndReplaceRange, position), 1))

                If intASCII >= 65 And intASCII <= 90 Then
                    replaceWith = UCase(Left$(replaceWith, 1)) + Right$(replaceWith, Len(replaceWith) - 1)
                End If

                FindSubStringAndReplaceRange = Left$(FindSubStringAndReplaceRange, position - 1) + replaceWith + Right$(FindSubStringAndReplaceRange, Len(FindSubStringAndReplaceRange) - (position + searchableLength - 1))

            End If
         End If
    Next

End Function


texts:
I'm pretty new to web development and I don't know if my solution is OK according to the best practices, considering performance and clean code.

I have a Merchant model that belongs to a Price model.

Price table:

create_table "prices", force: :cascade do |t|
  t.string   "price_range"
  t.integer  "percentile"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
end

The current values inside the table:

**price_range**    **percentile **
Up to $20.00            20
$20.01 to $40.00        40
$40.01 to $60.00        60
$60.01 to $80.00        80
More than $80.00       100

To show this at my view I'm using:

  <div class="full-prices" style= width:"<%= "#{@merchant.price.percentile}%" %>

According to the width value the dollar signals will be colored (the CSS part of code is in the jsFiddle link).

jsFiddle

I'm not sure about that approach. Can anyone recommend a finer solution to achieve the same or is that OK?


texts: Is there a better way of making an NSString with many argument values?

texts:
I have a form that I'm turning into a string value for an email, but the string value that I turn it into seems very complicated, plus I believe this way takes up a lot of memory and is somewhat slow as well. Is there any other way to make a NSString with many arguments besides using [NSString stringWithFormat:]?

Here is what I'm doing now:

strMessage = [NSString stringWithFormat:@"%@\n\n%@\n\n%@\n%@\n%@, Il\n%@\nPhone: %@\nEmail: %@", detailsText.text, nameText.text, addrLn1Text.text, addrLn2Text.text, cityAddrText.text, zipAddrText.text, phoneNumberText.text, emailText.text];


texts: Write it better/neat/fast (if condition)

texts:
How to write following if condition clean/fast/readable.
Any one of the fields 'address', 'city', 'district', 'province' can be null. I want to make full address by concat all these fields. Like

address = "Street # 32"
city = "My City"
District = "New York"
Province = "NY"

fullAddress = "Stree #32, My City, New York, NY"

If any information is missing then don't add this in string like if district is missing then don't include it.

address = "Street # 32"
city = "My City"
District = ""
Province = "NY"

fullAddress = "Stree #32, My City, NY"

Following code I have written but not good.

string address = dr["Address"].ToString();
string city = dr["City"].ToString();
string district = dr["District"].ToString();
string province = dr["Province"].ToString();
string fullAddress = "";

if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(district) && !string.IsNullOrEmpty(province))
{
    fullAddress = address + ", " + city + ", " + district + ", " + province;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(district))
{
    fullAddress = address + ", " + city + ", " + district;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(province))
{
    fullAddress = address + ", " + city + ", " + province;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(district) && !string.IsNullOrEmpty(province))
{
    fullAddress = address + ", " + district + ", " + province;
}
else if (!string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(district) && !string.IsNullOrEmpty(province))
{
    fullAddress = city + ", " + district + ", " + province;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(city))
{
    fullAddress = address + ", " + city;
}
else if (!string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(province))
{
    fullAddress = address + ", " + province;
}
else if (!string.IsNullOrEmpty(address))
{
    fullAddress = address;
}
else if (!string.IsNullOrEmpty(city))
{
    fullAddress = city;
}


texts: Removing everything after a certain character

texts:
I was just writing code, and wanted to make a piece that removes everything after the character ? if it's found within the URL.

if (strstr($url, "?")) {
    $url = strstr($url, "?", true);
}

Can I make this any shorter? It doesn't feel right to type the "same thing" twice with strstr.


texts:
I have got the following C code and I feel it is crazy stupid and there must be a better way to do this, but just can't think of one and have yet to learn algorithms.

/*generates 1000 random numbers, lists frequency*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int count, generated_num ;
    char nums[10] = {0};
    srand(time(NULL));
    for (count = 0; count < 1000; count++) {
        generated_num = rand() % 10 + 1;
        nums[generated_num-1] += 1;
    }

    for (count = 0; count < 10; count++) {
        printf("%d occured %d times\n", count+1, nums[count]);
    }

    return 0;
}

How do I learn to write code that is both efficient in speed but also efficient in the sense it is readable/modifiable/not-a-mess?


texts:
Here I'm posting my code for the Reorganize String problem on LeetCode. If you have time and would like to review, please do so, I'd appreciate that.
On LeetCode, we are only allowed to change the argument names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).
Problem

Given a string S, check if the letters can be rearranged so that two
characters that are adjacent to each other are not the same.
If possible, output any possible result.  If not possible, return the
empty string.
Example 1:
Input: S = "aab" Output: "aba" Example 2:
Input: S = "aaab" Output: "" Note:
S will consist of lowercase letters and have length in range [1, 500].

Java
class Solution {
    public String reorganizeString(String baseString) {
        int[] charMap = initializeCharMap26(baseString);
        int max = 0;
        int letter = 0;

        for (int iter = 0; iter < charMap.length; iter++)
            if (charMap[iter] > max) {
                max = charMap[iter];
                letter = iter;
            }

        if (max > ((-~baseString.length()) >> 1))
            return "";

        char[] reorganized = new char[baseString.length()];
        int index = 0;

        while (charMap[letter] > 0) {
            reorganized[index] = (char) (letter + 97);
            index += 2;
            charMap[letter]--;
        }

        for (int iter = 0; iter < charMap.length; iter++) {
            while (charMap[iter] > 0) {
                if (index >= reorganized.length)
                    index = 1;

                reorganized[index] = (char) (iter + 97);
                index += 2;
                charMap[iter]--;
            }
        }

        return String.valueOf(reorganized);
    }

    private int[] initializeCharMap26(String baseString) {
        int[] charMap = new int[26];

        for (int i = 0; i < baseString.length(); i++)
            charMap[baseString.charAt(i) - 97]++;

        return charMap;
    }
}

Reference
767. Reorganize String (Problem)
767. Reorganize String (Solution)


texts:
I have implemented a class which implements a list of my custom DateObj. I have sorted the list in a peculiar manner based on the current month. I achieved my desired results, but I'm required to call Collections.sort() four times to achieve it. I feel this could be improved. Any thoughts?

//Custom Date Object
public class DateObj {

private int year;
private int month;
private int date;

DateObj(int year, int month ,int date){
    this.year = year;
    this.month = month;
    this.date = date;
}

public Integer getYear() {return year;}
public Integer getMonth() {return month;}
public Integer getDate() {return date;}
}

The custom sort class:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CustomListSort {
 static List<DateObj> list = new ArrayList<>();

public static void main(String a[]){

createRandomDateObjs();

Integer CURRENTMONTH = 6;

//Sort Months Descending
Collections.sort(list,(arg0,arg1)-> arg1.getMonth().compareTo(arg0.getMonth()));

//Sort by keeping the object with nearest largest next month first
Collections.sort(list,(arg0,arg1)->CURRENTMONTH.compareTo(arg0.getMonth()));

//Sort the months which were pushed back in an ascending order.
Collections.sort(list,(arg0,arg1)->(arg0.getMonth()<=CURRENTMONTH && arg1.getMonth()<=CURRENTMONTH)? arg0.getMonth().compareTo(arg1.getMonth()):0);

//If months same sort them in ascending manner based on their dates
Collections.sort(list, (arg0,arg1)->(arg0.getMonth() == arg1.getMonth())  ? arg0.getDate().compareTo(arg1.getDate()) : 0);

System.out.println("\nDESIRED OUTPUT");
System.out.println("\nMM - DD - YYYY \n");

for(int i = 0 ; i<list.size();i++)
    System.out.println(list.get(i).getMonth() +" - "+list.get(i).getDate()+" - "+list.get(i).getYear());
}

static void createRandomDateObjs(){
    for(int i = 0 ; i<20 ; i++){
        int y = 1980;
            y+=(int)(Math.random()*55);
        int m = (int) (Math.random()*11);
        int d = (int) (Math.random()*30);
        list.add(new DateObj(++y,++m,++d)); //Pre-increment to change 0's to 1's
}
}

Initially I had implemented it using Comparators but the Lambda made the code much cleaner.

Desired output:

MM - DD - YYYY

7 - 20 - 2023
7 - 18 - 2027
8 - 30 - 2010
8 - 12 - 2020
9 - 21 - 2006
10 - 23 - 2008
11 - 19 - 2000
11 - 16 - 2033
11 - 13 - 1989
12 - 13 - 2019
1 - 10 - 1985
1 - 15 - 2016
4 - 10 - 2021
4 - 13 - 2022
4 - 14 - 2004
5 - 1 - 2025
5 - 4 - 2014
5 - 20 - 2023
5 - 21 - 2022
6 - 29 - 1990


texts: Angular UI Datepicker Popup with Default Time

texts:
I need to set date and time (12 hours 0 minutes) via Angular UI DatePicker Popup.

plunker

I had two issues:

1. When page was loaded:

Input had value 17-March-2017 12:00:00.000. It's right.
But Selected date was: "2017-03-17T14:57:51.080Z". It's not true, not 12:00.

 2. When I changed date via button:

Input view was 24-March-2017 12:00:00.000
Selected date was: "2017-03-24T09:00:00.000Z"

I solved both issues this way:

I added defTime directive with formatters and parsers for input element;
I added time service to set 12 hours.
If I use ng-model-options="{timezone: 'utc'}" attribute in input, I don't need to subtract TimezoneOffset from Date differently for view (formatter) and model (parser) (Compare plunker ver.1 and ver.2).

In ver.1 (without ng-model-options attribute):

subtracting TimezoneOffset hours for $parsers;
subtracting 0 hours for $formatters.

Could you offer a better solution?

Thanks.

var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap']);

app.controller('DatepickerPopupDemoCtrl', function ($scope, time) {
  $scope.dt = time.getDefault(new Date());
});

app.directive('defTime', function (time) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ngModel) {
      ngModel.$parsers.push(time.getDefault);
      ngModel.$formatters.push(time.getDefault);
    }
  }
});

app.service('time', function () {
  return {
    getDefault: getDefault
  }

function getDefault(dateObj){
  var tzOffset = new Date().getTimezoneOffset() / 60;
  var hoursTZ = 12 - tzOffset;

  return new Date(new Date(dateObj).setHours(hoursTZ, 0, 0, 0));
}
});
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Selected date is: {{dt}}

Popup

          <input def-time
                type="text"
                class="form-control"
                uib-datepicker-popup="dd-MMMM-yyyy HH:mm:ss.sss"
                ng-model-options="{timezone: 'utc'}"
                ng-model="dt"
                is-open="opened"/>

            <button type="button" class="btn btn-default" ng-click="opened = !opened">

            </button>


texts:
This is a simple and short "Pretty Bytes" javascript function using the SI Decimal System for quantifying bytes.
The code does not use complex maths such as Math.pow() or Math.log() and mainly uses strings with an array.
The function uses the SI system of decimals as shown below (1 kilo = 1,000, 1 M = 1,000,000, etc.).

The number of decimal places is defaulted to 2 (no rounding is necessary) but can be modified on calling the function to other values. The common most used display is the default 2 decimal place.
The code is short and uses the method of Number String Triplets to first convert the input number (the integer) into a Number String Triplet, then into an array of triplets.
The following one-line code is used for converting an integer into a Number String Triplet so that the resulting string will always be made of multiple of 3's by padding zero(s) to the left. It is the same concept used under this code review article: Simple Number to Words using a Single Loop String Triplets
Num = "0".repeat((Num += "").length * 2 % 3) + Num;        // Make a Number String Triplet

The output is then made up of concatenating the first element of the array being the whole number and the 2nd element being the fraction (after chopping off for decimals) and adding the suffix letter.
Numbers below 1000 do not require the functional code and are cleared out first.
If there is a possibility that the input number may be a float, it should be converted to an integer first Num = Math.floor(Num); before passing it to the function.
As the code is mainly for displaying size, no code is added for handling negative numbers or floats (not sure if one would give a size as '3 and a half byte').
I welcome your code review.
Thanks
Mohsen Alyafei

/*********************************************************************
* @function    : numberPrettyBytesSI()
* @purpose     : Convert number bytes size to human readable format
*                using the SI Decimal System.
* @version     : 1.00
* @author      : Mohsen Alyafei
* @date        : 01 July 2020
* @param       : {num}      [integer] Number to be converted
* @param       : {decimals} [integer] Deciaml places (defaul 2)
* @returns     : {String}   Pretty Number
**********************************************************************/

function numberPrettyBytesSI(Num=0, decimals=2){
if (Num < 1000) return Num + " Bytes";
Num = "0".repeat((Num += "").length * 2 % 3) + Num; // Make a Number String Triplet
Num = Num.match(/.{3}/g);                           // Make an Array of Triplets

return Number(Num[0]) +                             // Whole Number withou leading zeros
       "." +                                        // dot
       Num[1].substring(0, decimals) + " " +        // Fractional part
       "  kMGTPEZY"[Num.length] + "B";              // The SI suffix
}

//*********** tests ***********************
console.log(numberPrettyBytesSI(0));            // 0 Bytes
console.log(numberPrettyBytesSI(500));          // 500 Bytes
console.log(numberPrettyBytesSI(1000));         // 1.00 kB
console.log(numberPrettyBytesSI(15000));        // 15.00 kB
console.log(numberPrettyBytesSI(12345));        // 12.34 Kb
console.log(numberPrettyBytesSI(123456));       // 123.45 kb
console.log(numberPrettyBytesSI(1234567));      // 1.23 MB
console.log(numberPrettyBytesSI(12345678));     // 12.34 MB
console.log(numberPrettyBytesSI(123456789));    // 123.45 MB
console.log(numberPrettyBytesSI(1234567890));   // 1.23 GB
console.log(numberPrettyBytesSI(1234567890,1)); // 1.2 GB
console.log(numberPrettyBytesSI(1234567890,3)); // 1.234 GB


texts:
Is there a way to reduce this lengthy if condition:

if(
    statusCode.equals( NO_ERRORS_NO_WARNINGS ) ||
    statusCode.equals( HAS_ERRORS_NO_WARNINGS )  ||
    statusCode.equals( HAS_ERRORS_HAS_WARNINGS ) ||
    statusCode.equals( NO_ERRORS_HAS_WARNINGS )
){
    //do something
}

The purpose of it is to see if there is a status code set within a log file. So the String statusCode could be a null value, one of the 4 status codes above or an unpredicatable String.


texts: Run Length Encoding (RLE) and Move To Front (MTF) in C++

texts:
I have made two quite basic algorithms used for lossless data compression.

This is my RLE:

#include <string>

std::string rle(const std::string& input) // encode (aaaaeecd -> 4a2e1c1d)
{
    std::string output;

    int n = input.size();
    int i = 0;
    while(i < n)
    {
        int run_count = 1;
        int max_run_count = std::min(255, n - i); // condition: i + run_count < n, runcount <= 255
        while(run_count < max_run_count && input[i + run_count] == input[i])
            run_count++;
        output += run_count; // run_count is between 0 and 255 (unsigned char)
        output += input[i];
        i += run_count;
    }

    return output;
}

std::string irle(const std::string& input) // decode (4a2e1c1d -> aaaaeecd)
{
    std::string output;

    for(int i = 0; i < input.size(); i += 2)
    {
        int nb = (int)(unsigned char)input[i]; // range between 0 and 255
        for(int k = 0; k < nb; k++)
            output += input[i+1];
    }

    return output;
}

and here goes my MTF:

#include <string>
#include <deque>
#include <list>
#include <algorithm>

/*
if alphabet A = {'a', 'b', 'c'}
    then string "accbc" is encoded 02021
    (a is at index 0, alphabet remains {'a', 'b', 'c'}, outputs 0 ;
     c is at index 2, alphabet becomes {'c', 'a', 'b'}, outputs 2 ;
     c is at index 0, alphabet remains {'c', 'a', 'b'}, outputs 0 ;
     b is at index 2, alphabet becomes {'b', 'c', 'a'}, outputs 2 ;
     a is at index 1, alphabet becomes {'a', 'b', 'c'}, outputs 1)
*/
std::string mtf(const std::string& input)
{
    std::string output;

    std::list<char> alphabet; // constant erase/insert
    for(int i = 0; i <= 255; i++)
        alphabet.push_back((char)i);

    for(char c: input)
    {
        auto c_it = find(alphabet.begin(), alphabet.end(), c); // find char c in the alphabet
        output += distance(alphabet.begin(), c_it); // output index of char c in the alphabet
        // move character to the front of the alphabet
        alphabet.erase(c_it);
        alphabet.insert(alphabet.begin(), c);
    }

    return output;
}

/*
reverse operation:
    for each number, outputs the character at the corresponding index in the alphabet
        then move this character to the front of the alphabet
        and keep going
*/
std::string imtf(const std::string& input)
{
    std::string output;

    std::deque<char> alphabet; // constant erase (begin) & operator[] ; insert (middle) is O(n)
    for(int i = 0; i <= 255; i++)
        alphabet.push_back((char)i);

    for(unsigned char n: input)
    {
        char temp_c = alphabet[n];
        output += temp_c;
        alphabet.erase(alphabet.begin() + n);
        alphabet.insert(alphabet.begin(), temp_c);
    }

    return output;
}

I know there are many possible improvments possible, especially for the RLE algorithm. I would just like a review on the C++ syntax I've used, especially on the structures I have chosen.


texts: Prim's algorithm via Priority Queues to print the minimum spanning tree of an adjacency matrix undirected graph

texts:
My adjacency matrix looks like this, where non-zero weights denote edges.
[0, 2, 0, 0, 3]
[2, 0, 2, 4, 0]
[0, 2, 0, 3, 0]
[0, 4, 3, 0, 1]
[3, 0, 0, 1, 0]
Here's my attempt:
//nested class, only showing the relevant parts of code
class Edge implements Comparable<Edge> {
    int source;
    int destination;
    int weight;

    public Edge(int source, int destination, int weight) {
        this.source = source;
        this.destination = destination;
        this.weight = weight;
    }

    public String toString() {
        return source + "---" + weight + "---" + destination;
    }

    @Override
    public int compareTo(Edge other) {
        return Integer.compare(this.weight, other.weight);
    }
}

public void printPrimsMST(int[][] matrix) {
    // Start with any vertex.
    Set<Integer> visited = new HashSet<>();
    Queue<Edge> edgeQueue = new PriorityQueue<>();

    int currentNode = 0;
    visited.add(0);
    while (visited.size() < matrix.length) {

        for (int col = 0; col<matrix[currentNode].length; col++) {
            // Take all edges from this node.
            if (col == currentNode || matrix[currentNode][col] == 0) {
                //skip self as well as 0-weight edges.
                continue;
            }
            edgeQueue.add(new Edge(currentNode, col, matrix[currentNode][col]));
        }

        if (edgeQueue.isEmpty())
            return;

        //find cheapest edge to a not already visited destination.
        Edge edge = edgeQueue.remove();
        while (visited.contains(edge.destination)) {
            if (edgeQueue.isEmpty())
                return;
            edge = edgeQueue.remove();
        }

        System.out.println(edge.source + "--" + edge.weight + "--" + edge.destination);
        // Now that you've reached this edge as a destination, record it.
        currentNode = edge.destination;
        visited.add(edge.destination);
    }
}


texts:
I had a phone interview and we shared a screen to do a simple challenge. Instructions were ambiguous but I basically had to implement how an air conditioner would work in general. I wrote the following as I talked it out with the interviewer.

So I made a class with a parameter that would be a room temp and then added two properties, heatingSystem and coolingSystem and set them as booleans. Then wrote a function called setTemperature that should’ve been a while loop that changes the temperature and setting of the A/C until it reaches the set temperature.

class AirConditioner {
   constructor(temperature) {
       this.temperature = temperature;
       this.coolingSystem = false;
       this.heatingSystem = false;
   }

  temperatureSet(temperature) {
    while (this.temperature != temperature) {
       if (this.temperature < temperature) {
           // turn on the cooling system and turn off heating system
           if (this.coolingSystem) {
               this.coolingSystem = false;
               this.heatingSystem = true;
               this.temperature++;
           } else {
             this.heatingSystem = true;
             console.log('Temperature has been lowered to ' + this.temperature);
             this.temperature++;
           }
       } else if (this.temperature > temperature) {
           // turn off the cooling system and turning the heating
           if (this.heatingSystem) {
               this.coolingSystem = true;
               this.heatingSystem = false;
               console.log('Temperature has been increased to ' + this.temperature);
               this.temperature--;
           } else {
             this.coolSystem = true;
             console.log('Temperature has been lowered to ' + this.temperature);
             this.temperature--;
           }
       } else {
           // turn off cooling/heating system but keep the fan un
           console.log('temp is the same')
       }
    }
      console.log(`this.temperature: ${this.temperature} temperature: ${temperature}`)
  }
}

const AC = new AirConditioner(78);
console.log(AC);
AC.temperatureSet(63);
console.log(AC);

I honestly don't like the code and can already see a lot of possibilities on how to refactor or add other functions for re-usability. I was wondering what your suggestions are.


texts: Scheme, first timer first program, simple list removal technique

texts:
I have started my hand at writing some scheme code. I am trying to get the first n primes. I plan to do so but first getting a list from 2 to m, and doing the following algorithm. Remove the first number and place in the primes list, remove all #'s from the initial list that are multiples of the number just pulled off, repeat until the size of the primes list equals n.

There are no loops in scheme so I have to use recursion and also modulo will probably help me, how might I go about writing the method "listminusnonprimes"? Also does my code so far look good?

Code:

;Builds a list from [arg] to 2
(define buildlist
  (lambda (m)
    (if (<= m 2)
      '(2)
        (cons m (buildlist(- m 1))))))
;Returns a list from 2 to [arg]
(define listupto
  (lambda (m)
    (reverse (buildlist m))))
;Returns a list with nonprimes based off num removed
(define listminusnonprimes
 (lambda (num list)
   (
;Returns the first n primes
(define firstnprimes
  (lambda (n nlist slist)
    (append (car nlist) slist)
    (if (= n (length slist))
        slist
        (firstnprimes (- n 1) (listMinusNonprimes (car nList) nlist) slit))))


texts: Simple game to learn common port numbers for Sec+ exam

texts:
This is a basic game asking for the common port number for a protocol used. I designed it with the intent on helping myself and others who are going after their Sec+ exam to memorize the ports needed. Any in cleaning up the code or better ways to process the lists would be most appreciated.

import random
import sys
from os import system

#List of lists of ports and protocols for SEC+ exam
numbers= {'TCP 22':('ssh','scp','sftp'),'TCP AND UDP 53':('DNS'),
'TCP 20 and 21':('FTP'),'UDP 69':('TFTP'),'443':('FTPS,HTTPS,SSL VPN443'),'TCP 25':('SMTP'),
'TCP 110':('POP3'), 'TCP 143':('Imap'),'TCP 23':('TelNet'),'TCP 49':('TACACS+'),'UDP 49':('TACACS'),
'UDP 1701':('L2TP'),'TCP and UDP 1723':('PPTP'),'TCP and UDP 3389':('RDP'),
'UDP 67,68':('DHCP'),'TCP 80':('HTTP'),'TCP AND UDP 88':('Kerberos'), 'TCP 119':('NNTP'),'UDP 161':('SNMP'),
'UDP 514':('Syslog'),'TCP 443':('HTTPS/SSL VPN/FTPS'),'UDP 67 and 68':('DHCP'),'UDP 500':('ISAKMP VPN'),'TCP AND UDP 162':('SNMP Trap')
        }

#List of ports for random choice
random_gen= ('TCP 20 and 21','TCP 22','UDP 69','TCP 443','TCP 25','TCP 110','TCP 143','TCP 23','TCP 49','UDP 49','UDP 500'
,'UDP 1701','TCP and UDP 1723','TCP and UDP 3389','TCP AND UDP 53','UDP 67 and 68','TCP 80','TCP AND UDP 88','TCP 119','UDP 161',
'TCP AND UDP 162','UDP 514'
            )

def Sec_port_game():
    correct = 0
    incorrect = 0
    system('cls')
    print("""This will ask you for port number and weather or not is uses TCP or UDP for communication. Answer must be formatted like 'TCP 443'
if the uses both the answer must be formatted 'TCP and UDP' followed by the port number. If it uses more than one port it must be formatted like
67 and 68. The lowest number will always come first.""")

    while (1==1):
        #Keeps track of total answred
        total = incorrect + correct
        #prints the amount of answers that you have correct, incorrect and total
        print(f"correct {correct} incorrect {incorrect}: {total} total answered out of 20 questions.")
        #creates the random port for question
        rand_choice= random.choice(random_gen)
        #Total of 20 random ports will ne assesed. Gives the total correct, incorrect and % coorect.
        if(total == 20):
            print(f"Total correct is {correct} total incorrectis {incorrect}")
            print("Precent correct is")
            print(correct/20 * 100)
            #Asks the player if they would like to play again
            play_again=input('''Would you like to play again? "yes" or "no" any other response to exit the program
:''')
            #if player wants to play agin sets the correct and incorrect to 0 to start exit if and start over.
            if(play_again.upper() == 'YES') or (play_again.upper() == 'Y'):
                correct =0
                incorrect = 0
            #If the player does not wish to play again thanks them for playing and break out of the while loop wo exit the game.
            else:
                print("Thank you for playing")
                break
        #Takes the answer for the random port
        answer = input(f"""Port number for {numbers[rand_choice]}?
:""")

        #Checks the answer to see if it's correct
        if (answer.upper() == rand_choice.upper()):
            print('CORRECT!')
            correct += 1

        else:
            print(f"""Nice try but the correct port is {rand_choice}""")
            incorrect += 1

#starts the game
Sec_port_game()


texts: Fastest way to clamp an integer to the range 0-255

texts:
I'm working on some image processing code that can generate pixel values outside of the normal range of 0 to 255, and I'd like to clamp them back into the valid range. I know that there are saturating SIMD instructions that make this a moot point, but I'm trying to stay within standard C++ code for the moment.

The fastest I've been able to do on my Athlon II is the following:

inline
BYTE Clamp(int n)
{
    n &= -(n >= 0);
    return n | ((255 - n) >> 31);
}

This compiles down into the following assembly with MSVC 6.0:

setns dl
neg   edx
and   eax, edx
mov   edx, 255
sub   edx, eax
sar   edx, 31
or    dl, al

Is there any improvement possible?


texts: Gradient function that returns a list of all colors in order

texts:
I've made this Function gradient() that returns a list of rbg of all the colors in an order.
Issues:-

What should be the condition for while loop to stop the loop. Though b == 0 in the last elif block works fine.

How can I reduce the code of the function keeping the functionality the same. Like if there is any better approach to doing this.

Also, How can I calculate the length of the rbg_list just with the value of gap parameter without running the function. Let's say the length of the rbg_list will be 1529 if gap=1 so I can iterate it with range(1529).

gradient() function:-
def gradient(gap=1):
    r, g, b = 255, 0, 0

    if gap<=0:
        return (r, g, b)

    rbg_list = []
    while True:
        if  r == 255 and g >= 0 and g < 255 and b == 0:           # 1
            g += gap
            if g > 255:
                g = 255

        elif r <= 255 and g == 255 and r > 0 and b == 0:          # 2
            r -= gap
            if r < 0:
                r = 0

        elif r == 0 and g == 255 and b < 255 and b >= 0:          # 3
            b += gap
            if b > 255:
                b = 255

        elif r == 0 and g <= 255 and g > 0 and b == 255:          # 4
            g -= gap
            if g < 0:
                g = 0

        elif r >= 0 and g == 0 and r < 255 and b == 255:          # 5
            r += gap
            if r > 255:
                r = 255

        elif r == 255 and g == 0 and b > 0 and b <= 255:          # 6
            b -= gap
            if b < 0:
                b = 0

            if b == 0: break

        # print(r, g, b)
        rbg_list.append((r, g, b))
    return rbg_list

print(gradient(5))

Note:- I want the function to be compatible with both Python 2 and Python 3


texts: An ASCII histogram of a die rolled n times

texts:
A die is rolled n times. Each time, a random value has been inserted into a vector. This vector then is used to generate a sorted map (wrongly called hashmap in the code) that is later used to create an ASCII histogram.

The histogram, for example, looks like this:

    10
    #
    #
7   #
#   #
#   #     5
#   #     #
# 3 #     #
# # #     #
# # # 1   #
# # # #   #
-----------
1 2 3 4 5 6

And here's the code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <random>
#include <map>

std::vector<int> roll(int times)
{
    std::vector<int> rand;

    while (times > 0)
    {
        std::random_device seeder;
        std::mt19937 engine(seeder());
        std::uniform_int_distribution<int> dist(1, 6);
        rand.push_back(dist(engine));

        --times;
    }

    return rand;

}

std::map<int, int> histogram_calculate(int times)
{
    std::vector<int> random_numbers = roll(times);

    std::map<int, int> cnt_hashmap;
    auto max_element = 6;

    for (int i = 1; i <= max_element; ++i)
    {
        cnt_hashmap[i] = 0;
    }

    for (auto iter = random_numbers.begin(); iter != random_numbers.end(); ++iter)
    {
        cnt_hashmap[*iter] += 1;
    }

    return cnt_hashmap;
}

std::string histogram_draw(int times)
{
    std::vector<std::string> ret_vec;
    std::map<int, int> histogram = histogram_calculate(times);

    for (int i = 1; i <= histogram.size(); ++i)
    {
        std::string to_add = "";

        if (histogram[i] > 0)
        {
            to_add = std::to_string(histogram[i]);
            std::string column = "\n";
            int j = 0;

            while (j <= histogram[i])
            {
                column += "#";
                column += "\n";

                ++j;
            }

            to_add += column;
        }

        to_add += "--";
        to_add += std::to_string(i);

        ret_vec.push_back(to_add);

    }

    std::string finalize = "";

    for (auto &str : ret_vec)
    {
        finalize += str;
    }

    return finalize;

}

int main() {

    std::cout << histogram_draw(10) << std::endl;
    return 0;
}

There's three functions:

One to fill the random value vector
One to sort out the histogram.
One to display the histogram.

That's about it.


texts: Holding a reference of the active Android Activity

texts:
I recently had to work in a tricky piece of work for a project I am working on. You can find its code on GitHub and I'd like to have a feedback about some specific parts of it.

The project is a library and if you look at the README you will see how it needs to be integrated with an android application. I report it here:

public class YOUR_APP_NAMEApplication extends Application{
    private RateMyApp rateMyApp;
    @Override
    public void onCreate(){
        RateMyAppBuilder builder = new RateMyAppBuilder();
        builder.setLaunchesBeforeAlert(3);
        builder.setDaysBeforeAlert(7);
        builder.setEmailAddress("mariosangiorgio@gmail.com");
        PreferencesManager preferencesManager = SharedPreferencesManager.buildFromContext(this);
        rateMyApp = builder.build(preferencesManager);
    }

    public void activityCreated(Activity activity){
        if(rateMyApp != null)
            rateMyApp.appLaunched(activity);
    }

    public void activityDestroyed(){
        if(rateMyApp != null)
            rateMyApp.activityDestroyed();
    }
}

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);

        FutsalCoachApplication application = (FutsalCoachApplication)     getApplicationContext();
        application.activityCreated(this);
    }

    @Override
    public void onDestroy(){
        FutsalCoachApplication application = (FutsalCoachApplication) getApplicationContext();
        application.activityDestroyed();
        super.onDestroy();
    }
}

The first thing I'd like to ask is if it acceptable to require the creation of a new class extending Application just to hold the main component of my library.

I'd also like to get a feedback about the fact that my library needs to create instances of DialogFragment and to start new activities. Both these tasks require an active Activity and this is a source of a bit of trickery.

I like the fact that RateMyApp class has the dependency on the Activity instance isolated in the RateMyApp.appLaunched(Activity) method.

I don't really like how I get the class extending Application to get a reference of the current Activity. Needing to override Activity.onCreate(Bundle) and Activity.onDestroy() feels a bit dirty.

What do you think about this approach? Would you do it in an alternative (and possible cleaner) way?


texts: A better way of always dumping Gedit out of Terminal?

texts:
I use terminal alot, so it was frustrating to me to deal with gedit's inconsistent behavior between having a window open and when one was not. I ended up searching around, and finding a way of getting around this. I've created this bash script, and aliased it to gedit, and I've slowly been expanding it.

Basically the script does these things:

Checks to see if arguments exist, if not, it opens gedit with no document
If arguments do exist, it iterates over each and opens them all.

This creates consistent behavior where gedit won't stick in terminal dumping log data.

#!/bin/bash

if [[ -z $1 ]]; then
    /usr/bin/gedit &
else
    for var in "$@"
    do
        /usr/bin/gedit "$var" &
    done
fi

My question is if there are any glaring errors here, or if there is a cleaner, faster way of doing this? I'm specifically interested in the loop, as I feel there should be an easier way of passing list data as a single string. The reason I didn't just use $* for that, is when I tried the fact that it's wrapped in quotes caused it to open a single document with all parameters listed as the file name.

I added the quotes for a reason that I should have documented, but I currently do not remember.


texts: Is 'try / finally' the best way for me to handle (and close) this long-running IMAP4 connection?

texts:
I'm writing a script to archive email messages from one IMAP folder to another. It looks, more or less, like the following. I've obfuscated about 30 lines unrelated to this question:

import imaplib
import getpass

def main():
    user = getpass.getuser() + '@mymailbox.com'
    mailbox = imaplib.IMAP4_SSL('mymailbox.com', 993)
    try:
        mailbox.login(user, getpass.getpass())
    except imaplib.IMAP4.error:
        raise RuntimeError('Credential error.')
    mailbox.select('my_mailbox')

    # Here lies some 30 lines not relevant to the question, but which
    # find mailbox messages, copies them to another folder, and
    # sets the delete flag in 'my_mailbox'.

    try:
        mailbox.close()    # which also expunges the mailbox
    except:
        pass
    mailbox.logout()

After working with my IMAP server for a while, I've discovered a fair amount of unexpected error conditions arising from its implementation of RFC 3501. No matter what, however, I always want to attempt mailbox.close() and mailbox.logout().

It sounds like a good occasion for a try / finally block, and that usage is supported by other examples. All the same, it feels unnatural to wrap some 40 lines of main() execution in a try-block:

def main():
    user = getpass.getuser() + '@mymailbox.com'
    mailbox = imaplib.IMAP4_SSL('mymailbox.com', 993)
    try:
        try:
            mailbox.login(user, getpass.getpass())
        except imaplib.IMAP4.error:
            raise RuntimeError('Credential error.')
        mailbox.select('my_mailbox')

        # Here lies some 30 lines not relevant to the question, but which
        # find mailbox messages, copy them to another folder, and
        # set delete flags in 'my_mailbox'.
    finally:
        try:
            mailbox.close()    # which also expunges the mailbox
        except:
            pass
        mailbox.logout()

Is that a common pattern? I could also write my own context manager; perhaps that's the better way to go. What's the best practice for long-running connections like this?


texts: Remove duplicates from unsorted linked list

texts:
Remove duplicate elements from linked list.

#include<iostream>
using namespace std;

class LinkedList{
private:
    int data;
    LinkedList *next;
public:
    void insert(LinkedList **start, int data){
        LinkedList *p = new LinkedList;
        if (*start == NULL){
            p->data = data;
            p->next = NULL;
            *start = p;
        }
        else{
            LinkedList *temp = *start;
            while (temp->next != NULL){
                temp = temp->next;
            }
            temp->next = p;
            p->data = data;
            p->next = NULL;
        }
    }
    void removeDuplicates(LinkedList **start){//This function removes the duplicates using the standard runner method taking 2 pointers
        LinkedList *temp = *start;
        LinkedList *temp1 = (*start);
        while (temp != NULL){
                while (temp1->next!=NULL){
                    if (temp->data == temp1->next->data){
                        LinkedList *p;
                        p = temp1->next;
                        temp1->next = temp1->next->next;
                        delete(p);
                    }
                    else{
                        temp1 = temp1->next;
                    }

                }

            temp = temp->next;
            temp1 = temp;
        }
    }

    void traverse(LinkedList **start){
        LinkedList *temp = *start;
        while (temp != NULL){
            cout << temp->data;
            temp = temp->next;
        }
    }
};

int main(){
    LinkedList *start = NULL;
    LinkedList p1;
    p1.insert(&start, 9);
    p1.insert(&start, 8);
    p1.insert(&start, 7);
    p1.insert(&start, 9);
    p1.insert(&start, 8);
    p1.traverse(&start);
    p1.removeDuplicates(&start);
    cout << "\n";
    p1.traverse(&start);
    getchar();
    return 0;
}

This takes \$O(N^2)\$ time. Can we do the same in \$O(N)\$ without the use of hash table? Or if mandatory how can we implement it in C++?

How is the overall code quality of the above code? Is there any scope of improvement?


texts: Multiple input checks, repeat if conditions are not met

texts:
I've used this code to make some inputs checks. On any failed check, I need to ask again for proper input. I used labels and goto to achieve this, which they seem to be disliked by programmers as a concept.
How could I achieve the same effect without labels/goto? I considered putting all this code in a function and calling itself from inside, but it repeated only once for some reason - didn't keep asking if kept getting wrong answers.
// 0 exits
var f float64
var n int
startGame := func() {
reception:
    fmt.Println()
    fmt.Print(`Give number (1-9): `)
    _, err := fmt.Scan(&f)

    // check letters or symbols
    if err != nil {
        fmt.Println("Letters or symbols not accepted")
        goto reception
    }

    // exit
    if f == 0 {
        os.Exit(0)
    }

    // check for integers only
    if f < 1 || f > 9 || f-math.Ceil(f) != 0 {
        fmt.Println("Only integer numbers between 1-9 are accepted")
        goto reception
    }

    n = int(f)
    // check for empty cells
    if myArray[n-1] == false {
        fmt.Println("Empty cell", n)
        goto reception
    }
}


texts: Rounding and formatting hours, minutes, seconds as HH:MM AM/PM

texts:
I have a program which is supposed to convert standard time to traditional time. (e.g: 15:24:31 = 3:25PM [rounded seconds])

I would like for someone to error check my code for me as well as give me ideas on how to condense it.

I'm not sure if I'm allowed to post a program here because of safety issues but here is the exe.

Here is the program. Excuse the spelling mistakes regarding "Standared".

  private void button1_Click(object sender, EventArgs e)
{
    double Hours = double.Parse(textBox1.Text);
    double Minutes = double.Parse(textBox2.Text);
    double Seconds = double.Parse(textBox3.Text);

    if (Hours > 24 || Minutes >= 60 || Seconds >= 60)
    {
        label1.Text = "Please type in proper values.";
    }
    else if (Hours == 0 && Minutes == 0 && Seconds == 0)
    {
        label1.Text = "The traditional time is 12:00 AM";
    }
    else if (Hours == 0 && Minutes < 10)
    {
        label1.Text = "The traditional time is 12:0" + Minutes + " AM";
    }
    else if (Hours == 23 && Minutes == 59 && Seconds >= 30)
    {
        label1.Text = "The traditional time is 12:00 AM";
    }
    else if (Hours == 12 && Minutes == 59 && Seconds >= 30)
    {
        label1.Text = "The traditional time is 1:00 PM";
    }
    else
    {
        label1.Text = "The traditional time is " + Converter(Hours);
    }
}
public string Converter(double Input)
{
    String Final;
    double H = double.Parse(textBox1.Text);
    double M = double.Parse(textBox2.Text);
    double S = double.Parse(textBox3.Text);
    string AMPM = "";
    if (M == 59 && S == 59)
    {
        H = H + 1;
        M = 0;
        S = 0;
    }
    if (H == 12)
    {
        AMPM = "PM";
    }
    else if (H == 24)
    {
        H = 12;
        AMPM = "AM";
    }
    else if (H > 12)
    {
        H = H - 12;
        AMPM = "PM";
    }
    else if (H < 12)
    {
        AMPM = "AM";
    }
    if (S >= 30)
    {
        S = 1;
        if (S==1)
        {
            M = S + M;
        }
    }
    else
    {
        S = 0;
    }

    if (M == 0)
    {
         Final = H.ToString() + ":" + M.ToString() + "0 " + AMPM;
    }
    else if (M == 1 || M == 2 || M == 3 || M == 4 || M == 5 || M == 6 || M == 7 || M == 8 || M == 9)
    {
        Final = H.ToString() + ":0" + M.ToString() + " " + AMPM;
    }
    else
    {
        Final = H.ToString() + ":" + M.ToString() + " " + AMPM;
    }

    return Final;
}
}
}


texts: Evaluate the best common type to fit both of types

texts:
Here is an algorithm to evaluate best matching System.Type for two types in hierarhy. This is one of answers for this StackOverflow question by Ken Kin:

  Evaluate the maximum possible type to fit both of types

Algorithm

Searching for common base class (either concrete or abstract)

FindBaseClassWith method

If there is no common base class, search for common implemented interface

It's possible for one class to implement multiple interfaces, in this case return first common based interface
FindInterfaceWith method

Questions

GetInterfaceHierarchy implementaion

I'm not sure that this is correct implementation in case of complex class hierarhy with many implemented interfaces
Now all tests are passing for selected collection from BCL and my own testing hierarhy

Are there any other flaws that I do not pay attention to?
I had wrote this sample in LinqPad, that's why all unittests are located at Main method. Nevertheless, any improvments to Test.Assert are ok!

Full source code with unittests is available here

// provide common base class or implemented interface
public static Type FindEqualTypeWith(this Type typeLeft, Type typeRight)
{
    if(typeLeft == null || typeRight == null) return null;

    var commonBaseClass = typeLeft.FindBaseClassWith(typeRight) ?? typeof(object);

    return commonBaseClass.Equals(typeof(object))
            ? typeLeft.FindInterfaceWith(typeRight)
            : commonBaseClass;
}

// searching for common base class (either concrete or abstract)
public static Type FindBaseClassWith(this Type typeLeft, Type typeRight)
{
    if(typeLeft == null || typeRight == null) return null;

    return typeLeft
            .GetClassHierarchy()
            .Intersect(typeRight.GetClassHierarchy())
            .FirstOrDefault(type => !type.IsInterface);
}

// searching for common implemented interface
// it's possible for one class to implement multiple interfaces,
// in this case return first common based interface
public static Type FindInterfaceWith(this Type typeLeft, Type typeRight)
{
    if(typeLeft == null || typeRight == null) return null;

    return typeLeft
            .GetInterfaceHierarchy()
            .Intersect(typeRight.GetInterfaceHierarchy())
            .FirstOrDefault();
}

// iterate on interface hierarhy
public static IEnumerable<Type> GetInterfaceHierarchy(this Type type)
{
    if(type.IsInterface) return new [] { type }.AsEnumerable();

    return type
            .GetInterfaces()
            .OrderByDescending(current => current.GetInterfaces().Count())
            .AsEnumerable();
}

// interate on class hierarhy
public static IEnumerable<Type> GetClassHierarchy(this Type type)
{
    if(type == null) yield break;

    Type typeInHierarchy = type;

    do
    {
        yield return typeInHierarchy;
        typeInHierarchy = typeInHierarchy.BaseType;
    }
    while(typeInHierarchy != null && !typeInHierarchy.IsInterface);
}


texts:
I was wondering if anyone would be so kind as to look at this code I've written for practice.  Tell me what am I doing wrong, where can I optimize, anything.

What this code does is (in terminal) draw a bunch of random 1's and 0's, but I added an effect kinda like a lattice.  The bulk of this I got help on here.

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>

int main (int argc, char *argv[]){      //check for whitch effect to print
    switch(*argv[1]){
        case '1': lattus();break;
        case '2': normal();break;
        default: printf("1 = lattus effect | 2 = static effect\n");break;
    }
}

char *randstring (char *buffer, int length){        //genertate a random number
    int i = length;
    while(--i >= 0) {
        buffer[i] = (rand() % 2) ? '1' : '0';
    }
    buffer[length] = 0;
    return buffer;
}

int normal(){           // normal drawing of 1's and 0's
    struct winsize w;
    ioctl(0, TIOCGWINSZ, &w);
    int width = w.ws_col;
    int height = w.ws_row;      //get terminal width and height
    char buffer[width*height + 1];  //create a buffer big enough to hold one draw to the screen
    int i = 25;
    while(i-- >= 0) {
        printf("%s\n", randstring(buffer, width*height));   //draw to screen
        usleep(90000);
    }
    system("clear");        //clear screen
}

int lattus (void){
    struct winsize w;
    ioctl(0, TIOCGWINSZ, &w);
    int width = w.ws_col;       //get the terminal width
    char buffer1[width + 1];    //create 3 buffers for each segment
    char buffer2[width + 1];    //each big enough to hold the width of the terminal
    char buffer3[width + 1];
    int first = 1;          //how many before the space
    int second = width - 8;     //how many in the middle of the space
    int third = 1;          //how many at the end of the space
    int i = 1000;           //draw 1000 lines
    int on = 0;         //switch for growing and shrinking
    while(i-- >= 0){
        usleep(9000);
        if(first == 1 && third == 1 && second == width - 8 | second == width - 9){  //is it at min?
            if(second % 2 == 0){        //is it an even number (had problems with buffer if it was odd)
                second = second - 2;
            }else{
                second = second - 3;
            }
            first ++;
            third ++;
            on = 0;     //keep growing
        }else if(first == (width - 8) / 2 && third == (width - 8) / 2 && second == 2){  //untill it gets to max
            if(second % 2 == 0){
                second = second + 2;
            }else{
                second = second + 1;
            }
            third --;
            first --;
            on = 1;     //start shrinking
        }else if(on == 0){  //else if suppost to grow, grow
            second = second - 2;
            third ++;
            first ++;
        }else if(on == 1){  //else if suppost to shrink shrink
            second = second + 2;
            third --;
            first --;
        }else{
            break;
        }
        printf("%s   %s   %s\n", randstring(buffer1, first), randstring(buffer2, second), randstring(buffer3, third));  //print it out
    }
    system("clear"); //clear screen
}


texts: Dijkstra's shortest path with max intermediate nodes limitation

texts:
Suppose want to calculate the shortest path from one node to all other nodes, with the restriction of intermediate nodes cannot be more than a given number.

My major idea is, following how Dijkstra's algorithm works, with only the exception that when updating shortest path, if I see shortest path intermediate nodes exceeds the given number, I will skip the update. More details, refer to this line and len(self.shortest_path[shortest_node_so_far]+[n[0]])-1 <= max_path_stop

Here is my implementation, any advice on performance improvements in terms of algorithm time complexity, code bugs or code style are appreciated.

Test case is from wikipedia diagram (https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)

Source code in Python 2.7,

from collections import defaultdict
class Graph:
    def __init__(self):
        self.connections = defaultdict(list)
        self.visited = set()
        self.shortest_path = defaultdict(list)
        self.shortest_path_distance = defaultdict(lambda : float('inf'))
    def add_edge(self, edge):
        self.connections[edge[0]].append((edge[1], edge[2]))
        self.connections[edge[1]].append((edge[0], edge[2]))
    def calculate_shortest_path(self, cur, max_path_stop):
        self.visited.add(cur)
        self.shortest_path[cur] = [cur]
        self.shortest_path_distance[cur] = 0
        for n,d in self.connections[cur]:
            self.shortest_path_distance[n] = d
            self.shortest_path[n].append(cur)
            self.shortest_path[n].append(n)
        while (len(self.visited) < len(self.connections.keys())):
            shortest_so_far = float('inf')
            shortest_node_so_far = None
            for n,d in self.shortest_path_distance.items():
                if n in self.visited:
                    continue
                if d <= shortest_so_far:
                    shortest_node_so_far = n
                    shortest_so_far = d
            self.visited.add(shortest_node_so_far)
            for n in self.connections[shortest_node_so_far]:
                if self.shortest_path_distance[shortest_node_so_far] + n[1] < self.shortest_path_distance[n[0]] \
                        and len(self.shortest_path[shortest_node_so_far]+[n[0]])-1 <= max_path_stop:
                    self.shortest_path_distance[n[0]]=self.shortest_path_distance[shortest_node_so_far] + n[1]
                    self.shortest_path[n[0]]=self.shortest_path[shortest_node_so_far]+[n[0]]
if __name__ == "__main__":
    g = Graph()
    edges = [(1,2,7),(1,3,9),(1,6,14),(2,3,10),(3,6,2),(5,6,9),(5,4,6),(3,4,11),(2,4,15)]
    for e in edges:
        g.add_edge(e)
    g.calculate_shortest_path(1,2)
    print g.shortest_path
    print g.shortest_path_distance


texts:
I wrote my first unit testing code on a service class using Mockito. The code looks like this:

// Test Class
public class TestVideoService {
    private VideoService videoService;
    @Mock private VideoRepository videoRepository;
    @Rule public MockitoRule mRule = MockitoJUnit.rule();

    @Before
    public void setUp(){
        this.videoService = new VideoService(videoRepository);
    }

    @Test
    public void testGetAllVideos() throws Exception{
        when(videoRepository.findAll()).thenReturn(new ArrayList<Video>());
        assertEquals(new ArrayList<Video>(), videoService.getAllVideos(), "tested");
    }

}

I also have several questions. I feel like I'm just comparing the same mock values (ArrayList of Video) – what's the point of doing this, or am I just doing it the wrong way?

Some other classes:

@Service
public class VideoService {
    @Autowired
    private VideoRepository videoRepository;

    public VideoService(VideoRepository videoRepository){
        this.videoRepository = videoRepository;
    }

    public List<Video> getAllVideos(){
        return videoRepository.findAll();
    }
}

@Repository
public interface VideoRepository extends JpaRepository<Video, Long> {
}


texts:
I made the following class to handle 2D animation through GIF images. This is made using JME 3.1, Java 8 and this GIF library. Is what I'm doing optimal? Are there already other available libraries or methods that do this?

public class Animation2D {

    private final GifDecoder decoder = new GifDecoder();
    private final AWTLoader loader = new AWTLoader();
    private final SimpleApplication app;
    private int frameIndex;
    private float frameDelay = decoder.getFrameCount() > 0 ? decoder.getDelay(frameIndex) : 0;

    public Animation2D(SimpleApplication app, String path) {
        this.app = app;

        TextureKey key = new TextureKey(path, false);
        AssetInfo info = app.getAssetManager().locateAsset(key);

        try (InputStream stream = info.openStream()) {
            decoder.read(stream);
        } catch (IOException err) {
            MyGame.LOGGER.log(Level.SEVERE, "Count not find texture file!", err);
        }
    }

    public void update(Picture pic, float tpf) {
        frameDelay -= tpf;

        if (frameDelay < 0) {
            frameDelay = decoder.getDelay(frameIndex) / 1000F;

            Texture2D tex = new Texture2D(loader.load(decoder.getFrame(frameIndex), true));
            pic.setTexture(app.getAssetManager(), tex, true);

            if (frameIndex < decoder.getFrameCount() - 1) {
                ++frameIndex;
            } else {
                frameIndex = 0;
            }
        }
    }
}


texts: Is this recursion a bad idea and does it make for clean code?

texts:
This is a program I made to bounce the letter a across the screen.  I made a few others, but this one I made with a recursive bounce() method.  I know main() is a bit empty, but I intend to make an input menu that main refrences, so it seemed better to put the code in another method.

Is my code clean (probably far from it)?  Easy to read?  Am I overdoing the comments, or not specifing the code well enough?
Is it a bad idea using a recursive method for this as it has to keep memory for 80 recursions?  It seemed like a good idea, because I was condensing so much more code into a smaller space.

/**
 * This code is designed for use with CMD with an 80
 * ASCII character width space.
 * It adds and subtracts a space to a string and out prints
 * the line.
 * It uses recursion to create one full Right-Left cycle,
 * then uses an infinite while loop to repeat.
 */

class Wave8 {

  static String spaces = "";            // Holds the spaces
  static boolean direction = true;      // True is right, false is left

  // Bouncing loop
  public static void bounce() {

    if (spaces.length() == (80 - 1)) {        // Width minus the string after lead
      System.out.print(spaces + "a");

      direction = false;                      // Change direction
    }
    else
      System.out.println(spaces + "a");

    if (direction) {          // If going right
      spaces += " ";
      bounce();               // Recursion
    }

    if (!direction) {         // If going left
      spaces = spaces.substring(1);

      if (spaces.isEmpty()) {
        direction = true;
        return;
      }
      else System.out.println(spaces + "a");       // Normal routine

    }
  }

  public static void main(String args[]) {

    while (true) {
      bounce();
    }
  }
}

Also, is there a way to test for efficiency?  That would help greatly.


texts: Replacing "no-js" with “js” class in the body element properly

texts:
I currently have a WP site and in the header, I've put this in:

...
<body <?php body_class('no-js');?>>
    <script>document.body.className = document.body.className.replace( 'no-js' , 'js' );</script>
...

It works flawlessly and I've got no complaints, as it accomplishes the following:

Does not rely on jQuery to load, which is placed at the bottom of the code after the body element along with other js files.
Runs before the visible elements are loaded and doesn't change the look of the site after the site has loaded, meaning the user sees exactly what is supposed to be seen.
Code is placed immediately after the body element is opened so it can find the body after the browser reads that it exists, meaning it's quick, small, and easy to spot.

I'm wondering if there's a more efficient way of doing this.

This comment adds it as a function. Why a function and not just drop it in like I did?
Here is where I think I originally got my code from.
Here's a performance comparison I found from an SO answer, but it doesn't help me much.

Solution doesn't have to be js; it can be anything, as long as it's the right way. Obviously I'm using the classes to distinguish when js is working or not for the corresponding CSS styling to apply.


texts:
I'm studying unit testing in swift and I would like to know if I'm doing the right way.

Here I have the model

struct ChangePasswordRequest: Encodable {
    var email: String
    var newPassword: String
    var token: String
}

And here the unit test

import XCTest
@testable import MyProject

class ChangePasswordRequestTests: XCTestCase {

    var changePasswordRequest: ChangePasswordRequest!

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        changePasswordRequest = nil
        super.tearDown()
    }

    func testChangePasswordRequest() {

        // given
        let email = "abc@def.com.br"
        let newPassword = "abc123"
        let token =
        """
        rF1rHbYVCpcfyo6K2e7Q68QvKYdeOMt0vDXYehggGU3kx8XiuGmQylXabxbGAyUmSK9RnbL
        """

        // when
        changePasswordRequest = ChangePasswordRequest(email: email, newPassword: newPassword, token: token)

        let requestJSON = """
        {"email":"\(email)","token":"\(token)","newPassword":"\(newPassword)"}
        """

        changePasswordRequest = ChangePasswordRequest(email: email, newPassword: newPassword, token: token)
        guard let encodedRequest = try? JSONEncoder().encode(changePasswordRequest) else {
            XCTFail()
            return
        }

        // then
        XCTAssertEqual(String(data: encodedRequest, encoding: .utf8)!, requestJSON, "Any JSON key differs from model.")

    }

}

I never worked with unit test. It's possible to improve this test?


texts:
I have that XML-to-JSON function based on ElementTree.  It looks very simple but until now it does what it's supposed to do: give a JSON description of the document's ElementTree.

import xml.etree.ElementTree as ET

def dirtyParser(node):
    '''dirty xml parser
    parses tag, attributes, text, children
    recursive
    returns a nested dict'''

    # mapping with recursive call
    res = {'tag':node.tag,
           'attributes': node.attrib,
           'text': node.text,
           'children': [dirtyParser(c) for c in node.getchildren()]}

    # remove blanks and empties
    for k, v in res.items():
        if v in ['', '\n', [], {}, None]:
            res.pop(k, None)

    return res

Usage:

>>> some_xml = ET.fromstring(u'<?xml version="1.0" encoding="UTF-8" ?><records><record><him>Maldonado, Gavin G.</him><her>Veda Parks</her></record></records>')
>>> dirtyParser(some_xml)
>>> {'tag': 'records', 'children': [{'tag': 'record', 'children': [{'tag': 'him', 'text': 'Maldonado, Gavin G.'}, {'tag': 'her', 'text': 'Veda Parks'}]}]}

Is it really that reliable?


texts: Generic method for checking database integrity on soft delete

texts:
I have written this generic method to check whether a object has a dependent items or not:

public void ItemDependant<TEntity>(Guid id,
    Expression<Func<TEntity, bool>> condition,
    Expression<Func<TEntity, string>> select) where TEntity : BaseModel
{
    var foundItems = _dbContext.Set<TEntity>().Where(x => x.IsDeleted == false).Where(condition);
    var isAny = foundItems.Any();

    if (isAny)
        throw new Exception($"You must first delete these dependent items: {foundItems.Select(select).ToList().Aggregate((i, j) => i + ", " + j)}");
}

Now in each delete method in our services we call this method this way:

public override void Delete(Guid id)
{
    // This entity has only one dependent item (ItemB)
    // It means that this entity is being used by ItemB
    // So we can't delete it from the database
    // We should first delete ItemB
    ItemDependant<ItemB>(id, m => m.ItemAId == id, s => s.Title);

    base.Delete(id);
}

It works like a charm But I'm wondering if there's a better way for doing this.

Update: There's also another problem with this approach, If the entity has several dependent entities, consumer the API must know about them and add them in order:

public override void Delete(Guid id)
{
    ItemDependant<ItemB>(id, m => m.ItemAId == id, s => s.Title);
    ItemDependant<ItemC>(id, m => m.ItemAId == id, s => s.Title);
    ItemDependant<ItemD>(id, m => m.ItemAId == id, s => s.Title);
    ItemDependant<ItemE>(id, m => m.ItemAId == id, s => s.Title);
    ItemDependant<ItemF>(id, m => m.ItemAId == id, s => s.Title);

    base.Delete(id);
}

One thing that comes in my mind is that, I should have only one ItemDependent(.... call, then this method must inspects all of the dependencies then at the end gives the user several error messages. I think this solution is better, Isn't it?


texts: Logs UI errors to a service provided in the configuration

texts:
As part of the project I am currently working on we want to log our UI component errors as well. I developed this package as a base.
It's a factory (basically, not sure if it's correctly a factory).
There is one function exposed configure that takes the parameters that each service (of the project) needs to supply and returns a logger; an object with four functions - debug, info, warn and error.

I am not sure if this is the right way to do it in javascript. Or in general. Is this how a factory should look? I have seen some that expose a function rather than an object that has a function on it but in my mind these two seem equivalent.

import uuid from 'uuid/v4';
import post from './post';

function requiredParam(param) {
  const requiredParamError = new Error(`Required parameter, "${param}" is missing.`);
  // preserve original stack trace
  if (typeof Error.captureStackTrace === 'function') {
    Error.captureStackTrace(
      requiredParamError,
      requiredParam
    );
  }
  throw requiredParamError;
}

const Logger = {
  configure: ({
    url = requiredParam('url'),
    service = requiredParam('service'),
    version = requiredParam('version'),
    apigeeClientId = requiredParam('apigeeClientId')
  }) => {
    const prepareForwardLogFunction = function prepareForwardLogFunction(logLevel) {
      return async function forwardLog(details, exception) {
        const payload = {
          ...details,
          service,
          version,
          loggername: 'UiLogger',
          serviceType: 'reactjs',
          level: logLevel,
          eventType: logLevel === 'error' ? 'Exception' : 'Trace',
          correlationId: uuid(),
          timestamp: new Date(),
          exception: exception !== undefined ? exception : null,
          request: global.window.location.href
        };

        try {
          await post(url, payload, apigeeClientId);
        } catch (error) {
          console.warn('UI Logger failed:', { url, payload, error }); // eslint-disable-line no-console
        }
      };
    };

    return {
      debug: prepareForwardLogFunction('debug'),
      info: prepareForwardLogFunction('info'),
      warn: prepareForwardLogFunction('warn'),
      error: prepareForwardLogFunction('error')
    };
  }
};

export default Logger;


texts: Function to create URL relative to a configured base URL

texts:
I have written this function to create a URL:

function createUrl(urlPath) {
    const endpoint = url.parse(env.config.get('myEndpoint'));
    endpoint.pathname = path.posix.join(endpoint.pathname, urlPath);
    return endpoint;
}

const basically creates a mutable object whose properties can still be modified.
Here, I need to declare some Object which will only be modified once. Am I correct in declaring endpoint as const?


texts: Determine whether there is a winner in tic-tac-toe game

texts:
Below a function which answers: is there a winner in tic-tac-toe game?

Also, there is a test suite I wrote for it.

def is_win(field):
    # check horizontal
    N = len(field)
    for i in range(N):
        if field[i][0] != 0 and len(set(field[i])) == 1:
            return True
        vertical = [field[j][i] for j in range(N)]
        if vertical[0] != 0 and len(set(vertical)) == 1:
            return True
    # check diagonal
    diagonal = [field[i][i] for i in range(N)]
    if diagonal[0] != 0 and len(set(diagonal)) == 1:
        return True
    o_diagonal = [field[N-i-1][i] for i in range(N)]
    if o_diagonal[0] != 0 and len(set(o_diagonal)) == 1:
        return True
    return False

assert is_win(
        [
            [0, 0, 0],
            [2, 2, 2],
            [0, 0, 0],
            ]) == True

print(1)
assert is_win(
        [
            [0, 2, 0],
            [0, 2, 0],
            [0, 2, 0],
            ]) == True
print(2)
assert is_win(
        [
            [0, 0, 2],
            [2, 2, 1],
            [0, 0, 1],
            ]) == False
print(3)

assert is_win(
        [
            [2, 0, 0],
            [0, 2, 0],
            [0, 0, 2],
            ]) == True
print(4)
assert is_win(
        [
            [0, 0, 2],
            [0, 2, 0],
            [2, 0, 0],
            ]) == True
print(5)
```


texts: Searching text files for string patterns that are each defined in their own classes

texts:
I'm trying to implement interfaces in my design but not sure if this is correct or if there is a better way to do it.

What I need to do is

open a text file
keep searching blocks of text until I find a string that matches against one of the classes that defines that string pattern
process the string I found
continue processing file where I left off

This is the code I'm using so far, but not sure if the design is correct.
Maybe something about creating a new instance of each stringType class just to check if the string matches with the one defined in the class seems wrong to me. I don't need to create the instance of the object until I actually need to do work on it.

EDIT - Forgot to add the process function, not sure if that changes anything

static void Main(string[] args)
{
    //get types that implement IStringType interface
    List<IStringType> types = TypeFactory.GetTypeList();

    //scan text file and check against the types, store any matches found
    var stringMatches =  from t in types
                        where Regex.IsMatch(sourceString, t.stringPattern)
                        select t.getNewInstance(Regex.Match(sourceString,t.stringPattern).Value);

    if (stringMatches.Any())
    {
        //process string matches
    }
}
public class stringType1 : IStringType
{
    public string stringPattern { get { return @"(?m)^TEST1.+[\r\n]"; } set { this.stringPattern = value; } }
    private string _Message { get; set; }

    public stringType1() { }
    public stringType1(string str)
    {
        _Message = str;
    }

    public string ProcessString(string match)
    {
       //specific code to processes stringType1

    }
    public IStringType getNewInstance(string msg)
    {
        return (IStringType)(new stringType1(msg));
    }
}

public class stringType2 : IStringType
{
    public string stringPattern { get { return @"(?m)^BLAH2.+[\r\n]"; } set { this.stringPattern = value; } }
    private string _Message { get; set; }

    public stringType2() { }
    public stringType2(string str)
    {
        _Message = str;
    }
    public string ProcessString(string match)
    {
       //specific code to processes stringType2

    }
    public IStringType getNewInstance(string msg)
    {
        return (IStringType)(new stringType2(msg));
    }
}

public interface IStringType
{
    string stringPattern { get; set; }
    string ProcessString(string str);
    IStringType getNewInstance(string str);
}

public static class TypeFactory
{
    public static List<IStringType> GetTypeList()
    {
        List<IStringType> types = new List<IStringType>();
        types.AddRange(from assembly in AppDomain.CurrentDomain.GetAssemblies()
                       from t in assembly.GetTypes()
                       where t.IsClass && t.GetInterfaces().Contains(typeof(IStringType))
                       select Activator.CreateInstance(t) as IStringType);
        return types;
    }
}