texts:
I want to create a web app that should let users remotely make a device do a variety of things simply using any other device, anywhere, without installing anything. To do that, the device which performs tasks should receive commands as fast as possible, and, possibly, using few Internet data.

This is the code I'm going to use to receive the commands. Obviously, a login system still needs to be implemented.

index.php (the device which receives commands must keep it opened in the web browser)

<?php
$lastModified=filemtime(__FILE__);
$etagFile = md5_file(__FILE__);
$ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);
$etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
header("Etag: $etagFile");
header('Cache-Control: public');
if (strtotime($ifModifiedSince)==$lastModified || $etagHeader == $etagFile){
    header("HTTP/1.1 304 Not Modified");
    exit;
}
else{
?>
<!DOCTYPE html>
<html>
<head>
<script>
function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
 if (window.ActiveXObject){
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
   }
  }
 }
 else if (window.XMLHttpRequest)
  return new XMLHttpRequest()
 else
  return false
}
</script>
<style>
body{
    font-family:Arial,Verdana,Geneva;
}
</style>
<title>Remote control</title>
</head>
<body>
<div id="content">
Hey there! It seems that you turned Javascript off. Turn it back on in order to make this site work.
</div>
<script>
function carica(){
    document.getElementById("content").innerHTML="I\'m ready to receive remote commands"
    var request=new ajaxRequest()
    request.onreadystatechange=function(){
     if (request.readyState==4){
      if (request.status==200 || window.location.href.indexOf("http")==-1){
       document.getElementById("content").innerHTML=request.responseText
      }
      else if(request.status==204){
          carica()
      }
      else{
       document.getElementById("content").innerHTML='An error occurred!';
      }
     }
    }
    request.open("GET", "content.php", true)
    request.send()
}
carica();
</script>
</body>
</html>
<?php
}
?>

content.php

<?php
$maximumAttempts = 30;
$sleepTime = 10;
$totalTime = $maximumAttempts * $sleepTime;
ini_set('max_execution_time', $totalTime);
for($i=1;$i<$maximumAttempts;$i++){
    if(file_exists("command.txt")){ //a different check will be performed once the login system will be implemented
        echo 'New command for this device received!'; //commands still need to be implemented
        $commandReceived = 1;
        break;
    }
    else{
        sleep($sleepTime);
    }
}
$commandReceived = isset($commandReceived) ? $commandReceived : 0;
if($commandReceived!=1){
    http_response_code(204);
}
?>

Is this method to receive commands good? Does it overload the server? Is it fast enough for the client?


texts: Simplifying exception handling on Enumerators

texts:
I have a files search function that iterates over a given directory until a given depth is reached and returns the found files. I did this via the Enumerate methods of the Directory class and yield return the results. Since it's very likely that I hit a directory that I can't access (e.g. system directories) or generate a too long path (if the depth is large), I have to catch the exceptions from these cases. However since I can't use yield in try/catch statements, I find my code pretty bloated, because I have to seperate the critical method calls from the rest.

Is there a better/shorter way to do this, or are there best practices for that case?

private IEnumerable<string> SearchSubdirs(string currentDir, int currentDepth) {

    IEnumerable<string> exeFiles;
    try {
        exeFiles = Directory.EnumerateFiles(currentDir, "*.exe");
    }
    catch (UnauthorizedAccessException uae) {
        Debug.WriteLine(uae.Message);
        yield break;
    }
    catch (PathTooLongException ptle) {
        Debug.WriteLine(ptle.Message);
        yield break;
    }

    foreach (string currentFile in exeFiles) {

        // Ignore unistaller *.exe files
        if (currentFile.IndexOf("unins", 0, StringComparison.CurrentCultureIgnoreCase) == -1) {
            yield return currentFile;
        }
    }

    if (currentDepth < maxDepth) {
        IEnumerable<string> subDirectories;
        currentDepth++;
        try {
            subDirectories = Directory.EnumerateDirectories(currentDir);
        }
        catch (UnauthorizedAccessException uae) {
            Debug.WriteLine(uae.Message);
            yield break;
        }
        catch (PathTooLongException ptle) {
            Debug.WriteLine(ptle.Message);
            yield break;
        }

        foreach (string subDir in subDirectories) {
            foreach (string file in SearchSubdirs(subDir, currentDepth)) {
                yield return file;
            }
        }
    }
}


texts: Code review for python password generator

texts:
The following code is a simple random password generator that spits out a randomized password based on some input flags.

import string
import random
import argparse

def gen_char(lower, upper, digit, special):

    _lower_letters = string.ascii_lowercase
    _upper_letters = string.ascii_uppercase
    _digits = string.digits
    _special = "!@#$%^&*()"

    _rand = random.SystemRandom()

    _case = ""

    if lower:
        _case += _lower_letters

    if upper:
        _case += _upper_letters

    if digit:
        _case += _digits

    if special:
        _case += _special

    if _case:
        return _rand.choice(_case)

    else:
        return _rand.choice(_lower_letters+_upper_letters+_digits+_special)

def main():

    """

    The following lines of code setup the command line flags that the
    program can accept.

    """

    parser = argparse.ArgumentParser()

    parser.add_argument("length", type=int, help="length of password")
    parser.add_argument("--lower", "-l",
                       help="Generates passwords with lower case letters",
                       action="store_true")
    parser.add_argument("--upper", "-u",
                       help="Generates passwords with upper case letters",
                       action="store_true")
    parser.add_argument("--digit", "-d",
                       help="Generates passwords with digits",
                       action="store_true")
    parser.add_argument("--special", "-s",
                       help="Generates passwords with special characters",
                       action="store_true")

    args = parser.parse_args()

    """

    The following lines of code calls upon the gen_char() function to
    generate the password.

    """
    _pass = ""

    for x in range(args.length):

        _pass += gen_char(args.lower, args.upper, args.digit, args.special)

    print _pass

main()

The code is in working condition. I'm looking for tips in terms of coding styles, readability and perhaps optimizations if any.

If anyone is interested, the code can be found on github.


texts: Generate the alphabet and select only specific letters

texts:
I am learning java and would like to create a very simple application but which uses SOLID principles.

The required functionality is: generate the alphabet with a possibility to select specific letters. For now there must be an option to select only even/odd letters but the project must be open for extra functionalities (which are unknown at the moment but may be defined in the near future).

I created a code but I got a feedback that my code is not using the Single Responsibility Principle. Could you please help me understand which part of my code is not in line with that principle and what can be done better?

abstract class Characters {
    private ArrayList<Character> array;

    public ArrayList<Character> getArray() {
        return array;
    }

    public Characters() {
        array = new ArrayList<>();
        for (int i = 0; i < 26; i++) {
            array.add((char) ('A' + i));
        }
    }

    public abstract void getModifiedArray(String arg);
}

class CharactersParity extends Characters {

    @Override
    public void getModifiedArray(String arg) {
        String arg2 = arg.trim().toLowerCase();

        switch (arg2) {
        case "even": {
            for (char c : getArray()) {
                if (c % 2 == 0) {
                    System.out.println(c);
                }
            }
        }
            break;
        case "odd": {
            for (char c : getArray()) {
                if (c % 2 != 0) {
                    System.out.println(c);
                }
            }
        }
            break;
        default:
            System.out.println("wrong parameter");
        }
    }
}


texts: Adding elements to a hash from an output

texts:
The script currently loops through an output line-by-line, picking out elements of interest and adds them to a hash data structure. If a key already exists (in this case the interface name), it appends data to it.

I can work with a data structure, but I am never happy with the approach I take of looping through the data line by line.

Is there a cleaner way of achieving this?

#!/usr/bin/env perl

use strict;
use warnings;
use feature 'say';

my $output = <<END;
1C:C1:DE:AC:15:C2   192.168.50.16     236263      dhcp-snooping   50    FastEthernet3/0/8
00:24:B5:F7:1A:E3   192.168.58.77     225905      dhcp-snooping   58    FastEthernet3/0/8
00:22:64:A6:E5:C6   192.168.50.61     139103      dhcp-snooping   50    FastEthernet3/0/38
00:1B:25:2E:91:2F   192.168.51.42     222285      dhcp-snooping   51    FastEthernet4/0/15
00:23:7D:4F:18:A5   192.168.51.36     382530      dhcp-snooping   51    FastEthernet4/0/21
C8:F4:06:E0:32:7C   192.168.57.47     258924      dhcp-snooping   57    FastEthernet4/0/21
18:A9:05:1E:5C:B3   192.168.49.21     256946      dhcp-snooping   49    FastEthernet2/0/34
00:22:64:1B:F7:8C   192.168.49.18     192605      dhcp-snooping   49    FastEthernet2/0/21
00:23:7D:50:68:A4   192.168.51.110    381036      dhcp-snooping   51    FastEthernet4/0/26
00:21:E1:FE:E0:94   192.168.57.87     177812      dhcp-snooping   57    FastEthernet2/0/6
00:23:7D:4E:BA:02   192.168.49.80     167839      dhcp-snooping   49    FastEthernet2/0/31
00:23:7D:4F:1A:23   192.168.51.95     293268      dhcp-snooping   51    FastEthernet2/0/36
5C:E2:86:F5:B3:04   192.168.57.48     177809      dhcp-snooping   57    FastEthernet2/0/31
END

my @data = split /\n/, $output;

use Data::Dumper;

my %data_str;
foreach my $line (@data) {
    my @output_data = split /\s+/, $line;
    # Interface already found, append IP and MAC
    if ( exists $data_str{ $output_data[5] }
        && $data_str{ $output_data[5] } eq $data_str{ $output_data[5] } )
    {
        push $data_str{ $output_data[5] },
            { $output_data[1] => $output_data[0] };
    }
    # Add IP address and MAC address to hash
    else {
        $data_str{ $output_data[5] }
            = [ { $output_data[1] => $output_data[0] } ];
    }
}

say Dumper( \%data_str );


texts:
I want to improve my code or structure. How does it look? Any comments or suggestions?

$(function() {

    function searchGit() {
        //grab value of search field
        var search = $('#search').val();

        // Validates entered value
        if (search.length > 0) {
            //pull json data from url
            $.ajax({
                url: 'https://api.github.com/legacy/repos/search/' + search,
                dataType: 'json',
                success: function(data) {

                    // use the results to template the html using _
                    var results = data.repositories,
                        resultsTemplate = _.template($("#results-template").html()),
                        resultingHtml = resultsTemplate({results : results});

                    // place the generated data into the html
                    $("#results-container").html(resultingHtml);
                }
            });
        } else {
            alert("Please enter repo name");
        }

        return false;
    }

    $('#submit').on('click', searchGit);
});


texts:
I am writing an API wrapper and the endpoint takes dates in a very specific format.

The user of the API can pass in the parameters in whatever format they prefer, but regardless of what they pass in, I want to be able to clean up their input prior to submitting their query.

My question centers around the best way to update the options hash in place, and I have thought of a few possible ways to implement.

A helper method inside the class so you can overwrite options = reformat_hash(options)
A singleton on that specific variable

def options.clean_up!
  # see internals below
end

Or open up Hash and do the cleaning from the class

class Hash
  def clean_hash!
    self.each { |key, value|
      if value.is_a? Date
        self[key] = value.strftime('%Y-%m-%d %H:%M:%S')
      else
        self[key] = value.to_s
      end
    }
  end
end

so that I can just call it on whatever the variable may be named like:

def api_request(options={})
  options.clean_hash!
  # the options variable is now clean and I can pass it to the api
  HHTParty.get(path, :query => options).parsed_response
end

Is there a best practice for modifying or formatting hashes after they're passed into a method?

I feel like #3 is the neatest, but should I be worried about opening up Hash to do this?


texts:
using System;
using System.Linq;
using RedditSharp;
using System.Net;
using RedditSharp.Things;

namespace reSharp
{
    class Program
    {
        public static void Main()
        {
            string sub = "/r/";
            string saveDir = @"SAVE_DIRECTORY";
            Console.WriteLine("Subreddit:");
            sub += Console.ReadLine();

            Console.WriteLine("Amount:");
            int amount = Convert.ToInt32(Console.ReadLine());
            amount += 1;

            Console.WriteLine("Time Period");
            string timePer = Console.ReadLine();

            Reddit reddit = new Reddit();
            var subreddit = reddit.GetSubreddit(sub);
            if (timePer == "all")
            {
                foreach (var post in subreddit.GetTop(FromTime.All).Take(amount))
                {
                    if (post.IsStickied || post.IsSelfPost || Convert.ToString(post.Url).Contains("reddituploads")) continue;
                    string postURL = Convert.ToString(post.Url);
                    DownloadImages(postURL, saveDir);

                }
            }
            else
            {
                if (timePer == "hot")
                {
                    foreach (var post in subreddit.Hot.Take(amount))
                    {
                        if (post.IsStickied || post.IsSelfPost || Convert.ToString(post.Url).Contains("reddituploads")) continue;
                        string postURL = Convert.ToString(post.Url);
                        DownloadImages(postURL, saveDir);

                    }
                }
            }

        }

        public static void DownloadImages(string imageURL, string userDir)
        {

            if (imageURL.Contains("gfycat.com"))
            {
                imageURL = imageURL.Replace("gfycat.com", "zippy.gfycat.com") + ".mp4";
            }

            if (imageURL.Contains(".gifv"))
            {
                imageURL = imageURL.Replace(".gifv", ".mp4");
            }

            Console.WriteLine("Downloading {0}", imageURL);
            string[] splitURL = imageURL.Split('/');
            int index = splitURL.Length - 1;
            string fileName = splitURL[index];
            WebClient client = new WebClient();
            try
            {
                client.DownloadFile(imageURL, userDir + fileName);
            }
            catch (Exception)
            {
                Console.WriteLine("[INFO] ERROR DOWNLOADING FILE");
            }
        }
    }
}

The program effectively just downloads pictures from a given reddit subreddit. How could this be tided? Thanks.


texts:
I've written a program to get the names along with the titles of some practitioners out of a webpage. The content stored within disorganized HTML elements (at least it seemed to me) and as a result the output becomes messier. However, I've managed to get the output as it should be.

The way I've written the scraper serves its purpose just fine but the scraper itself looks ugly. Is there any way to make the scraper look good and still have it do the same job as it is doing currently?  For example, is there a way to eliminate the exception handlers?

This is how I've written it:

import requests
from bs4 import BeautifulSoup

url = "https://www.otla.com/index.cfm?&m_firstname=a&seed=566485&fs_match=s&pg=publicdirectory&diraction=SearchResults&memPageNum=1"

def get_names(link):
    res = requests.get(link)
    soup = BeautifulSoup(res.text,'lxml')
    for content in soup.select(".row-fluid"):
        try:
            name = content.select_one(".span5 b").get_text(strip=True)
        except: continue  #let go of blank elements
        else: name

        try:
            title = content.select_one(".span5 b").next_sibling.next_sibling.strip()
        except: continue  #let go of blank elements
        else: title

        print(name,title)

if __name__ == '__main__':
    get_names(url)


texts:
I am working on some sampling to collect data for my research on SOLID Principles. One of my sample consists proceeding code snippet:

public abstract class Notify
{
    public abstract void NotifyClient();
}

public class OnPremisesClient : Notify
{
    public override void NotifyClient()
    {
        Console.WriteLine("You're getting these notifications because you opted....");
    }
}

public class CloudClient : Notify
{
    public override void NotifyClient()
    {
        Console.WriteLine("You're getting these notifications because you opted....");

        if (IsOnPremisesToo)
            NotifyClientAsOnPremisesClient();
    }

    public void NotifyClientAsOnPremisesClient()
    {
        Console.WriteLine("Awesome! You are also using On premises services...");
    }

    public bool IsOnPremisesToo { get; set; }
}

Calling class is:

public  class Program
    {
         public static void Main(string[] args)
          {
              var premisesClient = new OnPremisesClient();
              var cloudClient = new CloudClient();

              ProcessNotifications(new List<Notify> { premisesClient, cloudClient });
          }

          private static void ProcessNotifications(List<Notify> list)
          {
               HandleItems(list);
          }

          static void HandleItems(IEnumerable<Notify> notifications)
          {
              foreach (var notification in notifications)
              {
                 if (notification is CloudClient)
                 {
                     var cloudClient = notification as CloudClient;
                     cloudClient.IsOnPremisesToo = true;
                 }
                 notification.NotifyClient();
              }
          }
    }

In the preceding code snippet, I am trying to notify the client as per the type of Notify client could be a OnPremisesClient or CloudClient.

This code-snippet looks neat and clean, but I would like to discuss which SOLID principle it violates. After going through few SOLID resources, I thought it violates SRP as it uses if. In the future, if there will be new client like GalaxyClient, then this code need a new condition. There might be more violations.

Are SOLID principles really violate in the give code-snippet or just I am thinking it violates SOLID? I would appreciate it if someone tells the which principles are violating with reasoning. What would be the new code or what are changes should made to this code so, it'd follow SOLID Principles?


texts: Clearing filters, copying a range, and then pasting a formula down a row

texts:
Novice coder here. I have the following code to perform a few actions like clearing filters, copying a range, and then pasting a formula down a row till the last line.

It works perfectly, but it takes longer than a minute to complete since I am addressing each in my for next loop individually. Would anyone know how to speed this up by using a range call instead of a cell call?

My constraint is that I must start on row six of the column selected and autofill to the bottom. The same with the paste values of the column to the left.

 Sub testingme2()

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

Dim myvalue As Double, lastrow As Long, paster As String

lastrow = Worksheets("x").Cells(Rows.Count, 1).End(xlUp).Row
myvalue = Worksheets("y").Cells(6, 2).Value
paster = "formula"

If Sheets("x").FilterMode Then
    Sheets("x").Cells.AutoFilter
End If

Sheets("x").Select
Range("A6:AG5000").Select
Selection.Copy
Sheets("z").Select
Range("A6").Select
Selection.PasteSpecial xlPasteValues
Sheets("x").Select

For i = 6 To lastrow
    Worksheets("x").Cells(i, (myvalue) + 20).Copy
    Worksheets("x").Cells(i, (myvalue) + 20).PasteSpecial xlPasteValues
    Worksheets("x").Cells(i, (myvalue) + 21).Cells.FormulaR1C1 = paster
Next

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub


texts:
I'm pretty new to programming and made a few programs so far. I recently made a Calculator program and I hope you guys could tell me what I could do to improve.
int firstNumber;
string sign;
int secondNumber;
int answer;

Console.WriteLine("Input Number:");
firstNumber = Convert.ToInt32(Console.ReadLine());
Console.Clear();

Console.WriteLine("Input Sign:");
sign = Console.ReadLine();
Console.Clear();

Console.WriteLine("Input Second Number:");
secondNumber = Convert.ToInt32(Console.ReadLine());
Console.Clear();

switch (sign)
{
    case "+":
        answer = firstNumber + secondNumber;
        Console.WriteLine(answer);
        Console.ReadKey();
    break;
    case "-":
        answer = firstNumber - secondNumber;
        Console.WriteLine(answer);
        Console.ReadKey();
    break;
    case "*":
        answer = firstNumber * secondNumber;
        Console.WriteLine(answer);
        Console.ReadKey();
    break;
    case "/":
        answer = firstNumber / secondNumber;
        Console.WriteLine(answer);
        Console.ReadKey();
    break;
    default:
        Console.WriteLine("Invalid Input");
    break;
}


texts:
I have written a small program to query the Stack Exchange API, specifically for badges. The main idea of the program is to return the new list of Tumbleweed posts on Stack Overflow, every 10 minutes. The motivation for this bot was the Weed Eater hat.

The program queries the API every 10 mins. If there are new tumbleweed posts, Then it'll print the number of new posts with a link to the tumbleweed page. If there are no new ones, It waits for another 10 minutes.

The code for the same is

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.time.Instant;

public class RunBadger {

    private static final String apiKey = "my api key";
    public static Instant previousBadgeTimestamp = Instant.now();
    public static void main(String[] args) {
        try {
            while (true) {
                JsonArray weeds = getBadges().get("items").getAsJsonArray();
                int numberOfWeeds = weeds.size();
                if(numberOfWeeds!=0) {
                    System.out.println("[ [Badger](https://www.youtube.com/watch?v=dQw4w9WgXcQ) ] " + numberOfWeeds + " new [Tumbleweed posts](//stackoverflow.com/help/badges/63/tumbleweed)");
                }
                previousBadgeTimestamp = Instant.now();
                Thread.sleep(600000);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }
    public static JsonObject getBadges() throws IOException{
        String badgeIdUrl = "https://api.stackexchange.com/2.2/badges/63/recipients";
        JsonObject badgeJson = get(badgeIdUrl,"site","stackoverflow","pagesize","100","fromdate",String.valueOf(previousBadgeTimestamp.minusSeconds(1).getEpochSecond()),"key",apiKey);
        return badgeJson;
    }
    public static JsonObject get(String url, String... data) throws IOException {
        Connection.Response response = Jsoup.connect(url).data(data).method(Connection.Method.GET).ignoreContentType(true).ignoreHttpErrors(true).execute();
        String json = response.body();
        if (response.statusCode() != 200) {
            throw new IOException("HTTP " + response.statusCode() + " fetching URL " + (url) + ". Body is: " + response.body());
        }
        JsonObject root = new JsonParser().parse(json).getAsJsonObject();
        return root;
    }
}

I'd like to have an improved version of it. Particularly regarding the while(true) code block.


texts:
I just programmed a basic neural network in F# to learn the logical OR function. As I am very new to F# and especially functional programming, I did it the imperative way. And even tho it works, I find it highly unattractive. I would like to improve it to make it as functional-like as possible. I though about overloading operators to make scalar products between weights and neuroninput but i don't think its the classier way to make my program nicer.

I want to make my code functional-like.

module nnbasic

let mutable neuroninput = [0.0;0.0]
let mutable weight = [0.4;0.6]
let rate = 0.2
let threeshold = 2.0

// [input1; input2; desiredoutput]
let matrix = [
             [0.0;0.0;0.0];
             [0.0;1.0;1.0];
             [1.0;0.0;1.0];
             [1.0;1.0;1.0]
             ]

let display output real =
    if output = real then printfn "yes"
    else printfn "no"

let output (_ni: float list, _wi: float list) =
    if threeshold > _ni.[0]*_wi.[0] + _ni.[1]*_wi.[1] then 0.0 else 1.0

let mutable iter = 0
let mutable out = 0.0

while iter < 100 do
    for row in matrix do
        neuroninput <- [row.[0];row.[1]]

        out <- output (neuroninput, weight)
        weight <- [weight.[0]+rate*(row.[2]-out);weight.[1]]
        display out row.[2]

        out <- output (neuroninput, weight)
        weight <- [weight.[0];weight.[1]+rate*(row.[2]-out)]

        if threeshold > neuroninput.[0]*weight.[0] + neuroninput.[1]*weight.[1] then display 0.0 row.[2] else display 1.0 row.[2]
        iter <- iter+1


texts: Object-oriented Tamagotchi-like program with a GUI

texts:
I am currently working on a small python project for an undergraduate course in python. The task is to create a Tamagotchi-like program with a GUI. My question is whether my code is Object oriented or not? Here are my classes:

Tamagotchi class

class Tamagotchi(Canvas):

    def __init__(self, radie, x,y):
        super().__init__()
        self.radie = radie
        self.x=x
        self.y=y

        self.createCircle(x, y, radie, fill="black")

    def createCircle(self, x, y, radie, **kwargs):
        circle = self.create_oval(x-radie,y-radie,x+radie,y+radie,**kwargs)
        return circle

    def updateCircle(self,radie, **kwargs):
        self.delete("all")
        self.radie=radie
        self.createCircle(self.x,self.y,self.radie, fill="black")

GUI class

class GUI(Frame):
    def __init__(self):
        super().__init__()
        tamagotchi = Tamagotchi(60,140,125)
        tamagotchi.pack(side=TOP)

        activityList = []

        Style().configure("TButton", padding=(20, 20, 20, 20), font='serif 10')

        sizeLbl = Label(self, text="Storlek: ")
        sizeLbl.grid(row=0, column=3, sticky=N)

        size = Label(self, text = tamagotchi.radie, foreground="red", font=(None, 15))
        size.grid(row=0,column=3, sticky = S)

        sovaButton = Button(self, text="Sova", command = lambda: self.tamagotchiLogic("sova", activityList, tamagotchi, size))
        sovaButton.grid(row=0, column=0)

        tentaButton = Button(self, text="Tenta", command = lambda: self.tamagotchiLogic("tenta", activityList, tamagotchi, size))
        tentaButton.grid(row=0, column=1)

        festaButton = Button(self, text="Festa", command = lambda: self.tamagotchiLogic("festa", activityList, tamagotchi, size))
        festaButton.grid(row=1, column=0)

        pluggaButton = Button(self, text="Plugga", command = lambda: self.tamagotchiLogic("plugga", activityList, tamagotchi, size))
        pluggaButton.grid(row=1, column=1)

        self.centerWindow()

    def centerWindow(self):
        w = 300
        h = 393

        sw = self.master.winfo_screenwidth()
        sh = self.master.winfo_screenheight()

        x = (sw - w) / 2
        y = (sh - h) / 2
        self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def tamagotchiLogic(self, activity, activitylist, tamagotchi, sizeLabel):
        activitylist.append(activity)

        end = len(activitylist)
        actString = ''.join(activitylist[end-3:end])

        print(actString)

        growthCombinations = ["pluggasovatenta", "sovatentafesta"]
        declineCombinations = ["festasovatenta","tentapluggaplugga"]
        boredCombinations = ["festafestafetsa","pluggapluggaplugga","sovasovasova","tentatentatenta"]

        if actString in growthCombinations:
            tamagotchi.updateCircle(tamagotchi.radie*1.05, fill="black")

        elif actString in declineCombinations:
            tamagotchi.updateCircle(tamagotchi.radie*0.95, fill="black")

        elif actString in boredCombinations:
            tamagotchi.updateCircle(tamagotchi.radie*(1/sqrt(2)), fill="black")

        sizeLabel.config(text=round(tamagotchi.radie))

Main

def main():
    root = Tk()

    gui = GUI()
    gui.pack()

    root.mainloop()

if __name__ == '__main__':
    main()


texts: Scoping through embedded document in MongoId

texts:
I'm using MongoId in a Rails project. I need to select some products which contain some SKUs which has an embedded document. The models are respectively Product and Sku.

The point is I want to keep it DRY and the conditions I apply to those subdocument already exist as a scope of the model. My working strategy so far is to fetch all the skus of each products, apply the SKU scope and return an array of ids. Then, I just use this array to get the correct products.

  # in models/product.rb
  scope :has_available_sku, -> do
    skus_ids = self.all.reduce([]) do |acc, product|
        acc << product.available_skus.map(&:id)
    end.flatten
    self.where("skus._id" => {"$in" => skus_ids})
  end

  def available_skus
    skus.is_active.in_stock.order_by({:discount => :desc}, {:quantity => :desc})
  end

  # in models/sku.rb
  scope :is_active, -> { where(:status      => true) }
  scope :in_stock,  -> { any_of({:unlimited => true  }, {:quantity.gt => 0}) }

As you can see, if the scopes in the sku model change at some point, or even in the product model, the has_available_sku will still work because the MongoDB logic is contained in only area.

I could have queried another way and just put all the conditions in the has_available_sku scope and use things like where("skus.status" => true) but it's hardly maintainable.

Is my strategy valid or is it a bad idea to do this way? Is there any magic method I'm not aware of in MongoId which would make this more simple? Finally, is the second solution (not DRY) a better way to go?

NOTE: If you're curious and don't know, SKUs are basically the different subtype of a product, like an XXL and XL version of a t-shirt.


texts:
I was working on an assignment and I was hoping to know if the merge sort algorithm I wrote in Python was not making any unnecessary computations.

def sort(some_list):

    if len(some_list) > 1:
        return merge(sort(some_list.__getslice__(0, len(some_list)/2)),\
         sort(some_list.__getslice__(len(some_list)/2, len(some_list))))
    else:
        return some_list

def merge(list_left, list_right):

    sorted_list = []

    while len(list_left) > 0 or len(list_right) > 0:

        if len(list_left) == 0:
            sorted_list.append(list_right.pop(0))

        elif len(list_right) == 0:
            sorted_list.append(list_left.pop(0))

        elif list_left[0] < list_right[0]:
            sorted_list.append(list_left.pop(0))

        else:
            sorted_list.append(list_right.pop(0))
    return sorted_list

I did some testing by calling time function to check how much time it took to merge a list of numbers of size 100,000 with different presortedness values (where a presortedness = 0 means it's completely random and presortedness = 1 means the list is already sorted).

I'm using a core i7 processor and working from PyCharm on an Ubuntu 14.04 OS.

This was my result:

-------Test for Merge Sort----------------
Presortedness = 0.00 (completely random)
Time elapsed = 1.90153600

Presortedness = 0.25
Time elapsed = 1.89535800

Presortedness = 0.50
Time elapsed = 1.90894200

Presortedness = 0.75
Time elapsed = 1.90660100

Presortedness = 1.00 (sorted)
Time elapsed = 1.79297100


texts:
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Example 1:

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

^
|
|        o
|     o
|  o
+------------->
0  1  2  3  4

Example 2:

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

^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6

Inputs
[[1,1],[2,2],[3,3]]
[[0,0],[94911151,94911150],[94911152,94911151]]
[[1,1],[2,2],[3,3],[131,131],[3111,3111],[31,31],[13,13],[113,11],[5,5]]

Outputs
3
2
8

Code
#include <vector>
#include <map>
#include <utility>
#include <algorithm>

struct Solution {
    static const inline int maxPoints(const std::vector<std::vector<int>> &points) {
        int max_points = 0;

        for (int index_i = 0; index_i < points.size(); index_i++) {
            int overlap = 0;
            int y_on = 0;
            int curr = 0;
            map<pair<int, int>, int> points_map;

            for (int index_j = index_i + 1; index_j < points.size(); index_j++) {
                if (points[index_i] == points[index_j]) {
                    overlap++;

                } else if (points[index_i][0] == points[index_j][0]) {
                    y_on++;

                } else {
                    const int x = points[index_i][0] - points[index_j][0];
                    const int y = points[index_i][1] - points[index_j][1];
                    const int gcd = greatest_common_divisor(x, y);
                    points_map[ {x / gcd, y / gcd}]++;
                    curr = std::max(curr, points_map[ {x / gcd, y / gcd}]);

                }

                curr = std::max(curr, y_on);
            }

            max_points = std::max(max_points, curr + overlap + 1);
        }

        return max_points;
    }

private:
    // std::gcd
    static inline const int greatest_common_divisor(const int a, const int b) {
        if (not b) {
            return a;

        } else {
            return greatest_common_divisor(b, a % b);
        }
    }
};

References

Problem

Discuss

Solution


texts: Regular expression to identify java function

texts:
I am trying to identify a java function block addition  in a diff file (new line start with + in diff).
For that I am using regular expression.

It is working fine, however I need to identify all (if not, at least maximum) possible combinations of keyword used in java method declarations.

Here is my regular expression written in my java program

Pattern functionPatter = Pattern.compile("\\+\\s*(public|private|protected)?(\\s+static)?(\\s+final)?\\s+\\w+\\s+\\w+\\s*\\(.*?\\)\\s*(throws .*)+\\{.*\\}",Pattern.DOTALL);

Please suggest me if I am missing anything.


texts:
Summary

  In a block storage system, new data is written in blocks. We are going to represent the flash memory as one sequential array. We have a list of block writes coming in the form of arrays of size 2: writes[i] = [first_block_written, last_block_written].

  Each block has a rewrite limit. If rewrites on a block reach a certain specified threshold we should run a special diagnostic.

  Given blockCount (an integer representing the total number of blocks), writes (the list of block-write arrays of size 2), and threshold, your task is to return the list of disjoint block segments, each consisting of blocks that have reached the rewrite threshold. The list of block segments should be sorted in increasing order by their left ends.

Examples

  For blockCount = 10, writes = [[0, 4], [3, 5], [2, 6]], and threshold = 2, the output should be blockStorageRewrites(blockCount, writes, threshold) = [[2, 5]].

  After the first write, the blocks 0, 1, 2, 3 and 4 were written in once;
  After the second write, the blocks 0, 1, 2 and 5 were written in once, and the blocks 3 and 4 reached the rewrite threshold;
  After the final write, the blocks 2 and 5 reached the rewrite threshold as well, so the blocks that should be diagnosed are 2, 3, 4 and 5.
  Blocks 2, 3, 4 and 5 form one consequent segment [2, 5].

  For blockCount = 10, writes = [[0, 4], [3, 5], [2, 6]], and threshold = 3, the output should be
  blockStorageRewrites(blockCount, writes, threshold) = [[3, 4]]

  For blockCount = 10, writes = [[3, 4], [0, 1], [6, 6]], and threshold = 1, the output should be
  blockStorageRewrites(blockCount, writes, threshold) = [[0, 1], [3, 4], [6, 6]]

Constraints

1 ≤ blockCount ≤ 10**5
0 ≤ writes.length ≤ 10**5
writes[i].length = 2
0 ≤ writes[i][0] ≤ writes[i][1] < blockCount

First try

from itertools import groupby

def group_blocks(num_writes, threshold):
    i = 0
    for key, group in groupby(num_writes, lambda x : x >= threshold):
        # This is faster compared to len(list(g))
        length = sum(1 for _ in group)
        if key:
            yield [i, i + length - 1]
        i += length

def blockStorageRewrites(blockCount, writes, threshold):
    num_writes = [0] * blockCount
    for lower, upper in writes:
        for i in range(lower, upper + 1):
            num_writes[i] += 1
    return list(group_blocks(num_writes, threshold))

Here I just do exactly what is asked, I create an array of blockCount size, loop over the writes and lastly group the consecutive ranges with itertoos.groupby

After trying to optimize

I'm not quite sure what the complexity was, but I tried to lessen the load, yet I still didn't pass the TLE constraints

def get_bad_blocks(blockCount, writes, threshold):
    cons = False
    u = l = -1
    for i in range(blockCount):
        count = 0
        for lower, upper in writes:
            if lower <= i <= upper:
                count += 1
            if count >= threshold:
                if not cons:
                    cons = True
                    l = i
                    u = -1
                break
        else:
            u = i - 1
            cons = False

        if u != -1 and l != -1:
            yield [l, u]
            l = -1
    if cons:
        yield [l, i]

def blockStorageRewrites(blockCount, writes, threshold):
    return list(get_bad_blocks(blockCount, writes, threshold))

Questions

You can review any and all, but preferably I'm looking for answers that:

Tell me if my first example is readable
I'm less concerned about readability in my second try, and more interested in speed
Please ignore the PEP8 naming violations as this is an issue with the programming challenge site


texts:
Here goes the depth first search:

#include <vector>
#include <iostream>

using namespace std;

typedef vector<vector<int> > graph; // adjacency list, vertexs are integers

void dfs(graph g, int s0) // s0 is the first vertex in the search
{
    int n = g.size();

    if(s0 < 0 || s0 >= n) // invalid initial vertex
        return;

    vector<bool> already_seen(n, false);
    vector<int> to_be_handled {};

    to_be_handled.push_back(s0);

    while(to_be_handled.size() > 0)
    {
        int s = to_be_handled.back();
        to_be_handled.pop_back();

        if(!already_seen[s])
        {
            already_seen[s] = true;

            cout << s << " "; // handle s

            for(int v: g[s]) // add neighbors
                to_be_handled.push_back(v); // (*)
        }
    }
}

And for the breadth first search, just replace the line (*) with this line:

to_be_handled.insert(to_be_handled.begin(), v);

I guess using a queue would be more effective for the BFS but I initially just wanted to implement a DFS so don't mind the second one.


texts: Find log4net logfiles at runtime without adding dependency to project

texts:
I was searching for a way to get all active log4net logfiles (if any) at runtime without adding a reference to the project.

This is the solution I came up with:

private static IEnumerable<AbstractReportInformation> GetLog4NetLogfiles()
{
    var type = Type.GetType("log4net.LogManager,log4net");
    if(null == type)
        return new List<AbstractReportInformation>();

    dynamic[] repositories = type.GetMethod("GetAllRepositories").Invoke(null, null) as dynamic[];

    IEnumerable<FileInfo> files = repositories
        .SelectMany<dynamic, dynamic>(repos => repos.GetAppenders())
        .Where(appender => Type.GetType("log4net.Appender.FileAppender,log4net").IsAssignableFrom(appender.GetType()))
        .Select(appender => new FileInfo(appender.File));

    return files.Select(
        file => new FilesystemInformation(file)).Cast<AbstractReportInformation>().ToList();
}

It makes use of the dynamic keyword instead of doing it all with reflection.

Are there any obvious errors in my code?
Are there better ways to
achieve the same result?

I feel a bit unsure about leaving the safety of the otherwise strongly typed language / framework.

Update to explain why no references shall be used / why dynamic is used

The above code is used to "detect" whether log4net is present and then gathers the logfiles. The same will later be implemented for NLog and possibly other frameworks of that sort. The project I'm using this code in is a application health monitoring framework and I don't want to add a lot of references.


texts:
For example, if we have 120, the answer should contain (2,2,2,3,5),(2,60),(4,30),...

Here is my not-so-good attempt

for (int[] x : getPossibleProducts(120)) {
    System.out.println(Arrays.toString(x));
}

public static List<String> getPossibleProducts2(int n) {
    List<String> possprod = new ArrayList<String>();
    possprod.add(n + "");
    if (isPrime(n)) {
        possprod.add(n + "");
        return possprod;
    }
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            for (String y : getPossibleProducts2(n / i)) {
                possprod.add(i + "x" + y);
            }
        }
    }
    return possprod;

}

public static List<int[]> getPossibleProducts(int n) {
    List<String> l = new ArrayList<String>();
    Set<int[]> set = new HashSet<int[]>();
    List<String> possprod = getPossibleProducts2(n);
    for (String x : possprod) {
        String[] y = x.split("x");
        Arrays.sort(y);
        if (!l.contains(Arrays.stream(y).reduce("", (a, b) -> a + b))) {
            l.add(Arrays.stream(y).reduce("", (a, b) -> a + b));
            int[] z = stringArraytoIntArray(y);
            set.add(z);
        }
    }
    return new ArrayList<int[]>(set);
}

public static int[] stringArraytoIntArray(String[] a) {
    int[] arr = new int[a.length];
    for (int i = 0; i < a.length; i++) {
        arr[i] = Integer.parseInt(a[i]);
    }
    return arr;
}

public static boolean isPrime(int i2) {
    if (i2 == 2)
        return true;
    if (i2 % 2 == 0)
        return false;
    for (int i = 3; i * i <= i2; i += 2)
        if (i2 % i == 0)
            return false;
    return true;
}

Here is the output:

[15, 8]
[10, 3, 4]
[30, 4]
[2, 3, 4, 5]
[12, 2, 5]
[10, 2, 2, 3]
[10, 12]
[120]
[15, 2, 2, 2]
[15, 2, 4]
[3, 40]
[4, 5, 6]
[2, 2, 5, 6]
[20, 6]
[2, 2, 30]
[2, 20, 3]
[2, 60]
[2, 2, 2, 3, 5]
[24, 5]
[10, 2, 6]
[3, 5, 8]


texts:
This script based on previous NRPE script for monitoring load average. Same purpouse - get NRPE friendly output with minimal usage of non built in commands. In this case wasn't need to count with floating point. So I could omit bc.

Yes, I read Why is using a shell loop to process text considered bad practice. And there is a lot of true. Bud I am still thinking about these NRPE scripts as about bash scripting trainnig to get more practice.

Desired output:

MEMORY_TOTAL=2041316kB MEMORY_AVAILABLE=1049260kB | MEMORY_IN_PERCENTAGE=51;80;90

#!/usr/bin/env bash

set -o errexit -o pipefail

warning=80
critical=90

while read -a meminfo_row; do
  # Remove the colon character.
  row_value_lenght=$(( ${#meminfo_row[0]} -1 ))
  row_value=${meminfo_row[0]:0:$row_value_lenght}

  case $row_value in
    MemTotal)
      mem_total=${meminfo_row[1]}
      mem_apercent=$(( meminfo_row[1] / 100 ))
    ;;
    MemAvailable)
      mem_available=${meminfo_row[1]}
    ;;
  esac
done < /proc/meminfo

mem_percentage=$(( mem_available / mem_apercent ))

if [[ -z $mem_percentage ]]; then
  returned_text="MEMORY UNKNOWN - check script"
  returned_code=3
else
  returned_text="MEMORY_TOTAL=${mem_total}kB MEMORY_AVAILABLE=${mem_available}kB | MEMORY_IN_PERCENTAGE=$mem_percentage;$warning;$critical"
  if [[ $mem_percentage -gt $critical ]]; then
    returned_code=2
  elif [[ $mem_percentage -gt $warning ]]; then
    returned_code=1
  else
    returned_code=0
  fi
fi

echo "$returned_text"
exit $returned_code


texts:
I wrote this class which is comparing some values, how can I improve its performance and maybe make it prettier?

You can see at the bottom what type of data it requires, also the array size can reach 100 000 elements.

As it is the class is working fine, but I would like to get a second opinion on how to improve it (I know that is not something complicated but I would like to find new ways of doing this).

module Stat
  class CompareData
    def initialize(datas)
      @datas = datas
      @result_data = {'g_yesterday' => {inc: 0, dec: 0}, 'g_week' => {inc: 0, dec: 0}, 'g_month' => {inc: 0, dec: 0}}
end

  def get_data
    @datas.each do |data|
      %w[g_yesterday g_week g_month].each do |compare|
        @today_value = data.g_current
        compare_data data[compare], compare
      end
    end
    @result_data
  end

  private
  def compare_data second_value, date
    unless @today_value == 0 && second_value == 0
      if @today_value != second_value
        period = @result_data[date]
        period[:dec] += 1 if @today_value == 0
        if second_value == 0
          period[:inc] += 1
        else
          @today_value < second_value ? period[:inc] += 1 : period[:dec] += 1
        end
      end
    end
  end
 end
end

values = [{'g_current' => '2', 'g_yesterday' => '0', 'g_week' => '3', 'g_month' => '4'}, ..]

init = Stat::CompareData.new(values)
init.get_data

EDIT

I have pasted the wrong code here is the one that I wanted to post:

  def get_data
    @datas.each do |data|
      %w[g_yesterday g_week g_month].each do |compare|
        @today_value = data['g_current'].to_i
        compare_data data[compare].to_i, compare
      end
    end
    @result_data
  end

  def compare_data second_value, date
    unless @today_value == 0 && second_value == 0
      if @today_value != second_value
        period = @result_data[date]
        if @today_value == 0 || second_value == 0
          @today_value > second_value ? period[:inc] += 1 : period[:dec] += 1
        else
          @today_value > second_value ? period[:dec] += 1 : period[:inc] += 1
        end
      end
    end
  end


texts:
Question.

  There are 5 CPUs and N number of tasks in the queue. You have to use
  minimum CPUs to process the tasks.

  A task is of format [arrival time, time to process the task].

  Note:

  You can only use at most 5 CPUs. If it is not possible in 5 CPUs, print -1.
  The time to process the task should not be greater than 10     i.e (Time waiting in queue + time to process the task) <= 10.
  If to process the current task, you need more than 10 seconds in current CPU, you can move to a different CPU and check if it is
  possible to process the task in <=10 time.
  If it is not possible to process the task in <=10 or at most 5 CPUs, print -1.

Constraints.

  0 <= Arrival time <= 500

  1 <= time to process the task <= 10

  0 <= N <=500

  You can only use iostream library. No STL's are allowed.

  Time : 3 second for T test cases

Eg:-

  Input

  3

  1 6

  2 7

  3 1

  Output

  2

Explanation:

  3   - N

  1 6 - the first task arrives in CPU0 at time 1, and leaves at time 7 (1+6).
   CPUs used = 1.

  2 7 - the second task arrives in CPU0 at time 2, and wait for 5
  seconds in the queue, so overall processing time is 5+7 > 10. So it is
  moved to CPU1. CPUs used = 2.

  3 1  -  the third task arrives. it can go to CPU0 or CPU1, as
  processing time is 5 ( (7-3) + 1 ) and 7 ( (9-3) + 1 )   seconds respectively. CPUs used = 2.

  CPU1 is a fresh CPU. So task2 will be completed in 9 (2 + 7) seconds without any Time to wait in the queue.

My Approach:

Initially, thought this as a variant of minimum train-platform problem. But that was wrong.
Tried a greedy approach, but it gave -1 for some valid solutions.
Trying memoization approach.

Recursive approach solves the problem, but it gets timed out. (No wonder)

What is the possible way to save the state of int, int, int[]?

I am also open to an iterative solution for the same.

Below is the code.

#include <iostream>
using namespace std;

#define MAXN 500

int min_cpus_used = 6;

int N;
int arr[MAXN];
int len[MAXN];

void recurse( int task_idx, int cpus_used_so_far, int  exit_time_of_task_in_CPUs[] ){

    if( task_idx == N-1){
        min_cpus_used = min( min_cpus_used, cpus_used_so_far);
        return ;
    }

    if( cpus_used_so_far >= min_cpus_used ){
        return ; //optimization
    }

    for(int i=0; i<cpus_used_so_far ; i++){

        int processing_time = 0;
        int time_in_queue = exit_time_of_task_in_CPUs[i] - arr[task_idx];

        if( time_in_queue < 0 ) // ie processor is free before arrival
            time_in_queue = 0;

        processing_time = time_in_queue + len[task_idx];

        // try with existing CPUs
        if( processing_time <=10){
            int prev =  exit_time_of_task_in_CPUs[i];
            exit_time_of_task_in_CPUs[i] = arr[task_idx] + processing_time;

            recurse( task_idx + 1 , cpus_used_so_far , exit_time_of_task_in_CPUs ); // can we optimize passing array

            exit_time_of_task_in_CPUs[i] = prev;

        }

        // try with new CPU
        if (cpus_used_so_far+1 <= 5){

            int new_cpu_index = cpus_used_so_far + 1 - 1; // converting to zero index

            int prev = exit_time_of_task_in_CPUs[new_cpu_index];

            exit_time_of_task_in_CPUs[new_cpu_index] = arr[task_idx] + len[task_idx] ;

            recurse( task_idx+1 , cpus_used_so_far+1 , exit_time_of_task_in_CPUs );

            exit_time_of_task_in_CPUs[new_cpu_index] = prev;

        }else{
            return ;
        }

    }

}

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    cin>>N;

    for(int i=0;i<N;i++){
        cin>> arr[i] >> len[i];
    }

    int exit_time_of_task_in_CPUs[5]={0};
    recurse(0, 1, exit_time_of_task_in_CPUs);

    if(min_cpus_used==6){
        cout<< -1 <<endl;
    }else{
        cout << min_cpus_used <<endl;
    }

}

Kindly help me with your thoughts on optimizing this solution.


texts: Print the nodes of binary tree column-wise, using recursion and iteration

texts:
I am trying to code for both recursive and iterative approach to a problem.

Below is a recursive code to print the nodes of binarytree column wise. Basically I have count of root as 0 and if I move left I decrement count by 1 and if I move right I increment the count by 1:

public void printcolumnOrder_recursive(Tree curr,int count){
    if(curr == null) return;
    if(hm.get(count)!=null){
        List l = hm.get(count);
        l.add(curr.data);
        hm.put(count, l);
    }
    else{
        List l = new ArrayList<Integer>();
        l.add(curr.data);
        hm.put(count,l);
    }
    printcolumnOrder_recursive(curr.left,count-1);
    printcolumnOrder_recursive(curr.right,count+1);

}

I converted it to an iterative approach:

    Stack<Tree> st = new Stack<Tree>();
    Stack<Integer> ct = new Stack<Integer>();
    Tree node = curr;

    st.push(node);
    ct.push(0);

    while(!st.isEmpty()){
        Tree temp=st.pop();
        int count = ct.pop();
        if(hm.get(count)!=null){
            List l = hm.get(count);
            l.add(temp.data);
            hm.put(count, l);
        }
        else{
            List l = new ArrayList<Integer>();
            l.add(temp.data);
            hm.put(count,l);
        }
        if(temp.right!=null){
            st.push(temp.right);
            ct.push(count+1);
        }
        if(temp.left!=null){
            st.push(temp.left);
            ct.push(count-1);
        }

    }
    for(Integer key: hm.keySet()){
        for(Integer i: hm.get(key)){
            System.out.print(" " + i);
        }
        System.out.println("");
    }

Both implementations work fine.

I have used 2 stacks in the iterative approach, one for nodes in a tree and the other for count.

Do we need a stack for count? Is there a better way to do it?


texts:
I'm new to Python and decided to work on a personal project and make a program that web scrapes and downloads manga. It works as expected, however, I am sure that there is a better way to structure my code. I'd appreciate some guidance on how to better write this project. You can check it out on my GitHub here.

import threading
import requests
import os
import re
import queue

from bs4 import BeautifulSoup
from display import Display

def gen_title(link):
    """Finds title of manga and removes any illegal characters"""
    page = requests.post(link, data=dict(adult="true"))
    soup = BeautifulSoup(page.text, 'lxml')

    title = soup.find('h1', {"class": "hb dnone"}).find('a').get('title')

    # Search for invalid characters and remove them.
    return re.sub('[^A-Za-z0-9 ]+', '', title)

def get_volume(soup):
    """Finds volume num"""
    volume = soup.find('h1', {"class": "hb dnone"}).findAll('a')
    volume = volume[1].get('title')

    # Grab first number in title
    temp = re.findall('\d+', volume)
    return "Volume " + temp[0]

def write_image(image, title, volume, counter):
    """Writes image to a file"""
    # Write the image to a file in chapter directory
    imagefile = open(title + "/" + volume + "/" + str(counter) + ".png", 'wb')
    imagefile.write(image.content)
    imagefile.close()

def download_manga(start_link, end_link=""):
    """given a start link and end link from twistedhelscans.com, downloads all manga images"""
    next_link = start_link
    counter = 1

    # Deal with end link being first page
    if end_link.endswith('1'):
        end_link = end_link[:-6]

    # get title of manga
    try:
        title = gen_title(start_link)
    except:
        queue.put("Title not found")
        return

    while next_link != end_link:
        # Open initial page
        page = requests.post(next_link, data=dict(adult="true"))

        # check if end link is first page redirect
        if page.url == end_link:
            break

        queue.put(page.url)
        soup = BeautifulSoup(page.text, 'lxml')

        if not end_link:
            end_link = soup.find('h1', {"class": "hb dnone"}).find('a').get('href')

        # Find image link and vol. num
        try:
            volume = get_volume(soup)
            image = soup.find('div', {"class": "inner"}).find('img').get('src')
        except:
            queue.put("Could not find image link. Website is not Twisted Hel Scan page?")
            return

        # Download the image
        image = requests.get(image)

        # Make manga directory
        if not os.path.exists(title):
            os.mkdir(title)

        # Make volume directory
        if not os.path.exists(title + "/" + volume):
            os.mkdir(title + "/" + volume)
            counter = 1

        # Write image to file
        write_image(image, title, volume, counter)
        counter += 1

        # Find next link
        next_link = soup.find('div', {"class": "inner"}).find('a').get('href')
    queue.put("Done")

def on_click(window):
    """Fetches text from entries and calls download manga"""
    start_link = window.start_entry.get()
    end_link = window.end_entry.get()

    if not start_link.strip():
        queue.put("No start link given")
        return

    def callback():
        download_manga(start_link, end_link)

    t = threading.Thread(target=callback)
    t.start()
    display.progress.pack(fill='x')
    display.progress.start(15)

def periodic_call():
    """
    Check every 100 ms if there is something new in the queue.
    """
    display.process_incoming()
    display.root.after(100, periodic_call)

# Create window and bind go button
queue = queue.Queue()
display = Display(queue)
display.go_button.bind("<Button-1>", lambda x: on_click(display))
periodic_call()
display.root.mainloop()
os._exit(1)


texts:
I've written a small function for solving simple quadratic equations:

class EquationSolver
  def solve(x, *args)
    args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.reduce { |result, element| result + element }
  end
end

To calculate  f(3) for f(x)=3x3−2x2−x+5, one would write:

puts EquationSolver.new.solve(3, 3, -2, -1, 5)

However, is there a more elegant version of my function, more like reduce.with_index or something similar?


texts:
I have a list of Script that i want to execute them in parallel, i already find this way in Creating dynamic number of threads concurrently, so i use this piece of code here :

private int i;//<---------------------------------(1)
private String[] listScript = {"Script1", "Script2", "Script3", "Script4"};

private void executeQueries() throws InterruptedException {

    ExecutorService threadPool = Executors.newFixedThreadPool(listScript.length);
    // submit jobs to be executing by the pool
    for (i = 0; i < listScript.length; i++) {
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                executeQuerie();
            }
        });
        Thread.sleep(500);//<---------------------(2)
    }
    // once you've submitted your last job to the service it should be shut down
    threadPool.shutdown();
    // wait for the threads to finish if necessary
    threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

}

private void executeQuerie() {
    //execute scripts action
    System.out.println(listScript[i]);
}

I'm really not happy with this code, i will explain a little my code so you can understand more :

(1). I use this i variable outside the method so i can know which script i should to execute
  (2). I use Thread.sleep(500); to make sure that i execute the right script, without this i can execute the same script multiple time for example it can gives me:

Script1
Script1
Script2
Script2

My question is : how can i make sure that my scripts executed safely in parallel, should i improve this piece of code, or do you have any other safe way?


texts: Run length encoding of an input string (Coderbyte 'Run Length' challenge)

texts:
I'd like feedback on my solution to the outlined (medium level) programming challenge. What might be a more efficient or Pythonic solution?

The challenge as outlined by Coderbyte:

  [Run Length] (https://www.coderbyte.com/solution/Run%20Length?tblang=german)

  Have the function RunLength(str) take the str parameter being passed and
  return a compressed version of the string using the Run-length encoding
  algorithm. This algorithm works by taking the occurrence of each repeating
  character and outputting that number along with a single character of the
  repeating sequence. For example: "wwwggopp" would return 3w2g1o2p. The
  string will not contain any numbers, punctuation, or symbols.

import doctest
import logging
import timeit

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(levelname)s - %(message)s")
# logging.disable(logging.CRITICAL)

def compress_string(s: str) -> str:
    """
    Indicate the freq of each char in s, removing repeated, consecutive chars

    E.g. "aaabbc" outputs '3a2b1c'

    :param s: the string to compress
    :type s: str
    :return: s as a compressed string
    :rtype: str

    >>> compress_string(s="wwwggopp")
    '3w2g1o2p'
    >>> compress_string(s="aaa")
    '3a'
    >>> compress_string(s="")
    ''
    >>> compress_string(s="b")
    '1b'
    >>> compress_string(s="abcd")
    '1a1b1c1d'
    """
    if s == "":
        return ""

    # indexes of change in characters
    indexes = [i+1 for i in range(len(s) - 1) if s[i+1] != s[i]]

    # add start and end index for slicing of s
    indexes.insert(0, 0)
    indexes.append(len(s))

    # slice string
    slices = [s[indexes[i]:indexes[i+1]] for i in range(len(indexes)-1)]

    compressed_str = "".join(f"{len(s)}{s[0]}" for s in slices)

    return compressed_str

if __name__ == "__main__":
    print(timeit.timeit("compress_string(s='wwwggoppg')",
                        setup="from __main__ import compress_string",
                        number=100000))
    doctest.testmod()


texts: Finding a perfect square smaller than an input number (Swift)

texts:
This code runs slowly, even with numbers smaller than 1,000,000. Can someone help me optimize this thing?

// Finds the highest perfect square below a certain input (int)

let target: Int = 758865 // Swap this out for testing other numbers
var smlSqr = [Int]()
let findLimit = Int(Double(target).squareRoot().rounded(.up))   // Saves CPU time, because perfect squares less than
                                                                // number a but higher than a.squareRoot is impossible.

var index = 0
var maxSqr = 0 // Final result
var candidate = 0

repeat {
    smlSqr.append(index * index)
    index += 1
} while(index < findLimit)

while candidate < smlSqr.count {
    if smlSqr[candidate] > maxSqr {
        maxSqr = smlSqr[candidate]
    }
    candidate += 1
}

print(String(maxSqr)) // For debugging, should print out 100
print(Int(Double(maxSqr).squareRoot())) // For debugging, making sure the number is actually a perfect square

I'm using Swift 5.1 on Xcode 11.
Also using a playground (if that helps)


texts: Find greatest number in array that is a product of some two elements in the same array

texts:
Given an array a, find the greatest number in a that is a product of two elements in a. If there are no two elements in a that can be multiplied to produce another element contained in a, return -1.

I am trying to get this to run as fast as possible.  I assume there is some math algorithm or formula to do this that I am unaware of.  This is the way I know how to find this answer.  However, I assume this would take a long time if the length of the array was huge.  Is there a faster way to do this?  I have provided the test.

using System;
using System.Linq;

namespace Exercise
{
    public static class Program
    {
        public static int maxPairProduct(int[] a)
        {
            int x = -1;

            for (int i = 0; i < a.Length; ++i)
            {
                for (int j = i + 1; j < a.Length; ++j)
                {
                    int temp = a[i] * a[j];
                    if (a.Contains(temp) && temp > x)
                    {
                        x = temp;
                    }
                }
            }
            return x;
        }
    }
}

using NUnit.Framework;

namespace Exercise
{
    public class SuccessTests
    {
        [Test]
        public static void TestOne() => Assert.That(Program.maxPairProduct(new int[] { 10, 3, 5, 30, 35 }), Is.EqualTo(30));
        public static void TestTwo() => Assert.That(Program.maxPairProduct(new int[] { 2, 5, 7, 8 }), Is.EqualTo(-1));

    }
}


texts: Checking whether the max and min values occur equally frequently

texts:
An array is defined to be "maxmin equal" if it contains at least two different elements and the number of times the maximum value occur is the same as the number of times the minimum value occur. So {11, 4, 9, 11, 8, 5 , 4, 10} is maxmin equal, because the max value 11 and min value 4 both appear two times in the array.

Write a function called isMaxMinEqual that accepts an integer array and returns 1 if the array is maxmin equal; otherwise it returns 0.

Note: Please do not use any string methods. No sorting allowed. No additional data structures including arrays allowed.

If the input array is:

{} | isMaxMinEqual should return 0 (array must have at least two different elements)

{2} | 0 (array must have at least two different elements)

{1, 1, 1, 1, 1, 1} | 0 (array must have at least two different elements)

{2, 4, 6, 8, 11} | 1 (Both max value (11) and min value 2 appear exactly one time)

{-2, -4, -6, -8, -11} | 1 (Both max value (-2) and min value -11 appear exactly one time).

Here is my solution. Is it possible to combine the loops?

    int max;
    int min;
    int maxCount = 0;
    int minCount = 0;
    if (a.length > 2) {
        max = a[0];
        min = a[0];
    } else {
        return 0;
    }
    for (int num : a) {
        if (num > max) {
            max = num;
        }
        if (num < min) {
            min = num;
        }
    }
    for (int num : a) {
        if (max == num) {
            maxCount++;
        }
        if (min == num) {
            minCount++;
        }
    }
    if (maxCount == minCount) {
        return 1;
    }
    return 0;


texts:
int *getUserInput(FILE *fpin, int *elementCount) {
  int *userInput;
  // Load file into buffer
  int length = fileLength(fpin);
  char *buffer = (char *) malloc(length * sizeof(char));
  int written = fread(buffer, sizeof(char), length, fpin);
  // Number of int's allocated in userInput
  int allocated = 10;
  *elementCount = 0;
  // Allocate space for the numbers
  userInput = (int *) malloc(allocated * sizeof(int));
  // "tokenize" the buffer with " " and "\n" as delimiters
  char *tokenized = strtok(buffer, " \n");
  while (tokenized != NULL) {
   if (allocated == *elementCount) {
      allocated *= 2;
      // Reallocate space based on need
      realloc(userInput, allocated * sizeof(int));
    }
    // Store the number in the array
    userInput[(*elementCount)++] = atoi(tokenized);
    tokenized = strtok(NULL, " \n");
  }
  realloc(userInput, *elementCount * sizeof(int));
  free(buffer);
  return userInput;
}

It's a function I wrote for reading in numbers from a file, delimited by a space. Curious to hear any thoughts/possible improvements.


texts: Read function that properly handles interrupts

texts:
This function is meant to be used for reading files. It returns all bytes asked unless EOF is reached. It handles interrupts and returns -1 on errors.

//safe function to read all bytes asked, only returns less bytes if EOF
static ssize_t read_all(int fdes, void *buffer, size_t size)
{
  ssize_t ret;
  ssize_t ret2;

  ret = read(fdes, buffer, size);
  if(ret == -1){
    if(errno == EINTR)
      return read_all(fdes, buffer, size);

    return -1;
  }

  if(ret && ret != size){
    ret2 = read_all(fdes, buffer + ret, size - ret);
    if(ret2 == -1)
      return -1;

    return ret + ret2;
  }

  return ret;
}


texts: Detect how long an HTML button is pressed

texts:
I recently had the need to detect how long a button is pressed and perform different actions based on that. I found some examples on Stack Overflow, but the ones I looked at showed how to use timeout().

I came up with this. There are probably other ways to solve this. While searching, I found an example using IIFE in JavaScript, which I then used for this tiny example.

HTML:

<button id="button">click</button>

JavaScript:

(function(window, document, undefined){
    'use strict';
    var start;
    var end;
    var delta;
    var button = document.getElementById("button");

    button.addEventListener("mousedown", function(){
        start = new Date();
    });

    button.addEventListener("mouseup", function() {
        end = new Date();
        delta = end - start;
        if (delta > 0 && delta < 500) {
            alert("less than half second:");
        }
        if (delta > 1000) {
            alert("more than a second:");
        }
    });
})(window, document);


texts:
I'm trying to practice my C++ on my own;
At the moment I'm trying to implement the concept of operator overloading making my own string class/function.

I think I handled this correctly; the code runs successfully.
However I'm not so sure if my code is optimally written (do I need to make more methods/params const? Do I use to much excess code?) and did I do good memory management?

Thanks for all the feedback :)

#include <iostream>
#include <vector>
#include <string.h>
#include <stdio.h>
using namespace std;
class DynString {
private:
    char *c;

public:
    ~DynString() { delete[]c; }
    DynString() : c(NULL) {}
    //second constructor
    DynString(const char* input) {
        int x = strlen(input) + 1;
        c = new char[x];
        strcpy(c, input);
    }

    //(copyconstructor) TRIO //QUATRO
    DynString(const DynString& dynstring) {
        c = new char[strlen(dynstring.c) + 1];
        strcpy(this->c, dynstring.c);
    }
    //UNO
    friend ostream& operator<< (ostream& lhs, DynString& a) {
        lhs << a.c;
        return lhs;
    }
    //DUO
    char& operator[] (int i) {
        return c[i];
    }
    //TRIO
    DynString& operator+ (DynString& y) {
        char *newArray = new char[strlen(y.c) + strlen(this->c) + 1];
        strcpy(newArray, this->c);
        strcat(newArray, y.c);
        delete[] c;
        c = new char[strlen(newArray)];
        this->c = newArray;
        return *this;
    }

    //QUATRO
    friend DynString operator+ (char* x, DynString& y) {
        DynString newString;
        newString.c = new char[strlen(x) + strlen(y.c) + 1];
        strcpy(newString.c, x);
        strcat(newString.c, y.c);

        return newString;
    }
    //QUATRO
    DynString& operator+ (char* x) {
        char *newArray = new char[strlen(x) + strlen(this->c) + 1];
        strcpy(newArray, this->c);
        strcat(newArray, x);
        delete[] c;
        c = new char[strlen(newArray)];
        this->c = newArray;

        return *this;
    }
    //TRIO // QUATRO
    DynString& operator= (DynString& x) {
        char *newArray = new char[strlen(x.c) + 1];
        strcpy(newArray, x.c);
        delete[] c;
        c = new char[strlen(newArray)];
        this->c = newArray;
        return *this;
    }

};

int main()
{
    DynString stringA("Hello");
    DynString stringB(" Worlt");
    //UNO
    cout << stringA << stringB << std::endl;

    //DUO
    stringB[5] = 'd';

    //TRIO
    DynString stringC = stringA + stringB;
    cout << stringC << std::endl;

    DynString stringD;
    //QUATRO
    stringD = "The" + stringB + " Wide Web";
    cout << stringD << std::endl;

    system("pause");

    return 0;
}


texts: Drawing on a pixel in blocks and diagonally

texts:
I've been working on this mini project to teach myself how to better use the graphical functions and nested loops in Java. I have achieved my basic goal with this project to be able to draw on a screen pixel by pixel in blocks and diagonally.

The basic idea is that it draws on the screen pixel by pixel in two different ways, one is diagonally and one is block by block.

I'm looking for any way at all to improve my program without implementing code very much more advanced than the code used in the program so far. I'm really looking for any improvements at all. A way to make it more compact, faster running, basically anything at all to make it 'better'.

    /**
     * @author Samuel
     */
    package main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Draw extends JFrame{
    public static int width = 1280;
    public static int height = (width/16)*9;
    int x = 3;
    int y = 25;
    Color randomColor = Color.BLACK;
    public Draw() {

        this.setPreferredSize(new Dimension(width,height));
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        while(true) {
            nextPixel2(); //Change to nextPixel() for block, nextPixel2 for diagonal
            g.setColor(randomColor);
            g.drawLine(x, y, x, y);
            pixels++;
        }
    }
    //250000~ timer value = 1 Second/Pixel
    int timer = 1;
    int pixels = 0;
    int xLock = x;
    int xStart = x;
    int yLock = y;
    int yStart = y;
    int blockSize = 50;
    int changeColor = 5; //Diagonal change color
    int i = 0;
    public void nextPixel2(){ //Diagonal
        x--;
        y++;
        for(int i = 0;i < timer;i++){
            i++;
            System.out.println("Pixels drawn: "+pixels);
        }
        while(x < xStart || y > height){
            xLock++;
            x=xLock;
            y=yLock;
            while(x > width) {
                xLock--;
                x=xLock;
                yLock++;
                y=yLock;
            }
            if(y == height && x == width){
                xLock = xStart;
                x = xLock;
                yLock = yStart;
                y = yLock;
            }
            if(i < changeColor){
                i++;
            }else{
            generateColor();
            i=0;
            }
        }
    }
    public void nextPixel(){ //Blocks
        x++;
        pixels++;
            for(int i = 0;i < timer;i++){
                i++;
                System.out.println("Pixels drawn: "+pixels);
            }
            while(x-xLock >= blockSize){
                x=xLock;
                y++;
                while(y-yLock >= blockSize){
                    y=yLock;
                    xLock+= blockSize;
                    x=xLock;
                    while(xLock >= width){
                        yLock+= blockSize;
                        y=yLock-1;
                        xLock=xStart;
                        if(yLock >= height){
                            y = yStart;
                            yLock = yStart;
                            x = xStart;
                            xLock = xStart;
                        }
                    }
                generateColor();
                }
            }
        }
    public void generateColor(){
        Random rand = new Random();
        float red = rand.nextFloat();
        float green = rand.nextFloat();
        float blue = rand.nextFloat();
        randomColor = new Color(red, green, blue);
    }
    public static void main(String[] args){
        Draw draw = new Draw();
    }
}


texts:
Finding the prime numbers between two given integers in the minimum number of comparisons:

#include <stdio.h>
#include <conio.h>
#include <math.h>

void main()
{
    clrscr();
    int i,n,count,n1,n2;
    printf("Enter n1 and n2:");
    scanf("%d",&n1);
    scanf("%d",&n2);
    n=n1;
    int c=0; //variable to store number of comparisions (number of times while() runs)
    for(n=n1;n<=n2;n1++,n=n1)
    {
        count=0; //number of factors found
        i=2;
        while((n>0)&&(i<=sqrt(n))) //condition for minimum comparisions
        {
            printf("\n\t%d",c++);//printing the comparision number
            if(n%i==0)
            {
                count++;
                n/=i;
            }
            else i++;
        }
        if(count==0)
            printf("\n%d",n1);
    }
    getch();
}


texts: Python program to remove invalid parentheses

texts:
This is a Leetcode problem -

  Remove the minimum number of invalid parentheses in order to make the
  input string valid. Return all possible results.

  Note -

  The input string may contain letters other than the parentheses (
  and ).

Here is my solution to this challenge -

def remove_invalid_parentheses(s):

    removed = 0
    results = {s}
    count = {"(": 0, ")": 0}
    for i, c in enumerate(s):
        if c == ")" and count["("] == count[")"]:
            new_results = set()
            while results:
                result = results.pop()
                for j in range(i - removed + 1):
                    if result[j] == ")":
                        new_results.add(result[:j] + result[j + 1:])
            results = new_results
            removed += 1
        else:
            if c in count:
                count[c] += 1
    count = {"(": 0, ")": 0}
    i = len(s)
    ll = len(s) - removed
    for ii in range(ll - 1, -1, -1):
        i-=1
        c = s[i]
        if c == "(" and count["("] == count[")"]:
            new_results = set()
            while results:
                result = results.pop()
                for j in range(ii, ll):
                    if result[j] == "(":
                        new_results.add(result[:j] + result[j + 1:])
            results = new_results
            ll -= 1
        else:
            if c in count:
                count[c] += 1
    return list(results)

Explanation -

Scan from left to right, make sure count["("] >= count[")"].
Then scan from right to left, make sure count["("] <= count[")"].

Here are some inputs/outputs -

print(remove_invalid_parentheses("()())()"))
>>> ["()()()", "(())()"]

print(remove_invalid_parentheses("(a)())()"))
>>> ["(a)()()", "(a())()"]

print(remove_invalid_parentheses(")("))
>>> [""]

Here are the times taken for each output -

%timeit remove_invalid_parentheses("()())()")
6.54 µs ± 176 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit remove_invalid_parentheses("(a)())()")
8.43 µs ± 1.29 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit remove_invalid_parentheses(")(")
3.69 µs ± 67.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

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

Any help would be highly appreciated.


texts: Repetitive event handler for a toggling UI control

texts:
I feel like this bit of code could have been written more elegantly, especially with the huge if/else statements. Can somebody help me break this down? It would really help me out in the future.

// Contact
var c = 0;
var contactHeight = $('#contact-keebs').outerHeight();
$('#mail-wrap').click(function (e) {

    e.preventDefault();

    if (c++ % 2 == 0) {

        $('#contact-button').addClass('project-button').css('width', '71px').text('Projects');
        $('.mail-icon').attr('src', site.theme_path + '/img/icon-projects.png');
        $('#contact-button').shuffleLetters({callback:function(){
            if ($(window).scrollTop() != 0) {
                $('html, body').animate({
                    scrollTop : 0
                },200, function() {
                    $('#contact-keebs').fadeIn(200);
                    $('body').css({
                        height   : contactHeight,
                        overflow : 'hidden'
                    });
                    $('#contact-info, #clients').addClass('animated fadeInUp');
                });
            } else {
                $('#contact-keebs').fadeIn(200);
                $('body').css({
                    height   : contactHeight,
                    overflow : 'hidden'
                });
                $('#contact-info, #clients').addClass('animated fadeInUp');
            }
        }
        });

    } else {

        $('#contact-button').removeClass('project-button').css('width', '96px').text('Get in touch');
        $('.mail-icon').attr('src', site.theme_path + '/img/icon-contact.png');
        $('#contact-button').shuffleLetters({callback:function(){
            if ($(window).scrollTop() != 0) {
                $('html, body').animate({
                    scrollTop : 0
                },200, function() {
                    $('#contact-info, #clients').removeClass('animated fadeInUp');
                    $('body').css({
                        height   : '',
                        overflow : ''
                    });
                    $('#contact-keebs').fadeOut(200);
                });
            } else {
                $('#contact-info, #clients').removeClass('animated fadeInUp');
                $('body').css({
                    height   : '',
                    overflow : ''
                });
                $('#contact-keebs').fadeOut(200);
            }
        }
        });
    }
});

HTML

// Button

    Get in touch

// Contact section

Title statement

Email

Clients &amp; Partners

Client 1

Client 2

Client 3

Client 4

Client 5

Client 6

Client 7

Client 8


texts: Encoding special characters in URLs with Ruby

texts:
I have the following Ruby code snippet:

  url = "http://somewiki.com/index.php?book=#{author}:#{title}&action=edit"
  encoded = URI.encode(url)
  encoded.gsub(/&/, "%26").sub(/%26action/, "&action")

The last line is needed since I have to encode the ampersands (&) in the author and title but I need to leave the last one (&action...) intact.

Consider this example for clarity:

author = "John & Diane"
title = "Our Life & Work"
url = "http://somewiki.com/index.php?book=#{author}:#{title}&action=edit"
encoded = URI.encode(url)
encoded.gsub(/&/, "%26").sub(/%26action/, "&action")

# => "http://somewiki.com/index.php?book=John%20%26%20Diane:Our%20Life%20%26%20Work&action=edit"

Although this result is satisfactory, I'd like to clean the original code with the gsub/sub calls. Any ideas?

PS: I could "clean" both params before passing them to the url = ... line but then the % characters will be re-encoded as %25 by the URI.encode call so I don't think that's an option. I'd love to be proved wrong here though.


texts:
I was playing a fun little board game called U.S. Patent No. 1 about time traveling to register your time machine as the first U.S. patent. I started to wonder what the dice probabilities were for basic attacks. In the game, you rolls 2 dice to attack, and your opponent rolls 1 die for defense. If the attack result is greater than the defense, then a time machine part is "disabled", and if it is greater by 5 or more, than it is "destroyed"; otherwise it "misses". However, this is not the end: players can also have attack and defense bonuses ranging from 0-12, which are added to the roll result before making the comparison.

To begin my program, I first did a straightforward brute force calculation, where each number in the array was a probability out of 216, and attack and defense bonus from 0 through 12 were cycled through.

But this was a bit slower than I wanted (~500ms, not terrible), so I decided to utilize a bit more math and hardcode the probability distribution of two dice to use multiplication instead of addition. I also replaced the dict with enum keys with a list where 0 is "MISSED", 1 is "DISABLED", and 2 is "DESTROYED", which seemed to significantly reduce overhead by my timings (from ~200ms to ~50ms).

But then I looked more carefully at my results and realized something that is in retrospect obvious about probability distributions of this nature: adding one to both the attack and defense bonus means the bonuses have no affect on the distribution. Represented symbolically, the distribution for A, D is always going to be the same as the distribution for A + N, D + N for integers N. So instead of calculating separate values for attack and defense bonuses, I can just calculate a raw value for attack shift (which also reformatted my array to be smaller and have different dimensions):

from itertools import product
import numpy as np

def calculate():
    two_dice_prob = [0, *range(6), *range(6,0,-1)]
    result = np.zeros((25,3))
    for attack_shift in range(-12, 13):
        result_counts = [0] * 3
        for defense, attack in product(range(1,7), range(2,13)):
            base_attack = attack
            attack += attack_shift
            if attack - 5 >= defense:
                result_counts[2] += two_dice_prob[base_attack]
            elif attack > defense:
                result_counts[1] += two_dice_prob[base_attack]
            else:
                result_counts[0] += two_dice_prob[base_attack]
        result[attack_shift+12] = result_counts
    return result

if __name__ == '__main__':
    print("Result:")
    print(calculate())

The result is a numpy array where the top is an attack with a penalty of -12, and the bottom is the attack with a bonus of 12, and every other row has an attack bonus of 1 more than the previous row. By merit of processing less cases, it now only takes ~6ms.

I was wondering how I could optimize the calculate function even more. I suspect I am not utilizing numpy's efficiency fully, since I am still not completely familiar with it.


texts: Making CSS rules for links in header more DRY

texts:
I want to implement the cleanest amount of CSS through proper use of inheritance. All links need to be a shade of white, so lets say #fff

HTML

    BruxZir

    &equiv;

CSS

.header {
  background-color: #333;
  color: #fff;
  height: 36px;
  width: 100%;
  line-height: 36px;
}

/* should be replaced with image */
.headerLogo {
  display:inline;
  font-size: 24px;
  line-height: 36px;
  padding-left: 6px;
}
.headerLogo a{
  color:#fff;
  text-decoration:none;
}

.headerMenu{
  float:right;
  font-size: 36px;
  margin-right: 6px;
}

.headerMenu a {
  /* needs the same rules for color, font-size, no text-decoration */
}

Here is my Codepen

I am thinking that since many of these rules will apply to the rest of the links in the header, I can set this up somehow for better inheritance. Also wondering if I would be better served using s instead of
s for the logo and the menu?


texts: C# greedy algorithm to pick activities that do not clash with each other (corrected)

texts:
My task is the greedy algorithm:

The activity selection problem is characteristic to this class of problems, where the goal is to pick the maximum number of activities that do not clash with each other.

Sample input (the first line indicates the number of intervals; each subsequent line contains a start time and end time):

5
2 4
1 7
6 9
9 11
5 8

Corresponding output (maximum number of non-overlapping activities, followed by the indexes of those activities):

3
1 5 4

The output above indicates that the activities at time intervals 2-4, 5-8, and 9-11 can all be chosen with no overlap.

The program works on small data, but it is too slow for really big input and I don't know how to improve it. Any ideas?

  class Program
{
    static void Main(string[] args)

    {
       int N;
       int[,] a;
        using (StreamReader sr = new StreamReader(@"prednasky.in"))
        {
            string line;
            line = sr.ReadLine();
            N = int.Parse(line);
            a = new int[N, 2];
            int[] indx = new int[N];
            int[] b = new int[N];
            for (int i = 0; i < N; i++)
            {
                line = sr.ReadLine();
                int[] nums = line.Trim().Split().Select(int.Parse).ToArray();
                //the beginning of the interval to a[i, 0], indexes to a[i, 1]
                a[i, 0] = nums[0];
                a[i, 1] = i + 1;
                //The end of the interval to b[i]
                b[i] = nums[1];
                //indx is array of indexes, i sort it instead of array a
                indx[i] = i;
            }

            //now sort array of the end of the interval and array of indexes by it
            Array.Sort(b, indx);
            //now in 1 cycle going through a[index, *] and b. And save "correct" intervals to the start of a(becouse we already don't need it

            int last = 0;
            int poc = 0;
            for (int i = 0; i < N; i++)
            {
                if (a[indx[i], 0] > last)
                {
                    a[indx[poc], 0] = a[indx[i], 1];
                    poc++;
                    last = b[i];
                }
            }
            using (StreamWriter sr1 = new StreamWriter(@"rozvrh.out"))
            {
                sr1.WriteLine(poc);
                for (int i = 0; i < poc; i++)
                {
                    sr1.Write(a[indx[i], 0]);
                    sr1.Write(" ");
                }
                }
        }
    }

}


texts: Code Hunter 2.06: Count occurrences of 'a' in a string

texts:
I'm playing Code Hunt on level 2.06 (loops).  This level is about counting the number of "a" in a String.

public class Program {
public static int Puzzle(String s) {
   int ret = 0;
   for(int x = 0; x < s.length(); x++){
       if(s.charAt(x).equals('a')) ret++;
    }
return ret;
}

It actually works, but the game scores your code from 1 to 3 depending on the elegance of the code.  Any ideas on improving that elegance?


texts:
Can following code be called insertion sort?
I tried implementation according to my underdtanding...

#include<iostream>
void insertionSort(int* array,int length){
       for(int unsortedIndex=1; unsortedIndex<length;unsortedIndex++){
           for(int sortedIndex=0; sortedIndex<unsortedIndex; sortedIndex++){
            if(array[unsortedIndex] < array[sortedIndex]){
                int temp = array[sortedIndex];
                array[sortedIndex] = array[unsortedIndex];
                array[unsortedIndex] = temp;
            }
        }
    }
}


texts: isLessThan function for structure with 7 integers

texts:
The objective

I was trying to create a function that would compare 7 different integers. It should be able to be used to:

Sort the two structures in a consistent manner
Be able to detect if two structures are equal with !isLessThan(a,b) && !isLessThan(b,a)

The code

At first, I thought of using a hash function to reduce all the values to one, but then it occurred to me that I was over-engineering this simple problem.

This is language agnostic, but I ended up doing it like this:

bool isLessThan(const MyStruct& lhs, const MyStruct& rhs) {
    return
        lhs.a +
        lhs.b * 2 +
        lhs.c * 3 +
        lhs.d * 4 +
        lhs.e * 5 +
        lhs.f * 6 +
        lhs.g * 7
            <
        rhs.a +
        rhs.b * 2 +
        rhs.c * 3 +
        rhs.d * 4 +
        rhs.e * 5 +
        rhs.f * 6 +
        rhs.g * 7;
}


texts:
I am designing classes for a game with card deck. Please review my code.

Each Player gets Hand of cards
The Deck can be shuffled and cards are dealt one at a time from the deck and added to the players hands.

Specifically, I am confused with the good method signature for the method dealCard in the Deck class. I can either pass the player method to the method like - void dealCard(Player player) or get the card and add to hand of player -  Card dealCard(). Which of these implementation is good as per the practices of OOPS? How do I think in these kind of scenarios? Any advice can be helpful

    package main;
        //Each card has a value and a suite.
    public class Card {
        int value;
        SUITE suite;

        public Card(int value, SUITE suite) {
            this.value = value;
            this.suite = suite;
        }

        public int getValue() {
            return value;
        }

        public SUITE getSuite() {
            return suite;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public void setSuite(SUITE suite) {
            this.suite = suite;
        }

        @Override
        public String toString() {
            return "Card{" +
                    "value=" + value +
                    ", suite=" + suite +
                    '}';
        }
    }

package main;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class Deck {
    List<Card> cardDeck;

    public Deck() {
        this.cardDeck = new ArrayList<Card>();
        for(int value = 1 ; value <= 13 ; value++){
            for(SUITE suite : SUITE.values()){
             cardDeck.add(new Card(value,suite));
            }
        }
    }

    @Override
    public String toString() {
        return "Deck{" +
                "cardDeck=" + cardDeck +
                '}';
    }

    public void shuffle(){
        Random rand = new Random();
        //Generate two random numbers between 0 to 51
        for(int i = 0 ; i < 20 ; i ++){
            int firstCard = rand.nextInt(52);
            int secondCard = rand.nextInt(52);
            Collections.swap(cardDeck,firstCard,secondCard);
        }
    }

    public void dealCard(Player player){
       //Get next card and add to hand of the player
        Card removedCard = cardDeck.remove(0);
        player.getHand().add(removedCard);
    }

    public Card dealCard(){
        Card removedCard = cardDeck.remove(0);
        return removedCard;
    }

    //Size of the deck for testing purpose
    public int getSizeOfDeck(){
        return cardDeck.size();
    }
}

package main;
import java.util.ArrayList;
import java.util.List;

public class Player {
    List<Card> hand;

    public Player() {
        this.hand = new ArrayList<Card>();
    }

    public List<Card> getHand() {
        return hand;
    }

    @Override
    public String toString() {
        return "Player{" +
                "hand=" + hand +
                '}';
    }
}

package main;

public enum SUITE {
    HEART,
    SPADE,
    CLUB,
    DIAMOND
}

package main;
public class Main {
    public static void main(String args[]) {
        Deck deck = new Deck();
        System.out.println(deck);
        System.out.println("Size of deck is: "+deck.getSizeOfDeck());
        deck.shuffle();
        System.out.println("Deck after shuffling is "+deck);

        Player player1 = new Player();
        Player player2 = new Player();

        deck.dealCard(player1);
        System.out.println("Size of deck after dealing a card to player is "+deck.getSizeOfDeck());
        deck.dealCard(player2);
        System.out.println("Size of deck after dealing a card to player is "+deck.getSizeOfDeck());

        System.out.println("Hand of player 1 is "+player1.getHand());
        System.out.println("Hand of player 2 is "+player2.getHand());

        player1.getHand().add(deck.dealCard());
    }
}


texts:
I have an assignment to code a method that will print values in a diamond pattern. For example, if the method is called like printNumberDiamond(2), then the results should look like:

"  0  "
" 010 "
"01210"
" 010 "
"  0  "

I have spent a ton of time on writing the code that does this, but I am sure that it's not the most efficient/clean way. I am hoping to learn new strategies for accomplishing this, because this was very difficult for me to complete, and I almost just gave up, but I got it to work:

public static void printNumberDiamond(int diaCenter)
{
        printNumberDiamondTop(diaCenter);
        printNumberDiamondBottom(diaCenter);
}

public static void printNumberDiamondTop(int diaCenter)
{
    int maxAscendingRows = diaCenter + 1;
    int maxColumnLength = diaCenter * 2 + 1;
    int highestNbrForRow = 0;

    for(int row = 0, rowCtr=0;row<=diaCenter;row++)
    {
        int thisColumnLength = 0;
        int thisColumnMaxLeftSpaces = 0;

        if(row >= maxAscendingRows)
        {
            thisColumnMaxLeftSpaces = (maxColumnLength - rowCtr) / 2;
            rowCtr--;
        }
        else
        {
            thisColumnLength = maxColumnLength - row;
            thisColumnMaxLeftSpaces = (thisColumnLength - row) / 2;
            rowCtr++;
        }

        int nbrWritten = 0;
        int nbrDescendingWritten = 0;
        for(int col = 0;col < maxColumnLength;col++)
        {
            if(col < thisColumnMaxLeftSpaces)
            {
                System.out.print(" ");
            }
            else if(nbrDescendingWritten == 0 && nbrWritten > row)
            {
                System.out.print(" ");
            }
            else if(nbrWritten <= highestNbrForRow)
            {
                System.out.print(nbrWritten++);
                nbrDescendingWritten = nbrWritten - 1;
            }
            else if(nbrWritten > highestNbrForRow)
            {
                System.out.print(--nbrDescendingWritten);
            }
        }
        ++highestNbrForRow;
        System.out.print("\n");
    }
}

public static void printNumberDiamondBottom(int diaCenter)
{
    int maxColumnLength = diaCenter * 2 + 1;
    int highestNbrForRow = 0;
    for(int row = diaCenter;row>0;row--)
    {
        highestNbrForRow = row - 1;
        int thisColumnMaxLeftSpaces = (maxColumnLength - highestNbrForRow * 2) / 2;
        int nbrWritten = 0;
        int nbrDescendingWritten = 0;

        for(int col = 0;col < maxColumnLength;col++)
        {
            if(col < thisColumnMaxLeftSpaces)
            {
                System.out.print(" ");
            }
            else if(nbrDescendingWritten == 0 && nbrWritten > highestNbrForRow)
            {
                System.out.print(" ");
            }
            else if(nbrWritten <= highestNbrForRow && nbrWritten >= 0)
            {
                System.out.print(nbrWritten++);
                nbrDescendingWritten = nbrWritten - 1;
            }
            else if(nbrWritten > highestNbrForRow)
            {
                System.out.print(--nbrDescendingWritten);
            }
        }
        ++highestNbrForRow;
        System.out.print("\n");
    }