texts:
This is my first ever real 100% self made perl script, I'd like to know how I can improve it.

#!/usr/bin/env perl
#this script takes a directory and sorts the files into folders by file ending

use strict;
use warnings;
use File::Copy;

sub sort_files {
    my $dir = shift || '.';     #cwd if no directory given
    $dir =~ s/\/$//;            #remove trailing /

    opendir(DIR, $dir) or die $!;
    my @files = grep {
        !/^\./      #does not start with .
        && -f "$dir/$_" #is file
        } readdir DIR;

    my $len = @files;
    print "sorting $len files\n";
    foreach my $file (@files){
        my ($ext) = $file =~ /([^.]*$)/;#grabs file extension

        my $dest = "$dir/$ext/";
        if (not -d "dest"){     #create folder if it does not exist
            mkdir $dest;
            print "\tcreated directory $dest\n";
        }
        move "$dir/$file", $dest or die "$!";
        print "\t$file moved to $dest\n"
    }
}

sort_files @ARGV;
exit 0;

ninja edit: I just noticed that this script runs into problems if there is no file ending specified. Elegant solutions apreciated! (checking the file for !/\./ would work, but that's not elegant in my book)


texts: Basic, single-threaded implementation of SynchronizationContext

texts:
I am trying to write a SynchronizationContext in C# that represents a message queue, to be pumped from a main loop.

Edit: I see that I have forgotten to say - I need the message loop executions to be done a single, pre-determined thread. (In my case I want to push updates to an OpenGL context.)

Here is the class I have written:

public class SingleThreadedSynchronizationContext : SynchronizationContext
{
    private sealed class WorkItem
    {
        private readonly SendOrPostCallback _callback;
        private readonly object _state;
        private readonly ManualResetEventSlim _reset;

        public WorkItem (SendOrPostCallback callback, object state, ManualResetEventSlim reset)
        {
            if (callback == null)
                throw new ArgumentNullException ("callback");

            _callback = callback;
            _state = state;
            _reset = reset;
        }

        public void Execute ()
        {
            _callback (_state);
            if (_reset != null) {
                _reset.Set ();
            }
        }
    }

    private readonly ConcurrentQueue<WorkItem> _workItems = new ConcurrentQueue<WorkItem> ();
    private readonly Thread _executingThread;

    public SingleThreadedSynchronizationContext (Thread executingThread)
    {
        if (executingThread == null)
            throw new ArgumentNullException ("executingThread");
        _executingThread = executingThread;
    }

    internal bool HasWorkItems {
        get {
            return !_workItems.IsEmpty;
        }
    }

    private WorkItem ExecuteAndReturnNextWorkItem ()
    {
        WorkItem currentItem;
        if (_workItems.TryDequeue (out currentItem)) {
            currentItem.Execute ();
        }
        return currentItem;
    }

    private void ExecuteNextWorkItem ()
    {
        ExecuteAndReturnNextWorkItem ();
    }

    public override void Post (SendOrPostCallback d, object state)
    {
        _workItems.Enqueue (new WorkItem (d, state, null));
    }

    public override void Send (SendOrPostCallback d, object state)
    {
        if (Thread.CurrentThread == _executingThread) {
            WorkItem requestedWorkItem = new WorkItem (d, state, null);
            _workItems.Enqueue (requestedWorkItem);
            WorkItem executedWorkItem = null;
            do {
                executedWorkItem = ExecuteAndReturnNextWorkItem ();
            } while (executedWorkItem != null && executedWorkItem != requestedWorkItem);
        } else {
            using (var reset = new ManualResetEventSlim ()) {
                _workItems.Enqueue (new WorkItem (d, state, reset));
                reset.Wait ();
            }
        }
    }
}

And here is a (everything additional removed) example of my main loop:

class MainClass
{
    public static void Main (string[] args)
    {
        var synchronizationContext = new CustomSynchronizationContext ();
        SynchronizationContext.SetSynchronizationContext (synchronizationContext);

        while (true) {
            // Do something else in my loop;

            while (synchronizationContext.HasWorkItems) {
                synchronizationContext.ExecuteNextWorkItem ();
            }
        }
    }

It is my first attempt at doing something on that level in the CLR concerning threading, so I wonder whether I have made any mistake in writing it, or done some other kind of mispractice (e.g. wrong class, etc.).


texts: Filtering by value X from array Y with a fallback

texts:
I wrote a function that solve a special problem. But one of my 'special hardcore software engineers' told me that this is a bad solution - but he will not give me a better solution. So I ask you: What could I do better? (This is more an academic exercise than a bottleneck in my software.)

I have an array $tags of {n} objects. Each object has an attribute called type. Further I have an array $types of {n} integers (tag types).

First value (index 0) of $types has highest priority, second value (index 1) of $types second highest priority and so on.

If this function finds a higher priority tag type during its iteration thru $tags it discards the lower priority tags from $returnArray.

$count just tell this function how many tags of same tag type are allowed. So if there are three tags of highest priority tag type it will return first occurrence.

Expected result 1:

    $tags = [
          $obj1, //type 50
          $obj2, //type 1
          $obj3 //type 25
        ]

    $types = [1, 50]

filterTagsByType($tags, $types) //returns [$obj2] because it has type 1

Expected result 2:

    $tags = [
          $obj1, //type 50
          $obj3 //type 25
        ]

    $types = [1, 50]

filterTagsByType($tags, $types) //returns [$obj1] because it has type 50

This is my function - I hope comments will clarify everything.

/**
 * This function filters and returns one or many tags of a defined tag type.
 * Define tag types in $types - first tag type (index 0) has highest priority.
 * This function returns only highest
 * tag type found and will ignore lower priority tag types.
 *
 * @param Tag[] $tags Array of tag models
 * @param int[] $types Array of tag types, first (index 0) has highest priority
 * @param int $count Max tags of one type to be returned
 * @return Tag[]
 */
public function filterTagsByType($tags, $types, $count = 1)
{
  $priority = 1000;
  $returnTags = [];

  foreach ($tags as $tag)
  {
      // get priority level of this tag, 0 is highest.
      $newPriority = array_search($tag->type, $types);

      // check if this tag has same priority like a tag before
      //if so, check if there is still room for another tag in $returnTags
      if ($priority == $newPriority && count($returnTags) < $count)
      {
          $returnTags[] = $tag;
      }
      // check if new priority is less (higher priority) than last tags (that
      // was added to return array) priority
      elseif ($newPriority < $priority)
      {
          // clear and add new highest priority tag to return array
          // it won't overwrite same priority tags because this case would
          // caught by first if.
          $returnTags = [$tag];
          //set new priority
          $priority = $newPriority;
      }

      //break this foreach as soon as highest priority tag typ was found and in
      // return array is no room anymore.
      if (0 == $priority && count($returnTags) == $count)
      {
          break;
      }
  }

  return $returnTags;
}


texts: Any simpler and more efficient way of writing this code?

texts:
I've noticed I've got quite a few repeated lines in my code.

$start = mktime(0, 0, 0, 3, 1, 2014);
$rate = 1 / 30;
$amount = number_format(floor((time() - $start) * $rate));

$id = array(
    array("42706686", "rebel2america"),
    array("100004055720670", "marquez.candace"),
    array("100000756492404", "vince.goode.3"),
    array("100007763585373", "laura.allen.75491"),
);

// 70% chance of red an 30% of green
$status = array(
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("red", "no"),
    array("green", "yes"),
    array("green", "yes"),
    array("green", "yes")
);

$online = range(7, 21);

// create and assign a 'seed' value that changes
// every $duration and assign to mt_srand
$duration = 5;
$mins = date('i', strtotime('now'));
$seed = $mins - ($mins % $duration);
mt_srand($seed);

// use mt_rand to build an 'order by'
// array that will change every $duration
$orderBy = array_map(function() {
    return mt_rand();
}, range(1, count($id)));

// sort $ids against $orderBy
array_multisort($orderBy, $id);

$orderBy = array_map(function() {
    return mt_rand();
}, range(1, count($status)));
array_multisort($orderBy, $status);

$orderBy = array_map(function() {
    return mt_rand();
}, range(1, count($online)));
array_multisort($orderBy, $online);

for($i = 0; $i < 10; $i++) {
    $results1 = array_pop($id);
    $results2 = array_pop($status);
    echo "                            {$results1[0]}	\n";
    echo "                            {$results1[1]}	\n";
    echo "                            {$results2[1]}	\n";
}


texts: JavaScript loop to copy JDBC query results to a 2D array

texts:
I have a JS running in Google App Script, but for me, it's like an overall example/problem I ran into more often.
The script fetches via JDBC the results of a MySQL query. The result has about 60.000 rows. Fetching that goes quite fast. After that I take the result and use this JS code to write it into a 2D array:

var rangeArray = [];
var row = 1;
while (rs.next()) {
   var tempArray = [];
     for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
       tempArray.push(rs.getString(col + 1));
     }
   rangeArray.push(tempArray);
   row++;
}

So it's this loop, which costs most time.
Fetching the query result itself executes in about 12 seconds - which is pretty much the execution time of the MySQL server itself.

However, fetching the query results AND write them to the array takes 10 minutes.
I am not surprised that it takes that long but is there a principal way to avoid such loops and create the array more effectively.


texts: Solution to 3Sum problem on Leetcode using HashTable

texts:
The problem of 3sum is described as:

  Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Here is my code, am I right to say its complexity is O(N2), and how can I further optimize my code? Here I am using HashTable:

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        dct = {}
        trip = {}
        triplet = []

        nums_len = len(nums)
        for i in range(nums_len - 1):
            for j in range(i + 1, nums_len):
                key = nums[i] + nums[j]
                if key in dct:
                    if (i in dct[key]):
                        continue
                    dct[key] = dct[key] + [i, j]  # If exists, append more in a bucket
                else:
                    dct[key] = [i, j]

        for k in range(nums_len):
            supplement = -1*nums[k]  # nums[k] = - (nums[i] + num[j])
            if supplement in dct:
                entry = dct[supplement]  #look on the dict
                entry_len = len(entry)
                entry_num = entry_len//2
                for m in range(entry_num):
                    pair = [entry[m*2], entry[m*2+1]]
                    if (k not in pair):
                        candidate = [nums[entry[m*2]], nums[entry[m*2+1]], nums[k]]
                        candidate.sort()
                        key = str(candidate[0]) +  str(candidate[1]) + str(candidate[2])
                        if (key not in trip):
                            trip[key] = True
                            triplet.append(candidate)

        return triplet


texts: Find all words that can create a pyramid

texts:
I wanted to write something that would find all pyramid words within a supplied text file or list of strings. An example of a pyramid word is the word "deadheaded". It has one of the letter "h", two of "a", three of "e", and four of "d".
    This would form a pyramid if you were to stack the letters:

   h
  a a
 e e e
d d d d

I'm looking for input regarding various things, such as design (is this constructed well for a user and easy to understand?), extensibility, using the right data structures, dealing with input/output...

Would this be better designed with more OOP in it? For example, I could have a base class with sub classes finding words with different shapes than a pyramid. But I'm not sure how much it would help in this design, as it seems fairly script-like with all the string manipulation.

public class PyramidWordsFinder
{
    public PyramidWordsFinder()
    {
        this.pyramidWordList = new List<string>();
    }

    public IList<string> pyramidWordList { get; set; }

    public IReadOnlyList<string> LoadDictionaryFile(string filePath)
    {
        List<string> wordsDictionary = new List<string>();
        Encoding enc = Encoding.GetEncoding(1250);
        string[] lines = File.ReadAllLines(filePath, enc);
        wordsDictionary.AddRange(lines.Where(x => x.Length > 2));
        return wordsDictionary.AsReadOnly();
    }

    public void WriteWordListToFile(IEnumerable<string> words, string fullFileName)
    {
        if (String.IsNullOrWhiteSpace(fullFileName))
        {
            throw new ArgumentException("The file name is not correctly formed");
        }

        File.WriteAllLines(fullFileName, words);
    }

    public IList<string> FindPyramidWords(IReadOnlyList<string> wordList)
    {
        foreach (var word in wordList)
        {
            // Quick checks before seeing if pyramid word
            if (this.WordIsCorrectLength(word) && (word.ToLower().Distinct().Count() == this.GetMaximumLetterFrequency(word)))
                {
                if (this.DetermineIfWordIsPyramid(word))
                {
                    this.pyramidWordList.Add(word);
                }
            }
        }
        return this.pyramidWordList;
    }

    private int GetMaximumLetterFrequency(string word)
    {
        int total = 0;
        for (int i = 1; i <= word.Length; i++)
        {
            total += i;
            if (total == word.Length) return i;
        }

        return 0;
    }

    private bool WordIsCorrectLength(string word)
    {
        var correctLengths = new List<int> {6, 10, 15, 21, 28, 36, 45, 55 };
        if (correctLengths.Any(item=> item == word.Length))
        {
            return true;
        }

        return false;
    }

    /// <summary>
    /// Determines if the given word is a pyramid word
    /// </summary>
    /// <param name="word"></param>
    /// <returns></returns>
    public bool DetermineIfWordIsPyramid(string word)
    {
        var lowerCaseWord = word.ToLower();
        List<int> letterCounts = new List<int>();
        var distinctLetters = lowerCaseWord.ToLower().Distinct();

        // Adds up how many times each distinct letter is seen in the word
        foreach (var letter in distinctLetters)
        {
            var numLetters = lowerCaseWord.Count(x => x == letter);
            letterCounts.Add(numLetters);
        }

        // determines if the frequency the distinct letters descends consecutively
        var maximumLetterFrequency = this.GetMaximumLetterFrequency(lowerCaseWord);
        for (var i = maximumLetterFrequency; i >= 1; i--)
        {
            if (!letterCounts.Contains(i)) return false;
        }

        return true;
    }
}


texts:
I am programing in C language and have created the below functions to read files. There are two functions that I can use to read files. I wanted to know how I can further improve these two in terms of efficiency and out of these two which one would be better to use for reading files.

First is:

        char *read_data_from_file(char *data, char *path, int *fsz1)
        {
              int imgFD=0;
              struct stat fst;
              int fsz = *fsz1;
              fsz = 0;

              imgFD = open(path, O_RDONLY);
              if (imgFD <= 0){
                      *fsz1 = fsz;
                      return NULL;
              }

              fstat(imgFD, &fst);
              fsz = fst.st_size;
              printf("the size %s = %d inmfd = %d \n ", path, fsz, imgFD);
              if (fsz <= 0){
                      *fsz1 = fsz;
                      return NULL;
              }
              data = (char *)malloc(sizeof(char)*(fsz+1));
              read(imgFD, data, fsz);
              close(imgFD);

              *fsz1 = fsz;
              return (data);
      }

Another is:

      int read_data_from_file(int fd, void *buffer, int count)
      {
              void *pts = buffer;
              int status = 0, n;

              if(count < 0) return -1;
              while(status != count) {
                      n = read(fd, pts+status, count-status);
                      if(n < 1) return n;
                      status += n;
              }
              return (status);
      }

The calling portion of the above mentioned function is:

      int main(int argc, char *argv[])
      {
              struct stat sb;
              off_t len;
              char *p, *buffer = NULL;
              int fd;

              fd = open("test.txt" , O_RDONLY);
              if (fd == -1) {
                      perror ("open");
                      return 1;
              }
              if (fstat (fd, &sb) == -1) {
                      perror ("fstat");
                      return 1;
              }
              if (!S_ISREG (sb.st_mode)) {
                      fprintf (stderr, "%s is not a file\n", argv[1]);
                      return 1;
              }
              debug_print("printing start time and size : %d\n", sb.st_size);
              buffer = (char *)malloc(sizeof(char) * (sb.st_size + 1));

              read_data_from_file(fd, buffer, sb.st_size);


texts:
I'm new to python and curious if this is the most efficient way to read addresses from a SAP database, geocode them, read the results, and then write the information back to the database.
Everything below works, I'm just curious if this would make an expert cry beginner bad, or acceptable code for my first try. :-) I'm pretty sure my variable name formatting isn't 100% up to spec.
For reference on Geocodio, https://www.geocod.io/docs/?python#fields
import platform
import json
import sys
from hdbcli import dbapi
from geocodio import GeocodioClient

client = GeocodioClient('x')

conn = dbapi.connect(address='x', port=x, user='x', password='x')

cursor = conn.cursor()
sql_command = "SELECT ADDRNUMBER, CITY1, REGION, POST_CODE1,STREET FROM CV_COORDS_TO_PROCESS"
cursor.execute(sql_command)
rows = cursor.fetchall()

address = ''
for row in rows:
    #build the address string and save the address id
    address = row[4] +", " + row[1] +", " + row[2] +" " + row[3]
    addr_id = row[0]
    #send the address to geocodio
    location = client.geocode(address)

    #Read the results and break after the first result, as per the geocodio documentation,
    #in the event of multiple points, it lists them in order of confidence
    for subs in location['results']:
        lat = subs['location']['lat']
        long = subs['location']['lng']
        accuracy = subs['accuracy']
        accuracy_type = subs['accuracy_type']
        break

    ##update / insert into database
    merge_query = "upsert zsa_addr_coords values  ('100', %s, %f, %f, %f, '%s')"\
                  %(addr_id, lat, long, accuracy, accuracy_type ) + " where addr_id = '%s'" %addr_id
    try:
        cursor.execute(merge_query);
    except:
        print (ex)

    address = ''
cursor.close()
conn.close()

This is example of the results Geocodio returns:
{
  "input": {
    "address_components": {
      "number": "1109",
      "predirectional": "N",
      "street": "Highland",
      "suffix": "St",
      "formatted_street": "N Highland St",
      "city": "Arlington",
      "state": "VA",
      "zip": "22201",
      "country": "US"
    },
    "formatted_address": "1109 N Highland St, Arlington, VA 22201"
  },
  "results": [
    {
      "address_components": {
        "number": "1109",
        "predirectional": "N",
        "street": "Highland",
        "suffix": "St",
        "formatted_street": "N Highland St",
        "city": "Arlington",
        "county": "Arlington County",
        "state": "VA",
        "zip": "22201",
        "country": "US"
      },
      "formatted_address": "1109 N Highland St, Arlington, VA 22201",
      "location": {
        "lat": 38.886665,
        "lng": -77.094733
      },
      "accuracy": 1,
      "accuracy_type": "rooftop",
      "source": "Virginia GIS Clearinghouse"
    }
  ]
}


texts: Using method trait to return something in laravel model

texts:
I have question about scope yesterday, and someone gives an answer to don't return anything in scope. Is return something in scope really bad practice?  Should I not return anything in the model except query?
Rather than scope, I want to create a normal method to return the select2 format. I have so many model/table that I need to return to select2 format, I think it's WET (write every time) if I must write every model or controller. I think I need to use DRY(Don't Repeat Yourself) principle, so I want to use a trait like below:
trait ModelTrait
{
    public static function getSelect2format($column = "name")
    {
        $data = static::select('id', $column.' as text')->orderBy($column, 'asc')->where($column, "like", "%".request()->q."%");

        if (is_array(request()->filter) && !empty(request()->filter)) {
            foreach(request()->filter as $key => $val)
            {
                if(in_array($key,$this->filterable))
                {
                    $data = $data->where($key, $val);
                }

            }
        }
        $data      = $data->limit(5)->get();

        return $data;
    }
}

I just need to call use ModelTrait in every model that I need and call it in the controller like below:
public function selectJson()
{

    $data = Customer::getSelect2Format("column_name");

    return \Response::json($data);
}

Is the code above break the best practice?
What are the concerns or something that I need to improve?


texts:
I'm working on a small isometric drawing system in JavaScript. After much help from the Gamedev section, reading old questions, I've got something working. However, it's still a little hacky. I need to fix the culling to be more straightforward and it still isn't quite getting edge tiles down correctly.

I want to improve the code to ensure that:

The "center" tile is actually centered in the drawing area.
The are always enough edge tiles.
The code is straight-forward

Link to live Codepen.

Here is the camera drawing function:

function cameraDraw(position)
{
  var cen = {
        a: position.x + position.y,
        b: position.x - position.y
      },
      max = { //Use testSize instead of canvas size so we can see overdraw
        a: Math.floor(testSize.y/(terrainImg.width/2))+1, //Adding +1 to each for better edging?? Is this normal?
        b: Math.floor(testSize.x/terrainImg.width)+1
      },
      startPos = {
        x: (((cen.a - max.a) + (cen.b - max.b))/2),
        y: (((cen.a - max.a) - (cen.b - max.b))/2)
      },
      offset = { //Subtract 100 to show overdraw
        x: (startPos.x - startPos.y) * (terrainImg.width/2) + terrainImg.width/2 + terrainImg.width/4 - 100, //+terrainImg widths for better placement
        y: (startPos.x + startPos.y) * (terrainImg.width/4) + terrainImg.width/4 - 100
      };

  for(var a = cen.a - max.a; a < cen.a + max.a; a++)
  {
    for(var b = cen.b - max.b; b < cen.b + max.b+1/*I add +1 here to take care of edge issue on the bottom...Should I have to do that, if I'd done it right, above?*/; b++)
    {
      if ((b&1) != (a&1))
        continue;

      var x = (a+b)/2,
          y = (a-b)/2;

      world[x][y].draw(offset, position);
    }
  }
}

And here is the tile .draw function:

this.draw = function(offset, p)
{
  var drawPos = {
    x: (X-Y)*(terrainImg.width/2) - offset.x,
    y: (X+Y)*(terrainImg.width/4) - offset.y
  };

  if(X == p.x && Y == p.y)
    drawPos.y -= 15;

  ctx.drawImage(terrainImg, drawPos.x, drawPos.y);
};


texts: Using POST data to call a function from a specified class

texts:
I've inherited a class in a project which is purposed to execute a function that exists in POST data from a specified class. I've tried to clean this up as much as possible as well as secure it against SQL injection but I'm wondering if I could have done a better job or written this better. Any assistance would be much appreciated!

class RegistrationProceduresController
{
    public function __construct($username, $password, $host, $port, $dbname)
    {
        $SP = new RegistrationProceduresModel($username, $password, $host, $port, $dbname);

        // Sanitize all the incoming POST data and move into an array of its own
        $sanitized = array_map(array($this, 'sanitize'), $_POST);

        // Check whether the method passed via our POST data is a public function within the model, or even exists
        // at all. If not then skip to logging.
        if(method_exists($SP, $sanitized['function']))
        {
            try
            {
                // Execute the function we passed via our post data against the model class post-sanitization.
                $SP->$sanitized['function']();
            }
            catch(exception $ex)
            {
                json_encode("Exception when trying to execute a sanitized function in registration controller: " . $ex->getMessage());
            }
        }
        else
        {
            try
            {
                $val = isset($sanitized['function']) ? $sanitized['function'] . " does not exist in model."  : "was not specified";

                json_encode("Function " . $val);
            }
            catch(exception $ex)
            {
                json_encode("Threw an error after failing to evaluate whether a $_POST method exists. Review registration controller. " . $ex->getMessage());
            }
        }
    }

    /// <summary>
    /// Takes an input and returns it with all HTML characters stripped.
    /// Protects against SQL injection.
    /// </summary>
    /// <param name="$input">Any string based input</param>
    public function sanitize($input)
    {
        try
        {
            return htmlspecialchars(trim($input));
        }
        catch(exception $ex)
        {
            json_encode("Failed to sanitize POST data array in registration controller: " . $ex->getMessage());
        }

        return null;
    }
}

This project is using POST data to call a function since it's being initialized by JavaScript. If there's a better way to call a PHP function from within JavaScript I would definitely, definitely value feedback on it!


texts: Java number formatting in accountant style

texts:
I have written a string number formatter. I would like to know if this can be improved and any suggestions with how it's done.

The purpose of this function is to convert a double that has been converted to a string, using String.valueOf to a accounting style formatted number.

/**
     * this function formats a number string to show commas and an arbitrary amount
     * of decimal places
     * @param string the number String
     * @param decimal the decimal precision
     * @return
     */
private String formatNumberString(String string, int decimal) {

    char[] num = string.toCharArray();
    char[] reverse = reverse(num);
    int cnt = 0;
    List<Character> chars = new ArrayList();
    boolean fd = false;
    int fCnt = 0;

    if (contains(reverse, '.')) {
        for (char a : reverse) {
            if (!fd) {
                chars.add(a);
            } else {
                if (fCnt == 3) {
                    chars.add(',');
                    fCnt = 0;
                }
                chars.add(a);

                fCnt++;
            }

            if (a == '.') {
                fd = true;
            }

        }
    } else {
        for (char a : reverse) {
            if (fCnt == 3) {
                chars.add(',');
                fCnt = 0;
            }
            chars.add(a);
            fCnt++;
        }

    }
    char[] fin = new char[chars.size()];
    int cntr = 0;
    for (Character ch : chars) {
        fin[cntr++] = ch;
    }

    String finall = String.valueOf(reverse(fin));
    if (decimal == 0) {
        int dot = finall.indexOf(".");
        finall = finall.substring(0, dot);
    }

    if (finall.equals("0") || finall.equals("0.0") || finall.equals("0.00")) {
        finall = " - ";
    }

    return finall;
}

My contains function checks to see the array contains a decimal

/**
     * this function checks to see if a decimal is present in char array
     * @param ch
     * @param c
     * @return
     */
    public boolean contains(char[] ch, char c) {
        for (char a : ch) {
            if (a == c) {
                return true;
            }
        }
        return false;
    }

My reverse function is simple it reverses the char array

 public char[] reverse(char[] ch) {
        char[] temp = new char[ch.length];
        int cnt = 0;
        for (int i = ch.length - 1; i >= 0; i--) {
            temp[cnt++] = ch[i];
        }
        return temp;

    }


texts: Improving Least Recently Used implementation in Java

texts:
I wrote implementation of LRU in java and want to know if it can be improved further both in space and time complexity.

Input: Number of frames and reference string for pages.

Output: Number of page faults.

Also I am a little skeptical about its correctness because I got 6/10 in my practical lab.

Kindly ignore OOP's aspect of the program.

import java.util.*;
import java.io.*;
class Lru
{
 private static ArrayList<Integer> arl=new ArrayList<Integer>();
 private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 public static void main(String []args)throws IOException
 {
     String [] arr;int n,f,pf=0;
     System.out.println("enter the number of frames");
     n=Integer.parseInt(br.readLine());
     System.out.println("enter the reference string");
     arr = br.readLine().split(" ");
     for(String s:arr)
     {
         f=Integer.parseInt(s);
         if(arl.size()<n)
         { ++pf;arl.add(f);}
         else if(arl.contains(f))
         {
          arl.remove(arl.indexOf(f));
          arl.add(f);
         }
         else { arl.remove(0); arl.add(f);++pf;}
     }
     System.out.println("the total no of page faults are "+pf);
 }
}


texts: Merging nested tables into a single table

texts:
I made a function that merges nested tables into a single table.

The following function converts the headers. It takes an old table that has nested tables in its rows, takes all the headers of these and creates just one big table with one header.

This is only one part of all the creation for the new table. I basically do the same for the body and the footer.

I was wondering if there is anything I can do to improve my code.

function setTableHeader(oldTableName, newTableName) {
    $('table#'+newTableName).html($('
'));
    var firstRow = $('
'+newTableName+'
');
    var countryColumn = $('Country	');
    var row = $('

');
    var channels = $('

');
    var className = '';

    $('#'+oldTableName+' .budget-inner-table').each(function() {
        var oldInnerTable = $(this);
        var headerText = oldInnerTable.find('h3').eq(0).text();
        className  = ((insideText.indexOf('-') > 0) ? /- (.*)/.exec(insideText)[1]: insideText.replace(/ /g, '-')).toLowerCase();
        className = className.replace(' ', '-');
        var column = $('	').text(insideText).attr('id', className);
        row.append(column);
        // loops through the table row headers
        oldInnerTable.find('.budget-channel-table thead th').each(function() {
            var channelTableHeaders = $(this);
            if (channelTableHeaders.hasClass('month') || channelTableHeaders.hasClass('countryCode')) {
                return;
            }
            else {
                var insideText = channelTableHeaders.text();
            }
            var columnData = $('	').text(headerText)
                .addClass(className)
                .addClass(headerText.replace(/ /g, '-').toLowerCase().replace('.', ''));

            channels.append(columnData);
        });
    });
    row.prepend(countryColumn);
    // appends all rows to the header
    $('table#'+newTableName+' thead').append(firstRow).append(row).append(channels);
}


texts:
I needed a timer that fires in intervals for a given duration when e.g. a button is pressed. The button can be pressed several times thus I thought it would be easiest to create a new timer for each button press and the timer destroys itself when its duration passed. I wrote this...

Interface:

// timerhandler.h
class TimerHandler {
    public:
        virtual void processTimer()=0; // callback
        void startNewTimer(int interval,int duration);
        virtual ~TimerHandler(){}
};

//timerhandler.cpp
#include "timerhandler.h"
#include "mytimer.h"
void TimerHandler::startNewTimer(int interval,int duration){
    new MyTimer(this,interval,duration);
}

Usage: MainWindow inherits TimerHandler

//MainWindow.cpp
void MainWindow::on_pushButton_start_clicked() { this->startNewTimer(100,2000); }
void MainWindow::processTimer() { std::cout << "TIMER" << std::endl; }

Implementation:

//mytimer.h
#include <QObject>
#include <QTimer>
class TimerHandler;
class MyTimer : public QObject {
        Q_OBJECT
    public:
        friend class TimerHandler;
    private:
        TimerHandler* th;
        QTimer* timer;
        MyTimer(){};
        MyTimer(TimerHandler* th,int interval,int duration);
        ~MyTimer();
    public slots:
        void commitSuicide();
        void on_timer_fired();
};

//mytimer.cpp
MyTimer::MyTimer(TimerHandler* th,int interval,int duration) : th(th) {
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(on_timer_fired()));
    timer->start(interval);
    QTimer::singleShot(duration,this,SLOT(commitSuicide()));
}
MyTimer::~MyTimer(){ delete timer; }
void MyTimer::commitSuicide(){ delete this; }
void MyTimer::on_timer_fired(){ th->processTimer(); }

...it works, but I wonder if there is an easier way (less code) and it is horribly inflexible. I am a bit stuck when I want to change the code to allow different callbacks (that take different parameters).

I first tried a virtual slot as interface. I think it would work somehow, but when TimerHandler inherits QOject, then my MainWindow inherits QObject twice and I could not get it running.

Also if there is anything else that I can/should fix please let me know.


texts: Find path from source to destination in tilt maze

texts:
For a tilt maze general reference, you can refer to this example. The previous related code review discussion could be referred here.

The problem I want to resolve is to find all possible path (so that in the future I can find minimal path) from source to destination.

My major idea is:

Represent the maze by flag which direction I can move from a specific cell
Using recursion, move left/right, then move top/down, then left/right, then top/down, until the destination is reached

I'm not sure if my implementation is elegant, move left/right, then move top/down, then left/right, then top/down, until reach to destination, seems a bit hard-coded way. I'm wondering if there are any functional/logical bugs in my code -- even if I tested, but might be potential issues which I do not find yet.

  __ __ __ __
 |__   |__   |
 |  |  |     |
 |  |   __|  |
 |     |   __|
 |__|__ __ __|

class MoveEnum:
    CAN_MOVE_LEFT = 1
    CAN_MOVE_RIGHT = 2
    CAN_MOVE_UP = 4
    CAN_MOVE_DOWN = 8

class Maze:
    def __init__(self, matrix):
        self.matrix = matrix
        self.results = []
    def move_left(self, x1, y1):
        while self.matrix[y1][x1] & MoveEnum.CAN_MOVE_LEFT:
            x1 -= 1
        return (x1, y1)
    def move_right(self, x1, y1):
        while self.matrix[y1][x1] & MoveEnum.CAN_MOVE_RIGHT:
            x1 += 1
        return (x1, y1)
    def move_up(self, x1, y1):
        while self.matrix[y1][x1] & MoveEnum.CAN_MOVE_UP:
            y1 -= 1
        return (x1, y1)
    def move_down(self, x1, y1):
        while self.matrix[y1][x1] & MoveEnum.CAN_MOVE_DOWN:
            print y1
            y1 += 1
        return (x1, y1)
    # find shortest move from x1 y1, to x2, y2
    def move_path(self, x1, y1, x2, y2, is_left_right, path):
        if x1 == x2 and y1 == y2:
            self.results.append(path[:])
        elif is_left_right:
            (x, y) = self.move_right(x1,y1)
            if x != x1:
                path.append((x, y))
                self.move_path(x, y, x2, y2, not is_left_right, path)
                path.pop(-1)
            (x, y) = self.move_left(x1,y1)
            if x != x1:
                path.append((x, y))
                self.move_path(x, y, x2, y2, not is_left_right, path)
                path.pop(-1)
        else:
            (x, y) = self.move_up(x1, y1)
            if y != y1:
                path.append((x, y))
                self.move_path(x, y, x2, y2, not is_left_right, path)
                path.pop(-1)
            (x, y) = self.move_down(x1, y1)
            if y != y1:
                path.append((x, y))
                self.move_path(x, y, x2, y2, not is_left_right, path)
                path.pop(-1)

if __name__ == "__main__":
    maze_matrix = [[MoveEnum.CAN_MOVE_RIGHT, MoveEnum.CAN_MOVE_LEFT|MoveEnum.CAN_MOVE_DOWN, MoveEnum.CAN_MOVE_RIGHT, MoveEnum.CAN_MOVE_LEFT|MoveEnum.CAN_MOVE_DOWN],
                   [MoveEnum.CAN_MOVE_DOWN, MoveEnum.CAN_MOVE_UP|MoveEnum.CAN_MOVE_DOWN, MoveEnum.CAN_MOVE_RIGHT|MoveEnum.CAN_MOVE_DOWN, MoveEnum.CAN_MOVE_LEFT|MoveEnum.CAN_MOVE_UP|MoveEnum.CAN_MOVE_DOWN],
                   [MoveEnum.CAN_MOVE_UP | MoveEnum.CAN_MOVE_DOWN, MoveEnum.CAN_MOVE_UP|MoveEnum.CAN_MOVE_DOWN|MoveEnum.CAN_MOVE_RIGHT, MoveEnum.CAN_MOVE_UP|MoveEnum.CAN_MOVE_LEFT, MoveEnum.CAN_MOVE_UP|MoveEnum.CAN_MOVE_DOWN],
                    [MoveEnum.CAN_MOVE_UP | MoveEnum.CAN_MOVE_DOWN | MoveEnum.CAN_MOVE_RIGHT, MoveEnum.CAN_MOVE_UP | MoveEnum.CAN_MOVE_DOWN | MoveEnum.CAN_MOVE_LEFT, MoveEnum.CAN_MOVE_DOWN|MoveEnum.CAN_MOVE_RIGHT, MoveEnum.CAN_MOVE_UP|MoveEnum.CAN_MOVE_LEFT],
                   [MoveEnum.CAN_MOVE_UP, MoveEnum.CAN_MOVE_UP|MoveEnum.CAN_MOVE_RIGHT, MoveEnum.CAN_MOVE_UP | MoveEnum.CAN_MOVE_RIGHT, MoveEnum.CAN_MOVE_LEFT]]
    maze = Maze(maze_matrix)
    maze.move_path(0,0,3,4,True,[])
    maze.move_path(0, 0, 3, 4, False, [])
    print maze.results


texts:
I've never done anything like this before so I'd like someone else to look at this before I get too carried away :)

Am I making this more complicated than it needs to be?  I'm trying to make it EASY for other modules/scripts on this system to store and retrieve their settings. Hence why I trap the ConfigParser.NoOptionError error and return None and create the section if it doesn't exist in the set() method.

Suggestions?

import ConfigParser
import os

from ast import literal_eval as Eval

class _ConfParse(ConfigParser.ConfigParser):
    def __init__(self, confpath, conffile):
        ConfigParser.ConfigParser.__init__(self)
        self.conf_file = os.path.join(confpath, conffile)
        try: self.readfp(open(self.conf_file), 'r')
        except IOError as Err:
            if Err.errno == 2: pass
            else: raise Err

    def set(self, section, option, value):
        if self.has_section(section):
            ConfigParser.ConfigParser.set(self, section, option, str(value))
        else:
            self.add_section(section)
            ConfigParser.ConfigParser.set(self, section, option, str(value))

    def get(self, section, option):
        try: return Eval(ConfigParser.ConfigParser.get(self, section, option))
        except ConfigParser.NoOptionError: return None

    def save(self):
        self.write(open(self.conf_file, 'w'))

    def __del__(self):
        self.save()

class LocalConfig(_ConfParse):
    def __init__(self, conffile, confpath = '/etc/local/cnf'):
        _ConfParse.__init__(self, confpath, conffile)

class SysConfig(_ConfParse):
    def __init__(self, conffile, confpath = '/etc/sys/cnf'):
        _ConfParse.__init__(self, confpath, conffile)


texts: Generating and storing a unique salt in Oracle database using Java

texts:
This is my account table:

CREATE TABLE mwUser (
  username varchar2(20) primary key not null,
  salt varchar2(64) unique not null,
  hashedpw varchar2(64) not null,
  email varchar2(320) unique not null
);

When I register a new user with my java webservice I automatically generate a random salt and store in the database base (see code below):

Connection c = dataSource.getConnection();
Statement stmt = c.createStatement();
boolean isFound=true;
String randomSalt="";
while(isFound){
   isFound=false;
   String randomSalt=createRandomString(); //creates salt/random string
   ResultSet rs = stmt.executeQuery("SELECT * FROM mvUser where salt="+randomString);
   //check if salt is unique
   while (rs.next()) {
     isFound=true;
   }
}

Statement insertStmt = c.createStatement();
String hashedPW=hash(randomSalt+pw); //generates hashed pw
ResultSet rs = stmt.executeQuery("INSERT INTO mvUser VALUES(.....));

stmt.close();
c.close();

But as you can see, from my point of view my code is not clean/performant/readable because I have two statements (for checking if salt is unique and and second statement is for inserting).

How can I automatically generate an unique string(salt) and hash it at the same time. I am trying to make my code more performant and read able.


texts:
I need to create a class which acts as a paginated list. My use case is like this:

I am writing a library which makes a service call to fetch a List<obj>. Since the List<> can be large, the service expects me to call with a PAGE_SIZE. The service has also provided me with a TPS of x which I need call it with.

I need to do two things:

Rate Limit my calls to the Service
Expose a PaginatedList<> from the library so that any client can use the Library and rate limit as per their TPS.

I was wondering whether the way I am implementing this PaginatedList is correct or if there is a better way.

public MyPaginatedList {
  private static final PAGE_SIZE = 50;
  private ServiceClient client;
  private int pageToProcess = 0; //to keep track of which page we need to process next
  private List<Data> data; // this is what the library exposes to outside world
  public MyPaginatedList(ServiceClient client) {
    this.client = client;
  }

  public MyPaginatedList getDataList(){
    Servicerequest request = new ServiceRequest();
    request.setIndex(PAGE_SIZE*pageToProcess++); // fetch the next set of items

    this.data = client.APICall(request);
    return this; // we return the current object
  }
}

The public API exposed by this Library would use MyPaginatedList like this:

class Library {
  private ServiceClient client;

  public Library(ServiceClient client) {
    this.client = client;
  }
  public MyPaginatedList fetchData() {
    return new MyPaginatedList(client).getDataList();
  }
}

Any client of this library can use MyPaginatedList and make Rate Limited Calls like this.

MyPaginatedList resultData = new Library().fetchData();
while(true) {
  for(Data d: resultData.getData()) // loop over the list exposed by MyPaginatedlist
  ...
  }
  RateLimiter.acquire(); // use guava rate limiter, would block till a token is available
  resultData = resultData.getDataList();
  if(resultData.getData().isempty()) {
    break;
  }
}

Edit:-

3 straightforward approaches come to my mind -

  The one described above. Where the PaginatedList would expose a way to fetch next pages (batch of elements or List<>)
  Let the Library expose 2 API's -

  PaginatedList fetchData() -> client would call this one initially
  PaginatedList fetchNextPage(PaginatedList) -> client would call this
  for sub-sequent pages
  This one is slightly modified version of approach 2. Let library expose a modified fetchData()

  PaginatedList fetchData(PaginatedList list) -> initially client
  would need to create a new PaginatedList(), which would initialize
  it's state like pageToProcess = 0; This API kind of takes in the
  metadata associated with the service call to identify which page to
  get next

Any more suggestions or variations would be appreciated!


texts: Loading Files from a Directory in Haskell

texts:
I'm a very new Haskell programmer, and I've written the following code for loading TSV files. I think it can be improved, but I'm not sure how.

I feel like the giant "do" block in loadData is inelegant, and that there's likely a better way to approach this.
I think I'm trying to avoid the IO monad because I'm not sure how to work with it, but that there's probably a better way to handle mapping parseTSV over the contents of the files.

One note: I'm not super concerned about performance - this will run once at the beginning of my program. I want to load in all the files entirely to build a composite data structure from their contents.

module LanguageMachine (loadData) where

import System.Directory (listDirectory)
import Data.List ((\\), elemIndex)
import Data.Maybe (mapMaybe)

parseTsv :: String -> [(String, Int)]
parseTsv contents = mapMaybe parseLine (lines contents)

parseLine :: String -> Maybe (String, Int)
parseLine line =
    case elemIndex '\t' line of
        Just i ->
            let
                (word, count) = splitAt i line
            in
                Just (word, read count :: Int)
        Nothing -> Nothing

loadData :: FilePath -> [FilePath] -> IO [(String, [(String, Int)])]
loadData path exclude = do
    files <- listDirectory path
    let filtered = files \\ exclude
    let prefixed = map ((path ++ "/") ++) filtered
    contents <- traverse readFile prefixed
    let results = map parseTsv contents
    return $ zip filtered results

The files look like this, which are two-value TSV lines of a word and then the number of occurrences of that word:

ARIA    4308
ORE 4208

Thank you!


texts: Building tree structure based on flat objects - second follow up

texts:
This is a follow up on this question which is a follow up on this question
This follow up is created, because the class in question contained something, which didn't do what it should do.

Based on the suggestion for the RemoveRootArchiveDefinitions() method of the first follow up I have renamed the name of the return variable to remainingEntries and renamed the method to GetNonRootArchiveDefinitions().

Please review the class in question, if you find anything, which should be changed.

public class ArchiveBuilder
{
    public static IEnumerable<ArchiveTreeEntry> Build(IEnumerable<ArchiveDefinition> archiveDefinitions)
    {
        IEnumerable<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

        if (archiveDefinitions != null && archiveDefinitions.Count() > 0)
        {
            IEnumerable<ArchiveDefinition> localEntries = new List<ArchiveDefinition>(archiveDefinitions);

            rootArchiveTreeEntries = CreateRootEntries(localEntries);
            localEntries = GetNonRootArchiveDefinitions(localEntries);

            foreach (ArchiveTreeEntry rootEntry in rootArchiveTreeEntries)
            {
                HandleEntriesForParent(localEntries, rootEntry);
            }
        }

        return rootArchiveTreeEntries;
    }

    private static IEnumerable<ArchiveTreeEntry> CreateRootEntries(
        IEnumerable<ArchiveDefinition> archiveDefinitions)
    {
        List<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

        rootArchiveTreeEntries.AddRange(
            archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive)
                .Select(d => new ArchiveTreeEntry(d)));

        return rootArchiveTreeEntries;
    }

    private static IEnumerable<ArchiveDefinition> GetNonRootArchiveDefinitions(
        IEnumerable<ArchiveDefinition> archiveDefinitions)
    {
        IEnumerable<ArchiveDefinition> remainingEntries =
                archiveDefinitions.Except(
                archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive));

        return remainingEntries;
    }

    private static void HandleEntriesForParent(
        IEnumerable<ArchiveDefinition> archiveDefinitions,
        ArchiveTreeEntry parent)
    {
        if (archiveDefinitions.Count() > 0)
        {
            IEnumerable<ArchiveDefinition> children = GetChildren(archiveDefinitions, parent.Id);

            AddChildrenToParent(parent, children);

            archiveDefinitions = GetParentlessEntries(archiveDefinitions, parent.Id);

            foreach (ArchiveTreeEntry nextParent in parent.Children)
            {
                HandleEntriesForParent(archiveDefinitions, nextParent);
            }
        }
    }

    private static IEnumerable<ArchiveDefinition> GetChildren(
        IEnumerable<ArchiveDefinition> archiveDefinitions, string parentId)
    {
        return archiveDefinitions.Where(e => e.ParentId == parentId);
    }

    private static void AddChildrenToParent(ArchiveTreeEntry parent,
        IEnumerable<ArchiveDefinition> children)
    {
        parent.AddChildRange(children.Select(x => new ArchiveTreeEntry(x)));
    }

    private static IEnumerable<ArchiveDefinition> GetParentlessEntries(
        IEnumerable<ArchiveDefinition> archiveDefinitions,
        string parentId)
    {
        return archiveDefinitions.Where(e => e.ParentId != parentId);
    }

}

Regarding Any() and Count() as pointed out in the last follow up:

As long as the underlying object is a ICollection or ICollection<T> the Count() method returns the Count property of the underlying object. Which in turn just returns an internal counter of the items contained in the collection.

See: this question and this question


texts: Formatting a date range, with shortening if the interval falls entirely within a calendar month

texts:
The graphic guy wants to display dates like

16. February
17. - 24. February, or
25. February - 02. March.

Here is my solution:

$d1 = new \DateTime('2015-02-06');
$d2 = new \DateTime('2015-03-02');

$dateDiff = $d1->diff($d2);
if (intval($dateDiff->d) != 0) {
    $d = $d1->format('d.') . ' ' . ($d1->format('m') != $d2->format('m') ? $d1->format('F') : '') . ' - ' . $d2->format('d. F');
} else {
    $d = $d1->format('d. F');
}

I'm wondering if the this comparison:

$d1->format('m') != $d2->format('m')

is the best way to check whether $d1 and $d2 are in the same or different months.

($dateDiff = $d1->diff($d2) tells me that the two dates are 24 days apart, but it doesn't tell me if they are in different calendar months.)


texts: Chain of responsibility and handlers dependent on each other

texts:
I'm importing data from file to many tables in database. It may look like this:

First Name, Last Name, Meeting
John, Doe, 2020-04-24 08:00:00

Some fields like "First Name" and "Last Name" are being saved in one table and other fields like "Meeting" are being saved in different tables. There are a lot of more fields and a lot of more rows in my case.

I create handler for each table and put it in a handler chain to reduce amount of code. Each handler knows which fields it can handle. My base handler class looks like this:

abstract class TableHandler
{
    protected $nextHandler;

    abstract public function isFieldSupported(string $field): bool;
    abstract public function handle(string $fieldName, string $fieldValue);

    public function next(TableHandler $nextHandler): TableHandler
    {
        $this->nextHandler = $nextHandler;
    }

    public function handleField(string $fieldName, string $fieldValue)
    {
        $this->handle($fieldName, $fieldValue);

        if ($this->nextHandler()) {
            $this->nextHandler->handleField($fieldName, $fieldValue);
        }
    }

    public function reset(): void
    {
        $this->resetHandler();

        if ($this->nextHandler()) {
            $this->nextHandler->reset();
        }
    }

    private function nextHandler(): bool
    {
        return $this->nextHandler !== null;
    }
}

I use my handler chain this way:

$table1->next($table2)
    ->next($table3);

foreach ($data as $row) {
    foreach ($headers as $index => $header) {
        $table1->handleField($header, $row[$index]);
    }

    $id = $table1->save();
    $table2->save($id);
    $table3->save($id);

    $table1->reset();
}

As you can see I was able to handle fields and reset all handlers by using only first handler. Chain does the rest of the job. The problem is that I don't know how can I improve saving data. When I insert record in first table I get its ID. I need to pass this ID to further handlers because rows that I insert in those tables are related to row from first table so ID is needed. Bacause of it I need to save data separately. I would like to avoid it. Is it possible?


texts:
This program should generate NxN boards where there are words going from left to right and words going from top to bottom. Words are valid if they appear in the scrabble dictionary.

For example, a valid 3x3 board would be:

ACT
TOO
EGO

as it contains ACT, TOO and EGO going across, and ATE, COG and TOO going down.

import itertools

N = 3

f = open("scrabble.txt")
words = [line.strip().upper() for line in f if len(line.strip()) == N]
words = sorted(words)
f.close()

def tuple_to_grid(t):
    for i in t:
        print(i)
    print()

found = []

for i in itertools.product(words, repeat = N):
    for j in range(N):
        down = "".join([k[j] for k in i])
        if down not in words:
            break
    else:
        tuple_to_grid(i)

N can be changed to change the size of the board. It can generate fine for 2x2 and 3x3 boards, but when it comes to 4x4 it takes hours to generate single boards.

Please comment on how to make this faster.


texts:
I created a queue in which we can perform Enqueue, Dequeue and Traversing in Scala.

class Queue[+A](list:List[A]) {
  def enqueue[B>:A](x:B):Queue[B]= new Queue[B](list :+ x)
  def dequeue[B>:A]:Queue[B] = new Queue[B](list.tail)
  def head = list.head
  def tail = list.tail
}

Please review this code and make suggestions.


texts: Analyzing the U.S. Births dataset in Python

texts:
I'm a Data Science newbie and currently looking to improve my code. I was trying to calculate the total number of the following:

The total number of births on each month
The total number of births on each day of the week

Sample dataset from CSV:

year, month, date_of_month, day_of_week, births
1994, 1,     1,             6,           8096
1994, 1,     2,             7,           7772
1994, 1,     3,             1,           10142
1994, 1,     4,             2,           11248
1994, 1,     5,             3,           11053
...

It led me into this implementation:

def weekly_births(lst):
    mon = birth_counter(lst, 3, 1, 4)
    tue = birth_counter(lst, 3, 2, 4)
    wed = birth_counter(lst, 3, 3, 4)
    thu = birth_counter(lst, 3, 4, 4)
    fri = birth_counter(lst, 3, 5, 4)
    sat = birth_counter(lst, 3, 6, 4)
    sun = birth_counter(lst, 3, 7, 4)

    births_per_week = {
        1: mon,
        2: tue,
        3: wed,
        4: thu,
        5: fri,
        6: sat,
        7: sun
    }

    return births_per_week

def monthly_births(lst):

    jan_births = birth_counter(lst, 1, 1, 4)
    feb_births = birth_counter(lst, 1, 2, 4)
    mar_births = birth_counter(lst, 1, 3, 4)
    apr_births = birth_counter(lst, 1, 4, 4)
    may_births = birth_counter(lst, 1, 5, 4)
    jun_births = birth_counter(lst, 1, 6, 4)
    jul_births = birth_counter(lst, 1, 7, 4)
    aug_births = birth_counter(lst, 1, 8, 4)
    sep_births = birth_counter(lst, 1, 9, 4)
    oct_births = birth_counter(lst, 1, 10, 4)
    nov_births = birth_counter(lst, 1, 11, 4)
    dec_births = birth_counter(lst, 1, 12, 4)

    births_per_month = {
        1: jan_births,
        2: feb_births,
        3: mar_births,
        4: apr_births,
        5: may_births,
        6: jun_births,
        7: jul_births,
        8: aug_births,
        9: sep_births,
        10: oct_births,
        11: nov_births,
        12: dec_births
    }

    return births_per_month

The birth_counter function:

def birth_counter(lst, index, head, tail):
    sum = 0
    for each in lst:
        if each[index] == head:
            sum = sum + each[tail]
    return sum

The parameters:

lst - The list of dataset
index - The lst's index
head - Will be compared from lst's index
tail - The target data that needs to be computed

Example usage:

[lst]  [0]  [1] [2] [3]  [4]
lst = [1994, 1,  1,  6, 8096]...
sample_births = birth_counter(lst, 1, 1, 4)

    if sample_births[1] == 1 then
        extract index[4] #8096

Questions regarding weekly_births and monthly_births:

If you notice, I manually entered the number of weeks and months then calculated the total births on each. Is there a way to iterate over weeks and months to avoid a lengthy piece of code?


texts: Android TCP server that maps data to an object and sends it to a service

texts:
This is a code for an android thread. This is a tcp server and gets data from socket, maps it to an object and sends that object back to the main service. If there is anything I'm doing wrong or if something can be done better, I would really appreciate comments.

public class SocketManager extends Thread {

    Handler mHandlerThread;
    private final int MAX_MESSAGE_LENGTH = 2048;
    private final int PORT = 2500;
    private ServerSocket serverSocket = null;
    private Socket socket = null;
    private DataInputStream in = null;
    private DataOutputStream out = null;
    private GPSFields gps;
    private ObjectMapper mObjectMapper;
    private final String APPNAME = "My App";

    public SocketManager(Handler mHandlerThread) {
        this.mHandlerThread = mHandlerThread;
    }

    @Override
    public void run() {

        int messageLength = 0;
        gps = new GPSFields();
        byte buffer[] = new byte[MAX_MESSAGE_LENGTH];
        mObjectMapper = new ObjectMapper();
        mObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        try {
            openSocket();
        } catch(Exception e) {
            Log.d(APPNAME, e.toString());
        }

        while(true) {
            try {
                if(socket.isClosed()) {
                    openSocket();
                }
                else {
                    messageLength = in.readShort();
                    if (messageLength > 0 && messageLength < MAX_MESSAGE_LENGTH) {
                        in.read(buffer, 0, messageLength);
                        gps = mObjectMapper.readValue(new String(buffer), GPSFields.class);
                        if (gps != null) {
                            out.write(1);
                            Message message = new Message();
                            message.obj = gps;
                            mHandlerThread.sendMessage(message);
                            Log.d(APPNAME, "Received Latitude: " + gps.getLatitude() + " Longitude: " + gps.getLongitude());
                        } else {
                            out.write(0);
                        }
                    } else {
                        out.write(0);
                    }
                }
            } catch (Exception e) {
                closeSocket();
                Log.d(APPNAME, e.toString());
            }
        }
    }

    private void closeSocket() {
        try {
            socket.close();
            serverSocket.close();
        }catch (Exception e){
            Log.d(APPNAME, e.toString());
        }
    }

    private void openSocket() {
        try {
            serverSocket = new ServerSocket(PORT);
            socket = new Socket();
            socket = serverSocket.accept();
            in = new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
        }catch (Exception e){
            Log.d(APPNAME, e.toString());
        }
    }
}


texts: How can I improve this Caesar encryption?

texts:
I have the following method which encrypts a english text, given the plain text and the desired key:

/// <summary>
/// Encrypts english plain text using user defined key. Range for the key is from -25 to 25.
/// </summary>
/// <param name="plainText"></param>
/// <param name="keyValue"></param>
/// <returns></returns>
public static string encryptTextEng(String plainText,int keyValue)
{
    string encText = "";
    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

    for (int i = 0; i < plainText.Length; i++)
    {
        if (plainText[i].ToString() == " ")
        {
            encText += " ";
        }

        for (int j = 0; j < alphabet.Length; j++)
        {
            if (String.Equals(alphabet[j].ToString(), plainText[i].ToString(), StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    encText += alphabet[j + keyValue];
                }
                catch (Exception ex)
                {
                    if (j + keyValue > 26)
                    {
                        encText += alphabet[j + keyValue - 26];
                    }
                    else if (j + keyValue < 0)
                    {
                        encText += alphabet[j + keyValue + 26];
                    }
                }
            }
        }
    }

    return encText;
}

What are good programming practices I am missing here? Also I am not sure about the try/catch part I guess there are better ways to do it? Would it be a good idea to add a switch case which checks if the char it is currently reading is a punctuation character?


texts: Updating single view on change of a model in backbone

texts:
The setup of Backbone:

1 Collection,
3 Models,
1 View for the collection,
1 View per Model.

HTML:

Template:

Backbone JS:

Book    =   Backbone.Model.extend({
            defaults:{
                name    :   "No Name",
                author  :   "No Name",
                likes   :   0
            }

BookListView    =   Backbone.View.extend({
                        collection  :   BookList,
                        initialize  :   function(collection){
                            this.collection = collection;
                            this.render();
                        },
                        render      :   function(){
                            this.collection.each(function(model){
                            var pustakView = new BookView({model: model});
                            pustakView.render();
                            });
                        }
});

BookView    =   Backbone.View.extend({
    model       : Book,
    initialize  : function(){},
    events      : {"click a.item": "clicked"},
    template    : Handlebars.compile($('#item-template').html()),

    clicked     : function(e){
                    e.preventDefault();
                    var likes_count =    this.model.get("likes");
                    this.model.set({likes:++likes_count});
                    this.renderOne();
    },

    renderOne   : function(){
                    var output=this.template({'book':this.model.toJSON()});
                    $(this.el).html(output);
    },
    render      : function(){
                    var output = this.template({'book':this.model.toJSON()});
                    $(this.el).append(output);
                    $('#showit').append($(this.el));
     }
});

var book1   =   new Book({name:'Awesome Book1',author:"John",likes:10});
var book2   =   new Book({name:'Awesome Book2',author:"Dave",likes:20});
var book3   =   new Book({name:'Awesome Book3',author:"Bill",likes:30});

BookList    =   Backbone.Collection.extend({model:Book});
var myBookCollection    =   new BookList([book1,book2,book3]);
myBookList  =   new BookListView(myBookCollection);

So here is a snippet of what it generates on page load:

       Awesome Book1

       Liked:10

...
...

I am a newbie into world of backbone and trying to implement the basics to apply it into my site. I have referred this site for the above implementation. (Well, not exactly as I have customized it for my needs).

The feature I have been trying to implement is that multiple models with same template will load in 1 Collection, clicking on any element in the rendered view of that model has to give me access to that model so that I can re-render the view of the clicked model only.

The above example does the same where in clicking a hyperlink updates the counter called 'likes' and updates the corresponding model view only. As it can be noticed I have not specified an 'el' attribute for the view of each model and so it will be a 'div'.

My Question is whether this method is an efficient method of updating individual views (when model attributes change due to events) or are there any better methods than this? Also I am not sure if having a view for each loaded model will not cause any memory issues (asuuming I have an infinite scroll implemented which keeps on loading the list of Books)

If the above implementation is good enough, I hope it can help other backbone newbies to get up and running with re-rendering model view when model attributes change.


texts: Euclidian distance - optimization and casting

texts:
I'm trying to optimize a simple Euclidian distance function in C. It's for a DLL, and calculates distances from one point to many. I have:

Version 1:

int CalcDistance (int y1, int x1, int *y2, int *x2, int nb , int *distances)
{
    double dx,dy = 0;

    for (int i = 0;i<nb;i++)
    {
        dx = x2[i] - x1;
        dy = y2[i] - y1;

        distances[i]=(int)sqrt((dx*dx)+(dy*dy));
    }

    return nb;
}

Version 2:

int CalcDistance (int y1, int x1, int *y2, int *x2, int nb , int *distance)
{
    int dx,dy =0;

    for (int i = 0;i<nb;i++)
    {
        dx = x2[i] - x1;
        dy = y2[i] - y1;

        distances[i]=(int)sqrt((double)(dx*dx)+(dy*dy));
    }

    return nb;
}

Essentially, I don't need extra high precision, so that's why I'm cutting down to ints, not doubles. For my specific use case, the final distance will not be larger than what an int (Int32) can hold.

I was taken aback by how slow version 2 was. I figured that in Version 1 calculating dx and dy would implicitly cast to double twice, whereas in version 2 I'm just explicitly casting once. What's happening? And ultimately, what could be even faster?

(And I tried _hypot, which was oddly the slowest of all...)


texts: Hacker rank 30 days of code Maximum Sum of Hourglass

texts:
I came up with this code as a solution to a contest question. The original question can be viewed here for attribution sake: Hackerrank 2d array problem

Sample input is like this:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

Sample output is like this:

19

My actual code input from the submission website is as follows:

import math
import os
import random
import re
import sys

if __name__ == "__main__":
    arr = []

    for _ in range(6):
        arr.append(list(map(int, input().rstrip().split())))

total = 0
max_total = -1073741824

for i in range(len(arr)):
    for j in range(len(arr[i])):
        if (j+2 < 6) and (i+2 < 6):
            total = arr[i][j] + arr[i][j+1] + arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
            if max_total < total:

                max_total = total
print(max_total)

There were several code listings on a different StackOverflow posting C++/Ruby solutions to 2d array problem. Being an absolute beginner in Python, I am still coming up to speed with advanced concepts in Python so my solution presented here is "un-Pythonic" and am sure not at all times optimized. How can I rewrite this code to be more "Pythonic"? I understand list comprehensions, but how can they be applied to multi-dimensional arrays like this case? Also, would rewriting the code to be Pythonic actually optimize the solution?


texts: Checking whether one string contains all the characters of another string

texts:
I am working on a CodeWars kata that requires the code to run under a certain time limit. This code passes all the tests; but, it doesn't run fast enough. I don't know what else I can trim down or change.

Addition: I tried looking up a String.split-join solution. But, that won't work. The split will replace every occurrence of a character. I need to check for only one at a time. I even tried using the split-join with RegEx that only took one occurrence of a character. But, that was just adding more code on top of what I already had.

Putting the strings into arrays is too slow.

Someone suggested that I try a different way of looking at the problem by rearranging the characters. Maybe I need to sort them which will group the duplicate characters together.

Kata description:

  If all the characters in the second string are found in the first string, then return true; otherwise, return false.

I included some test cases at the end.

function scramble(str1, str2) {

var str2Length = str2.length;
var str11 = "";

for(i = 0; i < str2Length; i++){
        str11 = str1.replace(str2[i], '');
        if(str11 === str1){
            return false;
        }
        str1 = str11;
}
// If all the characters have been found in the second string, then return true.
    return true;

}

scramble('rkqodlw','world');
console.log("should be true");

scramble('cedewaraaossoqqyt','codewars');
console.log("should be true");

scramble('katas','steak');
console.log("should be false");

scramble('scriptjava','javascript');
console.log("should be true");

scramble('scriptingjava','javascript');
console.log("should be true");

scramble('jscripts','javascript');
console.log("should be false");

scramble('aabbcamaomsccdd','commas');
console.log("should be true");


texts: Optimize this loop to access if a value was in previous line with one condition

texts:
I successfully create a for loop to generate a new column in my data. This column access if there is retention of the customer on a Radio station.

The data looks like this:

ID     Date       Time      Station
1    10-06-2017   8:45      SuperRadio
1    10-06-2017   8:56      SuperRadio
1    10-06-2017   9:10      AmazingRadio
1    10-06-2017   10:23     SuperRadio

AS you can see a new line is created when a new program start on the radio and the listener is still listening. What I want to do is to access the events of leaving and return. Like at the fourth line here. So I want to add the following:

ID     Date       Time      Station   retour   quit
1    10-06-2017   8:45      SuperRadio       0        0
1    10-06-2017   8:56      SuperRadio       0        0
1    10-06-2017   9:10      AmazingRadio     0        1
1    10-06-2017   10:23     SuperRadio       1        1

I have succeed doing that with a for loop but it is slow and not very pretty.

result = []

### Subsetting on date
for date in set(DF.loc[:,'Date']):
    Sub = DF.loc[ DF.Date == date,:]

    ### Subsetting on ID
    for mem in set(DF.loc[:,'ID']):

        Subb = Sub.loc[Sub.ID == mem,:]
        ### Creating a Station +1 column
        sta1 = Subb.loc[:,'Station'].shift(1)
        Subb.loc[:,'Sta+1'] = sta1
        ### Taking out Nan and Add Not Listening
        Subb.loc[:,'Sta+1'] = Subb['Sta+1'].fillna('Not listening')
        ### Creating the quit column
        q = Subb['Sta+1'] != Subb['Station']
        Subb.loc[:,'quit'] = q

        ### Looping over the Subset to get the return column
        for row in Subb.index[1:,]:
            row_last = row -1
            if Subb.loc[row, 'quit'] == True:
                Stat= Subb.loc[row,'Station']
                if Stat in list(Subb.loc[:row_last,'Station']):
                 ### If the row quit is true and the station is present in the previous row
                 ### Return is then True
                     Subb.loc[row,'retour'] = True
                else:
                    Subb.loc[row,'retour'] = False
            else:
                ### IF not then no Return
                Subb.loc[row,'retour'] = False

        result.append(Subb)

I transform into Dataframe for analysis

dff = pd.concat(result)
dff['quit'] = dff['quit'].astype(int)
dff['retour'] = dff['retour'].replace(np.nan,'Not Listening')
dff['retour'] = dff['retour'].replace([True,False],[1,0])

Note that my data is large and I have multiple ID and Date.


texts:
On scroll, I am adding a class (current) to particular elements.

The code looks like it can be made better. For example, it seems like I am reusing the same things over and over again (i.e. the nth-child(1), nth-child(2), etc.).

I appreciate any and all comments and advice.

 function isScrolledIntoView(elem) {
    if (elem.length > 0) {
      var docViewTop = $(window).scrollTop();
      var docViewBottom = docViewTop + $(window).height();
      var elemTop = $(elem).offset().top;
      return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
    }
  }

   $(document).scroll(function () { // Measure scroll To Top
      // @TODO Fix it so that there is only 1 if block
      if (isScrolledIntoView($('.section .main-content:nth-child(1)')) === true) {
        $('.events-widget-menu li').removeClass('current');
        $('.events-widget-menu li:nth-child(1)').addClass('current');
      }

      if (isScrolledIntoView($('.section .main-content:nth-child(2)')) === true) {
        $('.events-widget-menu li').removeClass('current');
        $('.events-widget-menu li:nth-child(2)').addClass('current');
      }

      if (isScrolledIntoView($('.section .main-content:nth-child(3)')) === true) {
        $('.events-widget-menu li').removeClass('current');
        $('.events-widget-menu li:nth-child(3)').addClass('current');
      }

      if (isScrolledIntoView($('.section .main-content:nth-child(4)')) === true) {
        $('.events-widget-menu li').removeClass('current');
        $('.events-widget-menu li:nth-child(4)').addClass('current');
      }
    });


texts: Proxy test class approach to allow covering legacy code with unit tests

texts:
There is huge legacy class MyService in which several new business cases need to be implemented. Unfortunately we are not allowed to touch existing legacy code within _legacyMethod and need to build a new condition on top of it. However I'd like to have a new code covered with unit tests (using NUnit)

public class MyService
{
    public bool Execute()
    {
        return _newMethod() && _legacyMethod();
    }

    protected virtual bool _newMethod()
    {
        // some business logics

        return true;
    }

    protected virtual bool _legacyMethod()
    {
        // hundreds of lines of code

        return false;
    }
}

So primarily my goals were:

Leave legacy method protected
Cover new methods with unit tests
Cover integration of new methods with legacy code

To achieve this I built a proxy within test class:

using NUnit.Framework;

[TestFixture]
public class MyServiceTests
{
    private MyServiceProxy _sut;

    [SetUp]
    public void SetUp()
    {
        _sut = new MyServiceProxy();
    }

    [TearDown]
    public void TearDown()
    {
        _sut = null;
    }

    [Test]
    [TestCase(true, true, true)]
    [TestCase(false, true, false)]
    [TestCase(true, false, false)]
    [TestCase(false, false, false)]
    public void Execute_ReturnsExpected(bool newMethodStub, bool legacyMethodStub, bool expectedResult)
    {
        _sut.LegacyMethodStub = legacyMethodStub;
        _sut.NewMethodStub = newMethodStub;

        var result = _sut.Execute();

        Assert.AreEqual(expectedResult, result);
    }

    [Test]
    public void NewMethod_ReturnsTrue()
    {
        var result = _sut.NewMethodProxy();

        Assert.That(result, Is.True);
    }

    public class MyServiceProxy : MyService
    {
        public virtual bool NewMethodProxy()
        {
            return base._newMethod();
        }

        public bool? NewMethodStub { get; set; }

        public bool? LegacyMethodStub { get; set; }

        protected override bool _newMethod()
        {
            if (NewMethodStub.HasValue)
            {
                return NewMethodStub.Value;
            }
            return base._newMethod();
        }

        protected override bool _legacyMethod()
        {
            if (LegacyMethodStub.HasValue)
            {
                return LegacyMethodStub.Value;
            }

            return base._legacyMethod();
        }
    }
}

In such a way I managed to have a separate set of tests for new method itself, and another one - for integration old-new logics within Execute method.
Could you advice please if this approach is applicable or can be simplified/improved somehow?


texts: Finding and returning a loopy path in a directed graph

texts:
I wrote a function in Scala to find out and return a loopy path in a directed graph.

One of the arguments is a graph presented in an adjacent list, and the other is a start node. It returns a pair including a loopy path by a list of nodes.

I wonder if there are more elegant ways of doing this.

  def GetACycle(start: String, maps: Map[String, List[String]]): (Boolean, List[String]) = {
    def explore(node: String, visits: List[String]): (Boolean, List[String]) = {
      if (visits.contains(node)) (true, (visits.+:(node)).reverse)
      else {
        if (maps(node).isEmpty) (false, List())
        else {
          val id = maps(node).indexWhere(x => explore(x, visits.+:(node))._1)
          if (id.!=(-1))
            explore(maps(node)(id), visits.+:(node))
          else
            (false, List())
        }
      }
    }
    explore(start, List())
  }

I felt I had to use the indexWhere in this situation, but I suppose it would have other ways to do that.


texts: Kohana newbie: setting a layout view and variables for layout in before()

texts:
The same view (a layout) used for all pages in Kohana3.3 project. That's why it could be placed in before() method instead of every action. Right?

Is there any better way to optimize the code below so you shouldn't use so many $this->? Are there any other improvements of this code so it looks really good?

public function before()
{   //shows layout for all pages
    $this->view = View::factory('layout');
    $this->view->left_column='pass this string to layout';
}

public function action_index()
{   //index section on the page
    $this->view->content = View::factory('index');
    $this->view->content->text = 'some index text';
    $this->response->body($this->view);
}

public function action_about()
{
    //about section on the page
    $this->view->content = View::factory('about');
    $this->view->content->text = 'some about text';
    $this->response->body($this->view);
}


texts: Counting the number of click on the entire page

texts:
In an interview I was giving the following problem:

  Count the number of click on on the entire page.

Can you think of a better way to do this?

let counter = 0;
document.addEventListener('click', clickCounter);

function clickCounter() {
  counter++;
  console.log(counter);
}


texts:
Here is some code to insert a new line escape sequence after a certain number of characters (for fixed width displays)

    private string spliceNoteText(string text)
    {
        StringBuilder sb = new StringBuilder();

        int maxWidth = 70;
        int blockOfText;

        for (int i = 0; i <= text.Length; i += maxWidth)
        {
            if (i >= text.Length)
                continue;

            int charsRemaining = text.Length - i;

            if (charsRemaining <= maxWidth)
                blockOfText = charsRemaining;
            else
                blockOfText = maxWidth;

            sb.Append(text.Substring(i, blockOfText));
            sb.Append("\n");

        }
        return sb.ToString();
    }

It's is ugly and boring, can it be made prettier or more elegant?


texts:
Function : User enters a word in korean and the program translates (defines) it in english.

  What improvements can I make?

  Extra : What other challenges would you recommend that incorporates both JSON and python?

KoreanDictionary.py

import json
from difflib import get_close_matches

korean_data = json.load(open("korean_vocabulary.json"))

def my_translator(word):
    if word in korean_data.keys():
        return korean_data[word]
    elif len(get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)) > 0:
        word = get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)[0]
        return korean_data[word]
    else:
        return "Word does not exist."

if __name__ == '__main__':

    user_input = input("Define:")
    definition = str(my_translator(user_input)).replace('[','').replace(']','').replace("'",'')
    print(user_input + ": " + definition)

korean_vocabulary.json

{"안녕하세요": ["hello"],"죽어버려": ["GO DIE"],"상황": ["situation"],"어려워": ["hard; difficult"],
    "모르겠다": ["I don't know."],"조건": ["condition"],"정규직 직업": ["full-time job"],
    "탈락": ["eliminate; out"], "눈치": ["quick to catch; tactfulness"],"슬픈": ["sad"],
    "복잡한": ["complicated"],"완전": ["completely"],"반대": ["opposite"],"대박": ["jackpot; awesome"],
    "어꺠": ["shoulders"],"얼굴": ["face"]}


texts: Newton's method to solve cubic equations

texts:
I have used the Newton-Raphson method to solve Cubic equations of the form $$ax^3+bx^2+cx+d=0$$ by first iteratively finding one solution, and then reducing the polynomial to a quadratic $$a1*x^2+b1*x+c=0$$ and solving for it using the quadratic formula. It also gives the imaginary roots.

def deg3(a,b,c,d,g):  #using newton raphson method, I designed this to solve degree3 equations
    y=a*g**3+b*g**2+c*g+d
    return y
def solvedeg3equation():
    '''solves for cubic equations of the form ax^3+bx^2+cx+d=0 with the rough estimate of error within e'''
    import math
    e=float(input("e= "))
    a=float(input("a= "))
    b=float(input("b= "))
    c=float(input("c= "))
    d=float(input("d= "))
    count=1
    g=0.01
    while abs(deg3(a,b,c,d,g))>e and count<=100 and not d==0:
        count=count+1
        if 3*a*g**2+2*b*g+c==0:
            g=g+0.001
        g=g-deg3(a,b,c,d,g)/(3*a*g**2+2*b*g+c)

   if count<=100:
        if d==0:
            a1=a
            b1=b
            c1=c
            g=0
        else:
            c1=-d/g                                 #This is generation 3, which provides all three solutions, including imaginary solutions, if any.
            a1=a
            b1=(c1-c)/g                             #imagg=imaginary part of root, realg=real part
        if b1**2-4*a1*c1<0:
            realg=-b1/(2*a1)
            imagg=math.sqrt(4*a1*c1-(b1**2))/(2*a1)
            if a1>0:
                g2=str(realg)+'+'+str(imagg)+'i'
                g3=str(realg)+'-'+str(imagg)+'i'
            if a1<0:
                g2=str(realg)+'+'+str(-imagg)+'i'
                g3=str(realg)+'-'+str(-imagg)+'i'
        if abs(b1**2-4*a1*c1)<e:
            g2=-b1/(2*a1)
            g3=None
        if b1**2-4*a1*c1>e:
            g2=(-b1+math.sqrt(b1**2-4*a1*c1))/2*a1
            g3=(-b1-math.sqrt(b1**2-4*a1*c1))/2*a1
        print("Solved. The best guess is:",g,'and',g2,'and',g3)
        print("Iterations required: ",count)
    else:
        print("Maximum iterations exceeded ")
        print("Iterations: ",count,"Current guess: ",g)

I would like to know how I can make this code more efficient, both mathematically and structurally. Some places which could do with a more efficient piece of code, according to me, are:

To avoid crashing of the program when the derivative equals zero, I have used the provision of g+0.001, to avoid the case. Is there a better way to solve this problem? Both mathematical optimizations or structural (code-related) are welcome.
Reducing the number of conditional statements and elementary operations (like comparisons, assignments and arithmetic operations) to reduce the computation time
Improve the Newton-Raphson algorithm mathematically to reduce the number of iterations required (since 3-4 digit numbers require more than 100 iterations currently). I'm incorporating the provision of better guesses.

I am a beginner to Python (this is my second program) and programming in general, so please try to suggest as simple modifications as possible. Also, I would appreciate any tips on the general nature of my writing style.


texts: Efficiently creating a list of formatted hex values

texts:
My background is in C, and I'm finally learning this new-fangled "Python" that all the cool kids are talking about.

I want to create a list of formatted hexadecimal values like so:

['0x00','0x01','0x02','0x03' (...) '0xfe','0xff']

Please note that the leading zero's shouldn't be stripped. For example, I want 0x03, not 0x3.

My first successful attempt was this:

hexlist=list()
tempbytes = bytes(range(256))
for value in tempbytes:
    hexlist.append("0x" + tempbytes[value:value+1].hex())
del tempbytes

But, wow this is ugly.  Then I tried to make it more Pythonic ("Pythony"?) like so:

hexlist = ["0x"+bytes(range(256))[x:x+1].hex() for x in bytes(range(256))]

My thoughts:

OMG! That's harder to read, not easier!
Not only that, but I had to invoke range twice, which I assume is inefficient.
I bet there's a much better way that I haven't been exposed to yet...

My questions:

Is the second much less efficient?
Is there a better way to do this?
What's the best thing to do here in keeping with python style?


texts:
I need a function (I named it applyToEveryPair) that works on lists, e.g. [x0,x1,x2,x3,...], and uses a function
f:: (a,a) -> [(a,a)]. For every (distinct) pair (xi,xj), i/=j of the list
I want all lists where xi is replaced by yik and xj is replaced by yjk where xik is the output of f.

This visualizes input and output

[a0, a1 ,a2 ,a3 ]  -- input to applyToEveryPair
  |   |
  |   |
  v   v
  f(a0, a1) =[(b0,b1),(c0,c1)]
  |   |
  v   v
[b0, b1, a2, a3]  -- to be included in output
[c0, c1, a2, a3]  -- to be included in output
   ...            -- more output
      |      |    -- now combine (a3,a1)
       \    /
        \  /
         \/
         /\
        /  \
     f(a3, a1) =
     [(d3, d1)]
        \  /
         \/
         /\
        /  \
       /    \
[a0, d1 ,a2 ,d3 ]  -- to be included in output

A use case would be to input a matrix and compute all resulting matrices for every (pairwise) line swap (f swaps lines), or, in my case, all possible move in a solitaire game from one stack of cards to another.

Long story, short code; This is how I do it so far:

applyToEveryPair :: ((a,a) -> [(a,a)]) -> [a] -> [[a]]
applyToEveryPair f (xs) = do i<-[0..length xs - 1]
                             j<-[0..length xs - 1]
                             guard (i /= j)
                             (x',y') <- f (xs !! i, xs !! j)
                             return . setList i x' . setList j y' $ xs

-- | setList n x xs replaces the nth element in xs by x
setList :: Int -> a -> [a] -> [a]
setList = go 0 where
    go _ _ _ [] = []
    go i n x' (x:xs) | i == n    = x':xs
                     | otherwise = x:(go (i+1) n x' xs)

I think comonads are overkill here, and I have not understood Lenses (yet),
but have a vague feeling lenses apply here.

The solution I use feels not very haskellish. I want to know if this is a good way to write it, but especially the double use of setList looks terrible to me. How to speed up / beautify this code?


texts: Creating directory within Application Support, and preventing iCloud backup

texts:
I'm using react native to build an iOS app, but have little to no experience in obj C or iOS development. The app I'm building has a bunch of content files that aren't user specific, will be downloaded from some CDN, and will (mostly) be behind a paywall. As I understand it, the best place for this would be somewhere within Application Support (the Cache dir doesn't seem to fit the bill because this is more about allowing users to download content for offline use than caching per se. Also, I think there's no guarantees about the lifetime of files in the Cache dir(?).). Also, I want to make sure that those content files aren't backed up to iCloud or anywhere else; and that they're not accessible by the user or other apps.

I have two questions:

Does that placement for the content fit with iOS recommendations/best practices?
Because I have little obj c/iOS experience, I'd be super grateful if you lovely people could cast your eyes over the code and review it?

// *** blah.h
#import <React/RCTBridgeModule.h>

@interface Blah : NSObject <RCTBridgeModule>
@end

// *** blah.m
#import "Blah.h"

@implementation Blah

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(createAppDataPath:(NSString *)namespace findEventsWithResolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){

    NSUInteger length = [namespace length];

    if (length < 1) {
        reject(@"namespace_invalid", @"Namespace param should be non-empty string", nil);
        return;
    }

    // ref: https://stackoverflow.com/a/17430820/1937302

    @try {

        NSString *appSupportDir = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) lastObject];
        NSString *cacheDir = [appSupportDir stringByAppendingString: [NSString stringWithFormat:@"/%@", namespace]];

        // check for existence of directory:
        BOOL isDir;
        BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:cacheDir isDirectory:&isDir];

        if (!exists) {
            NSError *error = nil;
            // if not present, create it:
            BOOL result = [[NSFileManager defaultManager] createDirectoryAtPath:cacheDir withIntermediateDirectories:YES attributes:nil error:&error];
            if (!result) {
                reject(@"cant_create", @"Can't create directory", error);
                return;
            }
        } else if (!isDir) {
            reject(@"non_directory_path_exists", @"Path already exists as a non-directory", nil);
            return;
        }

        // now mark the directory as excluded from iCloud backups:
        NSURL *url = [NSURL fileURLWithPath:cacheDir];
        NSError *error = nil;
        BOOL result = [url setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&error];

        if (!result) {
            reject(@"cant_exclude_from_backups", @"Can't exclude from backups", error);
            return;
        }

        resolve(cacheDir);

    }
    @catch(NSException *exception) {
        // TODO: capture information from exception and pass to rejection?
        // ref: https://stackoverflow.com/questions/43561531/how-to-convert-an-exception-into-an-nserror-object\
        // ref: https://stackoverflow.com/a/4654759/1937302
        // ref: https://developer.apple.com/documentation/foundation/nsexception
        reject(@"exception", @"An exception has occurred", nil);
    }
}

@end


texts: Negation detection in sentiment analysis

texts:
This basic function to detect negation while performing sentiment analysis. So that not good kind of words can be considered a negative.

This code is working fine. Can someone help to improve it or find if any bug present?

def negate_sequence(self,text):
    """
    Detects negations and transforms negated words into "not_" form.
    """
    negation = False
    delims = "?.,!:;"
    result = []
#Here rather then applying split, we can directly feed our extracted symptoms list
    words = text.split()
    prev = None
    pprev = None
    for word in words:
        # stripped = word.strip(delchars)
        stripped = word.strip(delims).lower()
        negated = "not_" + stripped if negation else stripped
        result.append(negated)
        if prev:
            bigram = prev + " " + negated
            result.append(bigram)
            if pprev:
                trigram = pprev + " " + bigram
                result.append(trigram)
            pprev = prev
        prev = negated

        if any(neg in word for neg in ["not", "n't", "no"]):
            negation = not negation

        if any(c in word for c in delims):
            negation = False

    return result


texts:
Following the review of my old merge sort implementation here, it appears that the biggest improvement to make was to use iterators instead of copying the vectors. Having never used iterators before, I'd like a review of the new code following that review:

#include <iostream>
#include <vector>
#include <algorithm>

template<typename T>
void Merge(T, T, T, T);
template<typename T>
void MergeSort(T, T);

int main()
{
    // As last time, this is just test code and does not need to be reviewed, but
    // is included for completeness
    std::vector<int> a;
    for (int i = 0; i < 10; i++) {
        a.push_back(10.0 * rand() / RAND_MAX);
    }
    for (int i = 0; i < a.size(); i++) {
        std::cout << a[i] << " ";
    }
    std::cout << "\n";
    // Note this swap is now in place, previously it returned a new vector
    MergeSort(a.begin(), a.end());
    for (int i = 0; i < a.size(); i++) {
        std::cout << a[i] << " ";
    }
    std::cout << "\n";
}

template<typename T>
void Merge(T arr1Begin, T arr1End, T arr2Begin, T arr2End) {
    T i1 = arr1Begin;
    T i2 = arr2Begin;
    int i = 0;
    std::vector<int> res(arr2End - arr1Begin, 0);
    while (i1 < arr1End && i2 < arr2End) {
        if (*(i1) < *(i2)) {
            res[i++] = *(i1);
            std::advance(i1, 1);
        }
        else {
            res[i++] = *(i2);
            std::advance(i2, 1);
        }
    }
    while (i1 < arr1End) {
        res[i++] = *(i1);
        std::advance(i1, 1);
    }
    while (i2 < arr2End) {
        res[i++] = *(i2);
        std::advance(i2, 1);
    }
    std::copy(res.begin(), res.end(), arr1Begin);
}

template<typename T>
void MergeSort(T arrBegin, T arrEnd) {
    int size = arrEnd - arrBegin;
    if (size < 2) {
        return;
    }
    if (size == 2) {
        if (*arrBegin > *(arrEnd - 1)) {
            std::swap(*arrBegin, *(arrEnd - 1));
        }
        return;
    }
    MergeSort(arrBegin, arrBegin + size / 2);
    MergeSort(arrBegin + size / 2, arrEnd);
    return Merge(
        arrBegin, arrBegin + size / 2,
        arrBegin + size / 2, arrEnd
    );
}

My questions this time:

I'm dereferencing a lot of iterators in order to swap and assign values, is there a better way to be doing this?
Is this implementation better than my last implementation? I'm looking for answers that think about stability,
efficiency in terms of speed/memory, etc. (Possibly an obvious question)
Also, I know nothing about templates, is there anything more to it than adding the line template<typename T> then line before the function and then using T within it?
I can't figure out how to get rid of std::vector<int> res(arr2End - arr1Begin, 0);. Obviously this goes against the templating, how should I store the results while I'm doing the merge? (Edit: since looking back at the previous accepted answer, I figure I should create a new vector outside the original call to MergeSort (inside main) and pass the .begin() of that array as the destination, rather than defining a new array inside each Merge() call and using std::copy. Is this correct?)

Edit: Thanks to @ratchetfreak for pointing out a bug whereby I was overwriting elements of arr1 without storing the overwritten element elsewhere beforehand (essentially losing it).


texts:
I have written code to find a duplicate char from a string. Can the code be improved?

Input:

         Hello World

output :

         l =  3 its a dup

         o = 2 its a dup

My approach is

step 1: sort the string

step 2: remove all the whitespace

step 3: copy std::string to char [] and loop through the array until different char and count on every dup char if count is more than one its duplicate.

#include<iostream>
#include<algorithm>
#include<set>
#include<string>
#include<string.h>
#include<unistd.h>

void dupcheck(std::string usr)
{
        int count =1;
        char temp[1024]={0};
        strncpy(temp,usr.c_str(),sizeof(temp));
        for(int i=0;temp[i];++i)
        {
                for(int j=i+1;temp[j]==temp[i];++j)
                {
                        if(temp[i]==temp[j])
                                count++;
                                i=j;

                }
                        if(count>=2)
                        {
                                std::cout<<"dup char ="<<temp[i]<<" "<<count<<std::endl;
                                count =1;
                        }
        }

}

int main()
{
        std::string userInput;
        std::getline(std::cin,userInput);
        userInput.erase(std::remove(userInput.begin(), userInput.end(),' '), userInput.end());
        std::sort(userInput.begin(),userInput.end());
        std::cout<<userInput<<std::endl;
        if(!userInput.empty())
        dupcheck(userInput);
}

Please help me to improve the code if possible.


texts: check if two elements exist in array with older browser support

texts:
Currently I have this code

function foo(firstId, secondId){
    var boolOne = false;
    var boolTwo = false;

    for (var i = 0; i < arr.length; i++) {
        var current = arr[i];
        var id = current.id;

        if(firstId == id){
            boolOne = true;
        }

        if(secondId == id){
            boolTwo = true;
        }

        if(boolOne && boolTwo){
            break;
        }
    }

    if(boolOne && boolTwo){
        bar();
    } else {
        // throw error
    }
}

I want to check if two objects with the given parameter ids already exist in the array.

I put my code into one for-loop but I could also split the code into two loops and break on a match.

I know I could also use

var boolOne = arr.includes(item => item.id == firstId)

but I have to support the Internet Explorer 9+. Is there something that can be optimized?


texts: How can I get this R code to pass the "1 minute" test for this Project Euler question?

texts:
I am attempting to learn R programming by going through the questions in Project Euler.

The code below is my solution to problem 5 which asks for the smallest number that is evenly divisible by 1 through 20.

The code works but takes a very very long time.  Project Euler states that all of their problems should take a modern computer < 1 minute.

I know R is not as efficient as other languages but would it be possible to make my solution more efficient?

divis <- function(){
  count = 11
  tst <- 1:20 %% count # create vector of remainders
  while(sum(tst) != 0){ # test if all remainders are 0
    count <- count + 1
    tst <- count %% 1:20
    print(count)
    print(tst)
    }
  }
}