texts:
I made an implementation of the Bridge Pattern to handle ever-changing in crawler APIs that I'm using in my APP.

public interface CrawlerApi {
    // common constants to serveral implementations.
    String CHARSET = "ISO8859_1";
    int TIMEOUT = 20000;

    /**
     * Visit an url and return contents in String format.
     *
     * @param url
     * @return
     */
    String visit (String url);

    /**
     * Parse an Html code into an Navigable object that is provided by the API.
     *
     * @param htmlCode
     * @param documentType
     * @param <T>
     * @return
     */
    <T> T getDocument (String htmlCode, Class <T> documentType);

}

public class HtmlUnitCrawlerApi implements CrawlerApi {
    private WebClient webClient;

    public HtmlUnitCrawlerApi() {
        this.webClient = createWebClient();
    }

    @Override
    public String visit(String url) {
        Page p = null;
        try {
            p = webClient.getPage(url);
            return p.getWebResponse().getContentAsString(CHARSET);
        } catch (IOException e) {
            return "";
        }
    }

    @Override
    public <T> T getDocument(String htmlCode, Class<T> documentType) {
        throw new IllegalArgumentException("not implemented");
    }

    private WebClient createWebClient() {
        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_38);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        webClient.waitForBackgroundJavaScript(TIMEOUT);
        return webClient;
    }

}

public class JsoupCrawlerApi implements CrawlerApi {
    public static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36";

    @Override
    public String visit(String url) {
        return connect.apply(url).html();
    }

    //I made this static because of the peculiarity of api that is static and because I have to
    //set some config parameters.
    private static Function<String, Document> connect = url -> {
        try {
            return Jsoup.connect(url).timeout(TIMEOUT).userAgent(USER_AGENT).postDataCharset(CHARSET).get();
        } catch (IOException e) {
            return new Document("");
        }
    };

    private static Function<String, Document> parse = html -> {
        Document doc = Jsoup.parse(html);
        doc.charset(Charset.forName(CHARSET));
        return doc;
    };

    @Override
    public <T> T getDocument(String htmlCode, Class<T> type) {
        return (T) parse.apply(htmlCode);
    }

}

Usage:

public class ApiClientExample {
    private CrawlerApi crawlerApi;

    public ApiClientExample(CrawlerApi crawlerApi) {
        this.crawlerApi = crawlerApi;
    }

    public void visit (String url){
        crawlerApi.visit(url);
    }
}

Concerns:

Is this code clean enough?

Is there anything that can be improved?


texts:
Input

inputBlob - A PDF or ZIP file containing all the pages of many students' test papers.
extension - The file type ("pdf" or "zip").
numPages - The number of pages in a single test. For example, if numPages is 2 and the input file contains 10 pages, then we must have 5 students' tests.

Routine

Extract all the pages as images.
Upload the images to blob storage.
For each test (i.e. set of images), queue another routine to process it.

Code

I've created PdfPack and ZipPack classes (implementations not included here) which implement a common interface:

public interface IPack : IDisposable
{
  void Open(Stream stream);
  Stream GetPage(int index);
  int PageCount { get; }
}

Here's the function itself:

public static async Task Run(
  CloudBlockBlob inputBlob,
  string extension,
  int numPages,
  CloudBlobContainer container,
  IAsyncCollector<StitchRequest> queue)
{

  IPack pack = null;

  try {

    using (var inputStream = new MemoryStream()) {
      await inputBlob.DownloadToStreamAsync(inputStream);

      switch (extension.ToLowerInvariant()) {
        case "zip":
          pack = new ZipPack();
          break;
        case "pdf":
          pack = new PdfPack();
          break;
        default:
          throw new InvalidOperationException("Invalid file type.");
      }

      pack.Open(inputStream);

      if (pack.PageCount == 0) {
        throw new InvalidOperationException("No pages found.");
      }

      if (pack.PageCount % numPages != 0) {
        throw new InvalidOperationException($"Pages not a multiple of {numPages}.");
      }

      Guid groupId = default;

      for (var i = 0; i < pack.PageCount; i++) {

        if (i % numPages == 0) {
          groupId = Guid.NewGuid();
        }

        using (Stream imageStream = pack.GetPage(i)) {
          var imageBlob = container.GetBlockBlobReference($"{groupId}/{i % numPages}");
          await imageBlob.UploadFromStreamAsync(imageStream);
        }

        if (i % numPages == numPages - 1) {
          await queue.AddAsync(new StitchRequest {
            GroupId = groupId.ToString("D"),
            Count = numPages
          });
        }

      }
    }

    await inputBlob.DeleteAsync();

  } finally {
    pack?.Dispose();
  }

}


texts: RC4 in Sinclair BASIC; Working around one-indexed arrays

texts:
This is a program written in Sinclair BASIC (48 BASIC) for the Sinclair ZX Spectrum. It uses a hardcoded key (null right now) as seen in the bottom and outputs a stream of integers generated with RC4. Is there any way I can improve this particularly to get around 48 BASIC using one-indexed arrays (which makes RC4 hard to do without a lot of integer additions)?

  10 READ L
  20 DIM K(L)
  30 FOR I=1 TO L
  40 READ K(I)
  50 NEXT I
  60 DEF FN M(A,B)=A-INT (A/B)*B
  65 REM KSA
  70 DIM S(256)
  80 FOR I=0 TO 255
  90 LET S(I+1)=I
 100 NEXT I
 110 LET J=0
 120 FOR I=0 TO 255
 130 LET T=S(I+1)+K(FN M(I,L)+1)
 140 LET J=FN M(J+T,256)
 150 GO SUB 250
 160 NEXT I
 165 REM PRGA
 170 LET I=0
 180 LET J=0
 190 LET I=FN M(I+1, 256)
 200 LET J=FN M(J+S(I+1),256)
 210 GO SUB 250
 220 LET T=S(I+1)+S(J+1)
 230 PRINT S(FN M(T,256)+1)
 240 GO TO 190
 245 REM SWAP
 250 LET T=S(I+1)
 260 LET S(I+1)=S(J+1)
 270 LET S(J+1)=T
 280 RETURN
 285 REM KEY
 290 DATA 5
 300 DATA 0,0,0,0,0

KSA is the Key Scheduling Algorithm which initializes a 256-element array S with a permutation based on the key K (an array of size L). PRGA is the Pseudo-Random Generator Algorithm which prints a single integer to the screen at a time based on the contents of S.


texts:
I have this code which makes it easy to color a string in terminal but it is looking really repetitive. Is there a more idiomatic way of writing this? Also is there a functional way of doing this more effectively?

It seems really trivial, something like strings blue,red etc should point to a generic function, and when you invoke it, you should get the output depending on the caller's name!

But apparently such a thing doesn't exist unless I call it as arguments. But then I lose the flexibility of writing blue(bold(italics("Foo"))) which is really the best way to do this from an end user perspective.

Can I have a single function object in the memory and do this more effectively?

bcolors = {"BLUE": '\033[94m',
           "HIGH": '\033[93m',
           "OKAY": '\033[92m',
           "FAIL": '\033[91m',
           "BOLD": '\033[1m',
           "LINE": '\033[4m',
           "ENDC": '\033[0m'
           }

def blue(string):
    return bcolors["BLUE"] + string + bcolors["ENDC"]

def yellow(string):
    return bcolors["HIGH"] + string + bcolors["ENDC"]

def green(string):
    return bcolors["OKAY"] + string + bcolors["ENDC"]

def red(string):
    return bcolors["FAIL"] + string + bcolors["ENDC"]

def bold(string):
    return bcolors["BOLD"] + string + bcolors["ENDC"]

def line(string):
    return bcolors["LINE"] + string + bcolors["ENDC"]


texts:
I am not a expert on php html. I built a website 2 months ago, and realized I using lot of php query result on web. Is there any approach without while my query result on multiple times

<?php
$proc = "{call p_rpt_str310Web (?,?,?)}";
$params = array($PlanPkID,$bycatID,$ByDateVal);
$result = sqlsrv_query($conn, $proc, $params);
while ($row = sqlsrv_fetch_array($result))
{
?>

<?php echo $count; ?>
<?php echo $row['CusName']; ?>
<?php echo $row['CusCount']; ?>
<?php echo $row['WorkTime']; ?>

<?php } ?>

I have code like this in my html multiple times is there any way to do something like this


texts: Using singleton pattern for a MySQL connection

texts:
I'm new to web programming, and writing some web apis to enable users to sync their data between devices.

Is it okay to use singleton pattern to prevent reconnecting the MySQL database on every api call?

<?php

final class MySQLiConnection
{
    private static $connection = null;

    private function __construct() {}

    public static function getInstance() : MySQLiConnection
    {
        if ($connection == null || !$connection->ping())
        {
            $connection = new mysqli("localhost", "id", "password", "database");
        }

        return $connection;
    }

    public function execute(string $sql, iterable $params) : void
    {
        if ($statement = $connection->prepare($sql))
        {
            foreach ($params in $param)
            {
                if (is_int($param))
                {
                    $statement->bind_param("i", $param);
                }
                else if (is_double($param))
                {
                    $statement->bind_param("d", $param);
                }
                else if (is_string($param))
                {
                    $statement->bind_param("s", $param);
                }
            }

            $statement->execute();
            $statement->close();
        }
    }

    public function getResult(string $sql, iterable $params) : mysqli_result
    {
        if ($statement = $connection->prepare($sql))
        {
            foreach ($params in $param)
            {
                if (is_int($param))
                {
                    $statement->bind_param("i", $param);
                }
                else if (is_double($param))
                {
                    $statement->bind_param("d", $param);
                }
                else if (is_string($param))
                {
                    $statement->bind_param("s", $param);
                }
            }

            $statement->execute();

            $result = $statement->get_result();
            $statement->close();

            return $result;
        }
    }
}

// example
MySQLiConnection::getInstance()->execute("SELECT * FROM users WHERE forename = ? AND surname = ?", "ben", "dover");

?>


texts:
I'm writing an application called "Learn Morse" in Java using Maven. A Morse code translator is a part of this app. I created encode and decode methods to translate in both sides Morse code and I moved the HashMap to the properties file. I also created a helper method to get keys by value.

pl/hubot/dev/learn_morse/model/Encoder.java:

package pl.hubot.dev.learn_morse.model;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

public class Encoder {
    public final String encode(final String input)
            throws IOException,
            NoSuchFieldException {
        StringBuilder encoded = new StringBuilder();
        String lowerCaseInput = input.toLowerCase();
        for (int i = 0; i < lowerCaseInput.length(); i++) {
            char current = lowerCaseInput.charAt(i);
            encoded.append(getMorseCode().getOrDefault(
                    Character.toString(current), " "));
            encoded.append("   ");
        }
        return encoded.toString();
    }

    public final String decode(final String input)
            throws IOException,
            NoSuchFieldException {
        StringBuilder decoded = new StringBuilder();
        String lowerCaseInput = input.toLowerCase();
        for (String current : lowerCaseInput.split(" ")) {
            String key = getKeyByValue(getMorseCode(), current);
            if (key != null) {
                decoded.append(key);
            }
            decoded.append(" ");
        }
        return decoded.toString();
    }

    final Map<String, String> getMorseCode()
            throws IOException,
            NoSuchFieldException {
        Class<?> aClass = Encoder.class;
        ClassLoader classLoader = aClass.getClassLoader();
        String filename = "morse_code.properties";
        try (InputStream input = classLoader
                .getResourceAsStream(filename)) {
            if (input == null) {
                throw new FileNotFoundException(
                        "Sorry, unable to find "
                                + filename);
            }

            Properties properties = new Properties();
            properties.load(input);

            Map<String, String> translations = new HashMap<>();
            for (String key : properties.stringPropertyNames()) {
                String value = properties.getProperty(key);
                translations.put(key, value);
            }

            return translations;
        }
    }

    private <T, E> T getKeyByValue(final Map<T, E> map, final E value) {
        for (Map.Entry<T, E> entry : map.entrySet()) {
            if (Objects.equals(value, entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
}

resources/morse_code.properties:

a = ._
b = _...
c = _._.
d = _..
e = .
f = .._.
g = __.
h = ....
i = ..
j = .____
k = _._
l = ._..
m = __
n = _.
o = ___
p = .__.
q = __._
r = ._.
s = ...
t = _
u = .._
v = ..._
w = .__
x = _.._
y = _.__
z = __..
\u0105 = ._._
\u0107 = _._..
\u0119 = .._..
\u00E9 = .._..
ch = ____
\u0142 = ._.._
\u0144 = __.__
\u00F3 = ___.
\u015B = ..._...
\u017A = __.._
\u017C = __.._.
0 = _____
1 = .____
2 = ..___
3 = ...__
4 = ...._
5 = .....
6 = _....
7 = __...
8 = ___..
9 = ____.
. = ._._._
, = __..__
' = .____.
" = ._.._.
_ = ..__._
\: = ___...
; = _._._.
? = ..__..
\! = _._.__
- = _...._
+ = ._._.
/ = _.._.
( = _.__.
) = _.__._
\= = _..._
@ = .__._.


texts: Lowest Common Ancestor in Binary Tree (Iterative)

texts:
In the below code I've implemented a method to find the lowest common ancestor of a binary tree.
This is an iterative approach using this pseudocode.
Please suggest any improvements that can be made.
class Node:
    def __init__(self, data=None, left=None, right=None):
        self.data  = data
        self.left  = left
        self.right = right

def lowest_common_ancestor(root, node1, node2):
    parent = {root: None}
    stack = [root]

    while node1 not in parent or node2 not in parent:
        node = stack[-1]
        stack.pop()
        if node.left:
            parent[node.left] = node
            stack.append(node.left)
        if node.right:
            parent[node.right] = node
            stack.append(node.right)

    ancestors = set()
    while node1:
        ancestors.add(node1)
        node1 = parent[node1]
    while node2 not in ancestors:
        node2 = parent[node2]

    return node2.data

def main():
    '''
    Construct the below binary tree:

            30
           /  \
          /    \
         /      \
        11      29
       /  \    /  \
      8   12  25  14

    '''
    root = Node(30)
    root.left  = Node(11)
    root.right = Node(29)
    root.left.left  = Node(8)
    root.left.right = Node(12)
    root.right.left  = Node(25)
    root.right.right = Node(14)

    print(lowest_common_ancestor(root, root.left.left, root.left.right))       # 11
    print(lowest_common_ancestor(root, root.left.left, root.left))             # 11
    print(lowest_common_ancestor(root, root.left.left, root.right.right))      # 30

if __name__ == '__main__':
    main()


texts: Shortest distance between two words in the list

texts:
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

Example: given words = ["practice","makes","perfect","coding","makes"]

Input: word1 = "coding", word2 = "practice"
Output: 3

We assume word1 does not equal to word2, and both are in the list. List can be big as length 1000.

public int shortestDistance(String[]words, String word1, String word2){
 int temp = 0;

 if(word1.equals(words[words.length - 1])) && word2.equals(words[words.length - 2])||
    word2.equals(words[words.length - 1])) && word1.equals(words[words.length - 2]){
   return 1;
 }

 for(int i = 0; i < words.length; i++){
   if(word1.equals(words[I]) || word2.equals(words[I])) && (temp == 0){
     temp++
   }else if(word1.equals(words[I]) || word2.equals(words[I])){
     return temp;
   }else if(temp > 0){
     temp++;
   }
 }
    return temp;
}


texts: LINQ statements that aggregate sums from a List of objects

texts:
I'm packaging data for use in a JavaScript charting library that expects a somewhat odd structure of data in which there is an array of labels and an array of dataItems where each data item has a label and an array of data that corresponds to the array of labels.  I'm creating the dataItems from a list of objects in which each one has a year, week, location, program, and hours.  I'm creating the labels by getting distinct year/week combinations, and then aggregating the data to get distinct program/location items each with an array of the sums of the hours when grouped by year/week.

I've got these two LINQ statements that I'm using to create just the data items that I believe could be one, but I can't figure out how it would be possible.  I'm summing the hours for each Program and Location for each Year and Week, and then I need an array of the sums for each Location and Program.

var dataRows = from h in hours
               orderby h.Year, h.WeekOfYear, h.LocationName, h.ProgramName
               group h by new { h.Year, h.WeekOfYear, h.LocationName, h.ProgramName } into programLocationGroups
               select new { Location = programLocationGroups.Key.LocationName, Program = programLocationGroups.Key.ProgramName, Hours = programLocationGroups.Sum(p => p.Hours) };

chartData.DataRows = (from d in dataRows
                      group d by new { d.Program, d.Location } into programLocationSums
                      select new FindAllAnalyticsResponse.DataRow
                      {
                          Location = programLocationSums.Key.Location,
                          Program = programLocationSums.Key.Program,
                          Data = programLocationSums.Select(p => p.Hours).ToList()
                      }).ToList();

I'd love to see a more concise solution if it exists.  There's also room for improvement due to the fact that missing data will result in mismatched arrays (not possible in the current environment, but something I'm aware of).


texts:
I've written the following code in Ruby:

class Node
  attr_accessor :data, :left, :right

  def initialize(data=nil, left=nil, right=nil)
    @data  = data
    @left  = left
    @right = right
  end

  def valid?(min=nil, max=nil)
    if @left.nil? && @right.nil?
      # base case (leaf node)
      return false if min && @data < min
      return false if max && @data >= max
      true # otherwise
    else
      return false if @left && !@left.valid?(min, @data)
      return false if @right && !@right.valid?(@data, max)
      true # otherwise
    end
  end
end

The basic idea is that when you turn left (i.e. recurse into left child), the children should be less than the value of the current node (i.e. you're setting a max = @data limit for the children).

To test it, I did:

root =
  Node.new(10,
    Node.new(5,
      Node.new(2), Node.new(7)),
    Node.new(15,
      Node.new(8), Node.new(20)))

puts root.valid?.inspect # => false (because 8 isn't between 10 -> 15)

Seems to work for me, but would love any feedback (everything's fair game, including style, etc.)


texts: Binary to decimal converter in JavaScript

texts:
This exercise with a test suite is from here. I did not intend to use ES6 features, it's plain old JavaScript. That's why I seek advice more on the good practices, performance side, than modern syntax. Basically anything to make this code more elegant, without ES6.

// Constructor
var Binary = function(binary) {
  this.binary = binary;
  this.base = 2;
};

// Transform the string input in a reversed array
Binary.prototype.reverseInput = function() {
  return this.binary.split('').reverse();
};

// Handle the conversion to decimal
Binary.prototype.toDecimal = function() {
  var output = 0;
      binaryArray = this.reverseInput();

  if (this.invalidInput()) {
    return output;
  }

  for (var i = 0, j = binaryArray.length; i < j; i++) {
    output += binaryArray[i] * Math.pow(this.base, i);
  }

  return output;
}

// Check if any character is not a 1 or a 0
Binary.prototype.invalidInput = function() {
  for (var i = 0, j = this.binary.length; i < j; i++) {
    if (this.binary[i] != '0' && this.binary[i] != '1') {
      return true;
    }
  }
}

module.exports = Binary;


texts:
This is a fixed up version (following RAII principles) of my previous reviewal. I have moved the construction of the object entirely to the constructor to prevent any bad object states.

The only thing I am slightly concerned about is if an exception is thrown, the destructor will not be called thus causing shader objects to leak (as glDeleteShader won't be called).

Maybe wrapping the shader handle ID (shader_id) in some sort of POD-wrapper could fix this?

compilation_error.h

#pragma once

#include <stdexcept>
#include <string>

class CompilationError : public std::runtime_error {
public:
    CompilationError(const std::string &message, std::string info_log);

    const std::string &get_info_log() const;

private:
    const std::string info_log;
};

compilation_error.cpp

#include <render/shader/compilation_error.h>

CompilationError::CompilationError(const std::string &message, std::string info_log) :
    runtime_error(message), info_log(std::move(info_log)) {}

const std::string &CompilationError::get_info_log() const {
    return info_log;
}

shader.h

#pragma once

#include <engine.h>
#include <string>

class Shader {
public:
    Shader(GLenum type, const std::string &path);

    ~Shader();

private:
    const GLuint shader_id;
};

shader.cpp

#include <render/shader/shader.h>
#include <render/shader/compilation_error.h>
#include <fstream>

Shader::Shader(const GLenum type, const std::string &path) :
    shader_id(glCreateShader(type)) {
    if (!shader_id) {
        throw std::runtime_error("Unable to create shader");
    }

    std::ifstream input_stream(path, std::ifstream::in | std::ifstream::ate);

    if (!input_stream) {
        glDeleteShader(shader_id);

        throw std::ifstream::failure("Unable to open shader file");
    }

    const long source_length = input_stream.tellg();
    std::vector<char> source((unsigned long) source_length);

    input_stream.seekg(0);
    input_stream.read(source.data(), source_length);

    const GLchar *sources[] = {source.data()};
    const GLint lengths[] = {(GLint) source_length};

    glShaderSource(shader_id, 1, sources, lengths);
    glCompileShader(shader_id);

    GLint compile_status;
    glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compile_status);

    if (!compile_status) {
        GLint log_length;
        glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &log_length);

        std::vector<GLchar> log_output((unsigned long) log_length);
        glGetShaderInfoLog(shader_id, log_length, nullptr, log_output.data());

        std::string info_log(log_output.data());

        if (!info_log.empty() && info_log.back() == '\n') {
            info_log.pop_back();
        }

        glDeleteShader(shader_id);

        throw CompilationError("Unable to compile shader", info_log);
    }
}

Shader::~Shader() {
    glDeleteShader(shader_id);
}


texts: Calculating the prime numbers between two integers

texts:
I've wrote this code to calculate the prime numbers between two integers n and m, and I want to optimise it.

#include<iostream>
#include <cmath>
using namespace std;
int main (){
long int T[100][2],n,m,i,j;
int testcase,k;
bool prem;
cin>>testcase;
for(i=0;i<testcase;i++){
   cin>>T[i][0]>>T[i][1];}
for(k=0;k<testcase;k++){
    m=T[k][0];
    n=T[k][1];
for(i=m;i<=n;i++){
    prem=true;
for(j=2;j<i;j++){
    if(i%j==0){prem=false;}}
    if(prem) {cout<<i<<endl;}}}
return 0;}


texts: Deserialize string into property array of the deserializing type using json.net

texts:
I have the input JSON

{"QtyEqualsQtyWorked":0,"ReasonCode":"IN"}

and my class is

public class LoadForMovementOpt
{
    public bool QtyEqualsQtyWorked { get; set; }
    public string[] ReasonCode { get; set; }
}

The property ReasonCode has to be array for some reasons I cannot argue with, but in json it can be both string and string[]. So I wrote a custom converter that actually works, but maybe it can improved:

class LoadForMovementConverter : JsonConverter
{
    public override bool CanConvert(Type objectType) { return true; }
    public override bool CanWrite
    {
        get
        {
            return false;
        }
    }
    public override bool CanRead
    {
        get
        {
            return true;
        }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        var reasonToken = token["ReasonCode"];

        if(reasonToken == null)
        {
            return token.ToObject(objectType);
        }

        if(reasonToken.Type == JTokenType.Array)
        {
            return token.ToObject(objectType);
        }
        else
        {
            var QtyEqualsQtyWorkedToken = token["QtyEqualsQtyWorked"];
            return
            new LoadForMovementOpt
            {
                QtyEqualsQtyWorked =
                    QtyEqualsQtyWorkedToken
                        .ToObject<bool>(),
                ReasonCode =
                    new string[]
                    {
                        reasonToken.ToObject<string>()
                    }
            };
        }
    }
}

Is there any way to improve it?


texts: Selection algorithm using merge sort and IEnumerable

texts:
For educational purposes, I wrote a selection algorithm based on a Merge sort. I would like to improve performance.

public IEnumerable<T> MergeSort<T>(List<T> list, int left, int right, Comparer<T> comparer)
{
    if (left == right)
    {
        yield return list[left];
        yield break;
    }

    //divide
    int mid = (left + right) / 2;
    var firstEnumerable = MergeSort(list, left, mid, comparer);
    var secondEnumerable = MergeSort(list, mid + 1, right, comparer);

    //merge
    using (var firstEnumerator = firstEnumerable.GetEnumerator())
    using (var secondEnumerator = secondEnumerable.GetEnumerator())
    {
        bool first = firstEnumerator.MoveNext();
        bool second = secondEnumerator.MoveNext();

        while (first && second)
        {
            if (comparer.Compare(firstEnumerator.Current, secondEnumerator.Current) < 0)
            {
                yield return firstEnumerator.Current;
                first = firstEnumerator.MoveNext();
            }
            else
            {
                yield return secondEnumerator.Current;
                second = secondEnumerator.MoveNext();
            }
        }

        while (first)
        {
            yield return firstEnumerator.Current;
            first = firstEnumerator.MoveNext();
        }

        while (second)
        {
            yield return secondEnumerator.Current;
            second = secondEnumerator.MoveNext();
        }
    }
}

What it does : it recursively divide the list into smaller sequences (until the sequence has only one element). Then, it repeatedly merge sequences to produce new sorted ones until there is only 1 sequence remaining.

The main idea is to use IEnumerable<T> so there is no need to allocate arrays to merge results AND I can sort the list lazily and stop when I want. Example :

var list = ... // 1.000.000 elements
MergeSort(list, 0, list.length - 1, comparer).Take(50);

The actual performance to sort 1M integers and return the first 50 ones is 600 ms why I found to be slower than expected.  Returning only the first element give a similar performance.

My main concern is the recursive calls between Enumerators/IEnumerables. I have tried to wrote the same logic using a stack (to fully avoid recursion) but I don't know how to implement it.

I have also tried to isolate the merge code part (the code inside the two usings statements) into a separate method but it run considerably slower (about 1 sec). I don't know why.

I could easily parallelise the algorithm or use another selection algorithm (like quick select) but this is outside the scope of this question.


texts: Removing C++ template arguments from a C++ function name

texts:
I'm working on some code that deals with mangled C++ function names. I'm displaying these to the user, so to help with readability of some of the really long C++ template class/function names, I'm removing some of the template arguments based on how deeply nested the template argument is.

The code below works fine, but it seems fairly clunky. It feels like I'm "writing C in any language". I'm wondering if I can improve it, shorten it, and make it more pythonic.

def removeTemplateArguments(str, depthToRemove):
    """ Remove template arguments deeper than depthToRemove
        so removeTemplateArguments("foo<int>()", 1) gives foo<>()
           removeTemplateArguments("foo< bar<int> >()", 1) gives foo< >()
           removeTemplateArguments("foo< bar<int> >()", 2) gives foo< bar<> >()"""
    if depthToRemove <= 0:
        return str
    currDepth = 0
    res = ""
    for c in str:
        if currDepth < depthToRemove:
            res += c
        if c == "<":
            currDepth += 1
        elif c == ">":
            currDepth -= 1
            if currDepth < depthToRemove:
                res += ">"
    return res


texts: Reduce nested for loops and if statements using Iterator Blocks?

texts:
Is it possible to reduce this long nested for loops and if conditions to increase its readability and to optimize it for future reference.

While writing code for my scheduling app, I ended up with a method as shown below. Really, I have a data structure like this. Here, I checks - Is there any stages (Inside LCycle) which using same Tool at same time and If its found so, another method LCycleTimeShift is called to make a rearrangment.

But I want to check whether the new arrangement is adaptable and the for loop counter is reset so that it will check the new arrangment again. I think this is not the better way to write the code for  better readabilty. A little research on the topic found that Enumerators can help me in this. But I don't know how can I accomplish this with the following code.

public List<LCycle> ToolArrangment(List<LCycle> TimeLineInit)
{
    for (int i = 0; i < TimeLineInit.Count; i++)//Each LIfeCycles In TimeLine
    {
        for (int j = 0; j < TimeLineInit[i].Stage.Count; j++)//Each Stages inTimeLine
        {
            for (int k = 0; k < i; k++)//Each L esvd =ifeCycles Upto Current LifeCycle
            {
                for (int l = 0; l < TimeLineInit[k].Stage.Count; l++)//Each Stages of (LifeCycle upto current LifeCycle)
                {
                    for (int m = 0; m < TimeLineInit[i].Stage[j].ToolList.Count; m++)//each tools in stage of timelkine
                    {
                        for (int n = 0; n < TimeLineInit[k].Stage[l].ToolList.Count;n++ )// Each tools In that stage (for loop outer of outer)
                        {
                            if (TimeLineInit[i].Stage[j].ToolList[m].ToolName == TimeLineInit[k].Stage[l].ToolList[n].ToolName)//If both tools are same (satidfying above for loop conditions)
                            {
                                if (IsTimeOverLaps(TimeLineInit[i].Stage[j].StageSpan, TimeLineInit[k].Stage[l].StageSpan))
                                {//tool using at same time.
                                    Stage ReplaceStage = TimeLineInit[i].Stage[j].DeepCopy();//Taking Copy of stage Span to make time shift
                                    Double TimeDifference=(ReplaceStage.StageSpan.ToTime-ReplaceStage.StageSpan.FromTime).TotalMinutes;//Calculating required time shift
                                    ReplaceStage.StageSpan.FromTime=TimeLineInit[k].Stage[l].StageSpan.ToTime;//FromTime changed accordingly
                                    ReplaceStage.StageSpan.ToTime=ReplaceStage.StageSpan.ToTime.AddMinutes(TimeDifference);//To Time Changed accordingly
                                    LCycleTimeShift(TimeLineInit[i], ReplaceStage);//passing refernce
                                    j = 0; k = 0; l = 0; m = 0; n = 0;//Counter Reset to validate the new arrangment
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return TimeLineInit;
}


texts:
The problem I have is to find the sum of 2 linked lists. Each linked list node contains 1 digit that represents a number.

My algorithm works but I was wondering if there is a more efficient (speed and memory wise) to solve this problem OR maybe some minor tweaks I can do to reduce space and runtime.

Example: 7 -> 5 -> 6 = 756

I am trying to find the sum of 2 linked lists.

def addlist(LL1, LL2):
    storage = []
    multiplier = 1
    total = 0
    while LL1 != None:
        storage.append(LL1.data)
        LL1 = LL1.next
    for i in storage[::-1]:
        total += i*multiplier
        multiplier *= 10
    storage = []
    multiplier = 1
    while LL2 != None:
        storage.append(LL2.data)
        LL2 = LL2.next
    for j in storage[::-1]:
        total += j*multiplier
        multiplier *= 10
    return total


texts: Parse WAP-230 "variable length unsigned integers"

texts:
I am working on a program to decode an MMS PDU file.  In the file, the "content-length" is represented in a unique way.  According to the MMS spec WAP-230 Section 8.1.2, it is encoded as a "Variable Length Unsigned Integer".

Basically for each byte, the 1st bit is the "continue bit" and the other 7 are the "payload".  We keep reading bytes while the "continue bit" is 1.  When it's 0, we take the "payloads" and combine them together into a value.

Here's an example, let's say I have the following bytes:

82 E5 04

or in binary:

1000 0010 1110 0101 0000 0100

Then we split them into their continue bit/payload:

1 | 0000010
1 | 1100101
0 | 0000100

Now, we start from the beginning, append the bits and move on until the continue bit is 0.  Thus we get the value:

000001011001010000100

or broken into bytes (and left padded with zeroes):

0000 0000 1011 0010 1000 0100

This can be read (in hex) as:

00 B2 84

which converts to 45700 (0xB284).

I tried to implement this in python as I was reading through an MMS PDU file byte by byte.  Here is what I came up with:

cont_bit = True
remaining_bits = []

while cont_bit:
    variable_length = self.data[curr_index]
    curr_index += 1

    # There's obviously a better way to do this, but I don't really know what it is
    binary_length = bin(variable_length).lstrip('0b').zfill(8)

    # Check the "continue bit"
    cont_bit = (binary_length[0] == '1')
    remaining_bits.append(binary_length[1:])

# Put the values together and read it as an int
content_length = int(''.join(remaining_bits), 2)

Note: self.data is the binary file I am reading and curr_index is my current position in the file.

This does work and content_length does contain the right value, I just think there's gotta be a better way to do this than to convert each byte into a string (representing its binary representation), reading the 1st character of this string, then appending the rest of the string into an array (which I parse as a base-2 integer).


texts: Concatenating strings into a fixed-size char array in C

texts:
Using the standard C library, I want to repeatedly concatenate onto a fixed size string. Despite its promising name, the semantics of strncat do not appear suited to doing this, and the return value provides no new information. strncpy also requires a strlen to update the position. The reason I used snprintf (C99) in the code below is that it returns the number of characters written, which I can subtract from future calls. I've written a helper struct:

#include <stdlib.h> /* EXIT_SUCCESS */
#include <stdio.h>  /* *printf */
#include <string.h> /* strlen */

struct Supercat {
    char *print, *cursor;
    size_t left;
    int is_truncated;
};

/** Initialises {cat} to hold the string {print}, size {print_size}. It stores
 the empty string in print. */
static void supercat_init(struct Supercat *const cat, char *const print,
    const size_t print_size) {
    cat->print        = cat->cursor = print;
    cat->left         = print_size;
    cat->is_truncated = 0;
    print[0] = '\0';
}

/** Adds {append} to the string specified when \see{supercat_init} was
 called. If {append} is too big for the size, it truncates the string and sets
 {cat.is_truncated}. */
static void supercat(struct Supercat *const cat, const char *const append) {
    size_t size_took;
    int took;

    if(cat->is_truncated) return;
    took = snprintf(cat->cursor, cat->left, "%s", append);
    if(took < 0)  { cat->is_truncated = -1; return; }
    if(took == 0) { return; }
    if((size_took = took) >= cat->left) {
        cat->is_truncated = -1, size_took = cat->left - 1;
    }
    cat->cursor += size_took, cat->left -= size_took;
}

static const char *const start_str     = "[ ";
static const char *const end_str       = " ]";
static const char *const alter_end_str = "...]";
static const char *const sep_str       = ", ";
static const char *const null_str      = "Null";

int main(int argc, char **argv) {
    static char buffer[80];
    struct Supercat cat;
    int i;

    /* want to terminate before the end; always have space for alter_end_str */
    supercat_init(&cat, buffer, sizeof buffer - strlen(alter_end_str));

    if(!argc) {
        supercat(&cat, null_str);
    } else {
        supercat(&cat, start_str);
        for(i = 0; i < argc; i++) {
            if(i) supercat(&cat, sep_str);
            supercat(&cat, argv[i]);
            if(cat.is_truncated) break;
        }
        /* we are guaranteed to have enough room */
        sprintf(cat.cursor, "%s", cat.is_truncated ? alter_end_str : end_str);
    }

    printf("Arguments: %s.\n", cat.print);

    return EXIT_SUCCESS;
}

The string now will go up to 79 characters and refuse to write any more:

Thor:Supercat neil$ bin/Supercat
Arguments: [ bin/Supercat ].
Thor:Supercat neil$ bin/Supercat saves the day!
Arguments: [ bin/Supercat, saves, the, day! ].
Thor:Supercat neil$ bin/Supercat where are you? we need you to rescue us from the burning building.
Arguments: [ bin/Supercat, where, are, you?, we, need, you, to, rescue, us, from, the,...].
Thor:Supercat neil$ bin/Supercat where are you? we need you to rescue us from this burning building.
Arguments: [ bin/Supercat, where, are, you?, we, need, you, to, rescue, us, from, this...].
Thor:Supercat neil$ bin/Supercat where are you? we need you to rescue us from danger.
Arguments: [ bin/Supercat, where, are, you?, we, need, you, to, rescue, us, from, dang...].

Using a temporary structure is a pain, but it seems to me like writing something like if(strlen(strncat(cat, argv[i], sizeof cat - strlen(cat))) >= sizeof buffer) break; would be inefficient on large strings because it traverses the string 3 times (I count) to write one value. On the other hand, snprintf is overkill with a constant format string.


texts:
I have only started working with XML files and PowerShell. I feel that while there are many ways to accomplish the same thing that I might be doing the following inefficiently.

This is all based on the following SO post which I have an answer to:

$numberOfCores = Get-WmiObject -class win32_processor numberOfCores | Select-Object -ExpandProperty numberOfCores

$path = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machineTest.config"
[xml]$machineConfig = Get-Content $path

# Remove the elements we are going to be replacing
$node = $machineConfig.SelectNodes("/configuration/system.web")
[void]($node.RemoveChild(($node.SelectSingleNode("processModel"))))
[void]($node.RemoveChild(($node.SelectSingleNode("httpHandlers"))))

# Create the element processModel and set attributes
$processModelxml = $machineConfig.CreateElement("processModel")
$processModelxml.setAttribute("maxWorkerThreads",370)
$processModelxml.setAttribute("maxWorkerThreads",370)
$processModelxml.setAttribute("maxIoThreads",370)
$processModelxml.setAttribute("minWorkerThreads",50)
$processModelxml.setAttribute("minIoThreads",50)
[void]($node.AppendChild($processModelxml))

# Create the element httpRuntime and set attributes. Adjust values based on number of cores
$httpRuntimexml = $machineConfig.CreateElement("httpRuntime")
$httpRuntimexml.setAttribute("minFreeThreads",90 * $numberOfCores)
$httpRuntimexml.setAttribute("minLocalRequestFreeThreads",80 * $numberOfCores)
[void]($node.AppendChild($httpRuntimexml))

# Build the <system.net> section
[xml]$systemnetxml = @"
  <system.net>
    <connectionManagement>
      <add address = "*" maxconnection = "$(200 * $numberOfCores)" />
    </connectionManagement>
  </system.net>
"@

# Import into config
$machineConfig.configuration.AppendChild($machineConfig.ImportNode($systemnetxml."system.net",$true)) | Out-Null

# Save changes
$machineConfig.Save("c:\temp\testing.xml")
# Change back to $path to write back to original file.

If you wanted to test this you need to change $path to that of a local machine.config in a .Net build folder. Also the last step saves the file in an alternate location for testing. Changing it to $machineConfig.Save($path) would be a production approach.

In my defense this code was gear towards a new user so there are a few lines that are created to be more verbose on purpose. I am mostly interested in the XML focus of this code but will welcome any criticism towards the rest (in case I am being complacent.) Was designed using PowerShell v4.


texts: Rendering three types of events as HTML elements

texts:
I have to clean up some Javascript and I am trying to figure out a more elegant way to write this code below. It's basically looping through 3 dictionaries with the same loop structure and appending some custom HTML onto a specific div.  I wanted to see if there is a way to avoid this repetitive code:

if (dtInt in calendarEventDict) {
    var arrEvents = calendarEventDict[dtInt];
    for (var a = 0; a < arrEvents.length; a++) {
        var calendarEvent = arrEvents[a];
        $("#dateCupcake" + i).append("
" + calendarEvent.DisplayName + "
");
    }
}
if (dtInt in vacationEvents) {
    var arrEventsV = vacationEvents[dtInt];
    for (var v = 0; v < arrEventsV.length; v++) {
        var vacationEvent = arrEventsV[v];
        $("#dateCupcake" + i).append("
" + vacationEvent.PersonName + "
");
    }
}
if (dtInt in travelEvents) {
    var arrEventsV1 = travelEvents[dtInt];
    for (var v1 = 0; v1 < arrEventsV1.length; v1++) {
        var travelEvent = arrEventsV1[v1];
        $("#dateCupcake" + i).append("
" + travelEvent.TravelRequest.Person.LastName + ", " + travelEvent.TravelRequest.Person.FirstName.Substring(0, 1) + " visiting " + travelEvent.TravelRequest.TechnicalCentre.Name + "
 ");
    }
}


texts:
I have just implemented a quick test of the visitor design pattern in C++ and have a few questions regarding the code.

main.cpp

#include <iostream>

#include "Base.h"
#include "Derived.h"
#include "Visitor.h"

int main() {
    Base base;
    std::cout << "hello\n";
    Base * derived = new Derived();
    Visitor v;
    base.acceptvisitor(v);
    derived->acceptvisitor(v);
}

IVisitable.h

#ifndef IVISITABLE_H
#define IVISITABLE_H

class Visitor;

class IVisitable {
    virtual void acceptvisitor(Visitor v) = 0;
};

#endif

Base.h

#ifndef BASE_H
#define BASE_H

#include <string>

#include "IVisitable.h"

class Base : public IVisitable {
public:
    void acceptvisitor(Visitor v);
};

#endif

Base.cpp

#include "Base.h"

#include "Visitor.h"

void Base::acceptvisitor(Visitor v) {
    v.visit(*this);
}

Derived.h

#include "Base.h"

class Derived : public Base {
public:
    void acceptvisitor(Visitor v);
};

Derived.cpp

#include "Derived.h"

#include "Visitor.h"

void Derived::acceptvisitor(Visitor v) {
    v.visit(*this);
}

Visitor.h

#ifndef VISITOR_H
#define VISITOR_H

class Base;
class Derived;

class Visitor {
public:
    void visit(Base b);
    void visit(Derived d);
};

#endif

Visitor.cpp

#include "Visitor.h"

#include <iostream>

#include "Base.h"
#include "Derived.h"

void Visitor::visit(Base b) {
    std::cout << "Visiting Base\n";
}

void Visitor::visit(Derived d) {
    std::cout << "Visiting Derived\n";
}

And here are some questions, of course I am interested in all remarks you may have not just answers to these.

How do you keep track of includes? Even in this short example I now have includes that are not needed anymore.
Is this #ifndef treatment of header files still normal? I picked it up somewhere but have never actually seen anybody else do it.
Is there any way to treat an object as a superclass without a pointer? I.e. can I do something like this: Base d = Derived();
When can I use a forward declaration like class Visitor; and when do I need to include the actual header file? Or when should I?
Should I make implementations of abstract functions virtual? It seems not to matter.


texts: Handling 8 toggle buttons in a point-of-sale application

texts:
I am self-taught and trying to improve my programming skills.  My project is a point-of-sale application, with lots of buttons. I am curious how improve this section of code, as I seem to be going against the DRY principle.

I have a Customer object named cust, and each customer has an ID that is set to one of 8 different toggle buttons.

    //update the sales to the customers
    //if cust1 toggle button is selected:
    if (cust1.isSelected()){
        //get the id number from the button
        cust = custDAO.getCustById(Integer.getInteger(cust1.getText()));
        //add the sales to the current value
        int sales = cust.getTotalSales();
        //set the value (note: cust.setTotalSales(cust.getTotalSales() + subtotal) doesn't work
        cust.setTotalSales(sales + subtotal);
        //update the Customer
        custDAO.updateCustomer(cust);
    }else if (cust2.isSelected()){
        cust = custDAO.getCustById(Integer.getInteger(cust2.getText()));
        int sales = cust.getTotalSales();
        cust.setTotalSales(sales + subtotal);
        custDAO.updateCustomer(cust);
    }else if (cust3.isSelected()){
        cust = custDAO.getCustById(Integer.getInteger(cust3.getText()));
        int sales = cust.getTotalSales();
        cust.setTotalSales(sales + subtotal);
        custDAO.updateCustomer(cust);
    }else if(cust4.isSelected()){
        cust = custDAO.getCustById(Integer.getInteger(cust4.getText()));
        int sales = cust.getTotalSales();
        cust.setTotalSales(sales + subtotal);
        custDAO.updateCustomer(cust);
    }else if (cust5.isSelected()){
        cust = custDAO.getCustById(Integer.getInteger(cust5.getText()));
        int sales = cust.getTotalSales();
        cust.setTotalSales(sales + subtotal);
        custDAO.updateCustomer(cust);
    }else if(cust6.isSelected()){
        cust = custDAO.getCustById(Integer.getInteger(cust6.getText()));
        int sales = cust.getTotalSales();
        cust.setTotalSales(sales + subtotal);
        custDAO.updateCustomer(cust);
    }else if(cust7.isSelected()){
        cust = custDAO.getCustById(Integer.getInteger(cust7.getText()));
        int sales = cust.getTotalSales();
        cust.setTotalSales(sales + subtotal);
        custDAO.updateCustomer(cust);
    }else if(cust8.isSelected()){
        cust = custDAO.getCustById(Integer.getInteger(cust8.getText()));
        int sales = cust.getTotalSales();
        cust.setTotalSales(sales + subtotal);
        custDAO.updateCustomer(cust);
    }else{
        //No button selected
        System.out.println("No customer selected");
    }


texts: Performing batch insertion for a single row

texts:
I've following code that insert single row in if (rows == 1) { part and inside loop it is batch insert.
So I'm thinking to skip single insert and have it in batch insert code.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

        int rows = jTable.getRowCount();
        if (rows == 1) {
            String itemName = (String) jTable.getValueAt(0, 0);
            int itemQty = (int) jTable.getValueAt(0, 1);
            Double itemPrice = (Double) jTable.getValueAt(0, 2);

            Items items = new Items();
            items.setName(itemName);
            items.setPrice(itemPrice);
            items.setQty(itemQty);
            items.setTransactionNumber(manager.getTransNo());
            manager.saveItems(items);

Above part insert single record if there's only one row in a JTable
Below in else part inside loop performed batch insert if JTable contains more than one row.

        } else {
            for (int i = 0; i < 1; i++) {
                String itemName = (String) jTable.getValueAt(i, 0);
                int itemQty = (int) jTable.getValueAt(i, 1);
                Double itemPrice = (Double) jTable.getValueAt(i, 2);
                Items items = new Items();
                items.setName(itemName);
                items.setPrice(itemPrice);
                items.setQty(itemQty);
                items.setTransactionNumber(manager.getTransNo());
                int max = items.getTransactionNumber();
                manager.saveItems(items);

And here in a second loop it does perform insertion after first row in a JTable when int i = 1.

for (i = 1; i < rows; i++) {
            String itemsName = (String)
            jTable.getValueAt(i, 0);
            int itemsQty = (int) jTable.getValueAt(i, 1);
            Double itemsPrice = (Double)
            jTable.getValueAt(i, 2);

            items.setName(itemsName);
            items.setPrice(itemsPrice);
            items.setQty(itemsQty);
            items.setTransactionNumber(max);
            manager.saveItems(items);
            }
        }
    }
}

I was thinking to save all rows without considering is either only one row or more.
So my modified version would not have if (rows == 1) {....} part
Will have only for (int i = 0; i <= 0; i++) {
So if there will have only one row in a JTable would this modified version can be cause of lower performance?


texts: New Year Chaos JavaScript, needs to be sped up

texts:
Similar to this question but this is for Python

Original problem with description on hacker rank

I am currently trying to iterate through a large number of arrays and count how many times numbers have been swapped.

A sorted array looks like this: [1,2,3,4,5] and a number can be swapped only towards the front (counting down to 0) twice.

If a number is more than 2 out of order the array is deemed 'Too chaotic' and the process should stop.

Instead of bubble sorting I am simply going through and counting the actual swaps. As a sorted array is not actually required, my code works except for a couple of the tests where it times out due to large arrays.

Any ideas on how to speed this process up?

function minimumBribes(q) {
console.log(sort(q));

    function sort(items) {
     let bribes = 0;

     for (let i = 0; i < items.length; i++) {
         if (items[i] - (i + 1) > 2) return "Too chaotic";
         for (let j = 0; j < i; j++) {
             if (items[j] > items[i]) bribes++;
         }
     }
     return bribes;
   }
}


texts:
I have this jQuery function I wrote up to set the size of an input based off of its data. In this case I have already figured out the widths for each character based off of a 12px font size for Helvetica.

It's not super flexible or anything, but I would like to know if there is any good way to take what I have and maybe make it more elegant (or fewer lines of code).

HTML:

<input value="Some really long string about nothing important"" />

CSS:

body {
    font-family:Helvetica;
    font-size:12px;
}
span {
    padding:0;
    margin:0;
}
input {
    border:0;
}

JavaScript / jQuery:

// Helvetica, 12px or 1.2em at 62.5%
var str = $('input').val();
var length = str.length;

var charWidth = 0;
for ( var i = 0; i < length; i++ )
{
    console.log(str[i]);

    if ( str[i] == "f" ||
         str[i] == "i" ||
         str[i] == "I" ||
         str[i] == "j" ||
         str[i] == "l" ||
         str[i] == "t"
       )
    {
        charWidth += 3;
    }
    if ( str[i] == "r" )
    {
        charWidth += 4;
    }
    if ( str[i] == "v" ||
         str[i] == "x" ||
         str[i] == "y" ||
         str[i] == "z"
       )
    {
        charWidth += 5;
    }
    if ( str[i] == "c" ||
         str[i] == "k" ||
         str[i] == " "
       )
    {
       charWidth += 6;
    }
    if ( str[i] == "a" ||
         str[i] == "A" ||
         str[i] == "b" ||
         str[i] == "d" ||
         str[i] == "e" ||
         str[i] == "F" ||
         str[i] == "g" ||
         str[i] == "h" ||
         str[i] == "J" ||
         str[i] == "L" ||
         str[i] == "n" ||
         str[i] == "o" ||
         str[i] == "p" ||
         str[i] == "q" ||
         str[i] == "s" ||
         str[i] == "T" ||
         str[i] == "u" ||
         str[i] == "V" ||
         str[i] == "X" ||
         str[i] == "Y" ||
         str[i] == "Z" ||
         str[i] == "0" ||
         str[i] == "1" ||
         str[i] == "2" ||
         str[i] == "3" ||
         str[i] == "4" ||
         str[i] == "5" ||
         str[i] == "6" ||
         str[i] == "7" ||
         str[i] == "8" ||
         str[i] == "9"
       )
    {
        charWidth += 7;
    }
    if ( str[i] == "B" ||
         str[i] == "E" ||
         str[i] == "K" ||
         str[i] == "P" ||
         str[i] == "S"
       )
    {
        charWidth += 8;
    }
    if ( str[i] == "C" ||
         str[i] == "D" ||
         str[i] == "G" ||
         str[i] == "H" ||
         str[i] == "M" ||
         str[i] == "N" ||
         str[i] == "O" ||
         str[i] == "Q" ||
         str[i] == "R" ||
         str[i] == "U" ||
         str[i] == "w"
       )
    {
        charWidth += 9;
    }

    if ( str[i] == "m" || str == "W")
    {
        charWidth += 11;
    }
}

$('input').css({'width': charWidth});

jsFiddle


texts: Truncate String to target length using only whole words

texts:
I've got a bit of code that I'm wanting to tidy up. The aim is to take a String that consists of multiple words connected by a separator (It's produced using Collectors.joining(SEPARATOR) as below, although the stream processing is not quite so trivial), and return a portion from the front of it.

This portion should never contain partial words, but should in most cases be less than the TARGET_LENGTH number of total characters. It is safe to assume that the words themselves do not contain the SEPARATOR character.

String SEPARATOR = "-";
int TARGET_LENGTH = 20;

//Expected output: "this-is-a-sample"
String s = Arrays.asList("this", "is", "a", "sample", "string")
            .stream()
            .collect(Collectors.joining(SEPARATOR));

if (s.length() > TARGET_LENGTH) {
    if (s.contains(SEPARATOR)) {
        if (s.substring(0, TARGET_LENGTH + 1).contains(SEPARATOR)) {
            return s.substring(0, s.substring(0, TARGET_LENGTH + 1).lastIndexOf(SEPARATOR));
        } else {
            return s.substring(0, s.indexOf(SEPARATOR));
        }
    }
}
return s;

Expected output is as follows:

s                                   ||  result
"easy"                              ||  "easy"
"simple-case"                       ||  "simple-case"
"very-long-input-will-be-truncated" ||  "very-long-input-will"
"countercountermeasures"            ||  "countercountermeasures" //Longer than 20 chars
"countercountermeasures-foo-bar-baz"||  "countercountermeasures" //Longer than 20 chars
"a-b-c-d-e-f-g-veryveryverylongword"||  "a-b-c-d-e-f-g"

The provided code works, but isn't very clear and I imagine it will be horrible to maintain if any requirements change in the future. I'm looking for suggestions as to how it could be improved. I've considered adding a filter to the Stream that generates the String, with a counter keeping track of the current output length declared outside of the string-generation, but this feels like an even worse thing to do (At a guess I'd have to do something silly like update the counter from within a call to Stream.map())


texts:
I am seeking a review of a previous project I completed to help understand hash tables.  The following is my implementation of a hash-table using linear probing.

My solution assumes a number of variables have been initialised:

Private int[] H;  Representing the hash table with each value initialised to -1
private int hSize; Storing the size of the hash table

Hash Function:

public int hash(int key){
    return key % hSize;
}

Add value to hash table:

private void addToHash(int value){

    int i;

    for (i = hash(value); H[i] != -1; i = (i + 1) % H.length)
        if (H[i] == value) return;

    H[i] = value;

}

Search for value:

public int hashSearch(int key){

    int hash = hash(key);

    for (int i = hash; H[i] != -1; i = (i + 1) % H.length)
        if (H[i] == key) return i;

    return -1;

}

I am looking for feedback regarding the design of my solution / programming style - Anything which could be improved in the future or would not be encouraged when programming in the industry.


texts:
I have to co-operate with third party APIs from where I get a list and I have to remove certain elements before passing it toward.
I have a working solution but I am opened for every suggestion to make it better or more reliable (assuming the third party API maybe will change a bit in the future):

public List<Column> remove(List<Column> columns){
    for(Iterator<Column> iterator = columns.listIterator(); iterator.hasNext();     ){
     Column column = iterator.next();
     try{
      switch(column.getValue()){
        case "FIRST":
        case "SECOND":
        case "THIRD":
          iterator.remove();
      }
     }catch(NullPointerException e){}
    }
    return columns;
}

Edit

Yes, it is not my production code. My production code is something like this:

private static final String FIRST = "first to remove";

private static final String SECOND = "second to remove";

private static final String THIRD = "third to remove";

...lots of code here

List<Column> columns = ThirdPartyLibrary.getColumns();
for(Iterator<Column> iterator = columns.listIterator(); iterator.hasNext();     ){
     Column column = iterator.next();
     try{
      switch(column.getValue()){
        case FIRST:
        case SECOND:
        case THIRD:
          iterator.remove();
      }
     }catch(NullPointerException e){}
}
working with columns

I made the try and catch methods for the case if I get a column from the third party which getValue() returns null.


texts:
I have this code:

Tabzilla.fillZGContacts = function(){
   if (!Tabzilla.panel.id) return;
   $.ajax({
       url: 'zgcontacts.json',
      success: function(d){   // "Type","Name","Link","Contact","Location","Icon"
        Tabzilla.zgContacts = d;
        var countries = [];
        d.rows.forEach(function(row){
          if (row[0] == 'Country') countries.push(
            {link:row[2], contact:row[3], country: row[4]}
          );
        });

        //alphabetically
        countries.sort(sortByKey('country'));

        //adding link
        countryTemplate = function (country){
          s = ''
      +'
'
        +''+country.country+'
'
        return s;
        }

        var byletter = {};

        //count countries starting from each letter
        countries.forEach(function(c){
          var firstletter = c.country.toLowerCase().charAt(0);
          if (byletter[firstletter]) byletter[firstletter]++;
          else byletter[firstletter]=1;
        });
        console.log(byletter);
        //prepare containers
        var panel = $("#"+Tabzilla.panel.id);
        var $cols = [];

        $cols.push(panel.find(".c_COL4"));
        $cols.push(panel.find(".c_COL3"));
        $cols.push(panel.find(".c_COL2"));
        $cols.push(panel.find(".c_COL1"));
        var columns = $cols.length;
        var targetlen = countries.length/columns;

        var FirstLetter = countries[0].country.toLowerCase().charAt(0);
        var cc = [];

        //fill containers. this loop is buggy. should be reviewed.
        countries.forEach(function(c){
          var newFirstLetter = c.country.toLowerCase().charAt(0);
          if (FirstLetter != newFirstLetter)
          {

             var l1 = cc.length;
             var l2 = l1 + byletter[newFirstLetter];
             //condition maybe shd be changed..

             if (Math.abs(l2-targetlen) >= Math.abs(l1-targetlen)){
               var $col;
               if ($cols.length>0) $col = $cols.pop();
               cc.forEach(function(c){
                 $col.append(countryTemplate(c));
               });
               cc=[];

               //does not work :(
               //could generate another template with first letter raised
               $col.find('span').first().addClass("first-letter");
             }
             cc.push(c);
          }
          else cc.push(c);
          FirstLetter = newFirstLetter;
        });

      },
   });
}

The zgcontacts.json file can be found here.

Any pointers in optimizing this is much appreciated.  For example, this loop:

countries.forEach(function(c)


texts:
I have a function that returns some preferences, but first I have to do some checks to see whether the user is authorised to read them. I'm still not happy with the result (the match is a bit ugly).

Note: Result is a framework class, it just means some kind of response.

// implementations are not relevant.
def canAccessPreferences(id: Long): Future[Boolean] = ???
def doGetPreferences(id: Long): Future[Result] = ???

def getPreferences(id: Long) = Future[Result] {

  canAccessPreferences(id).flatMap {
     case false =>
       Future.successful(Forbidden)
     case true =>
       doGetPreferences(id)
  }
}


texts:
I'm very new to Haskell, and I would like some feedback on my coding style. Is there anything here that could be made more elegant or concise?

This is my solution to Project Euler Problem 57.

  It is possible to show that the square root of two can be expressed as an infinite continued fraction.

  $$\sqrt 2 = 1 + \dfrac{1}{2 + \dfrac{1}{2 + \dfrac{1}{2 + \ldots}}} = 1.414213\ldots$$

  By expanding this for the first four iterations, we get:

  1 + 1/2 = 3/2 = 1.5

  1 + 1/(2 + 1/2) = 7/5 = 1.4

  1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...

  1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...

  The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.

  In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?

numerator =
  3 : 7 : zipWith (+) numerator (map ((*) 2) (tail numerator))

denominator =
  2 : 5 : zipWith (+) denominator (map ((*) 2) (tail denominator))

numDigits :: Integer -> Int
numDigits = length . show

moreDigits :: Integer -> Integer -> Bool
moreDigits x y = (numDigits x) > (numDigits y)

countTrue :: [Bool] -> Int
countTrue = length . filter ((&&) True)

pe_057 = countTrue $
  take 1000 (zipWith moreDigits numerator denominator)

main :: IO ()
main = do
    print pe_057


texts:
I'm new to Kotlin, not so new to Java and Android development. But willing and trying to make a switch. I've wrote a simple validator for EditText
and was wondering if there is a way to write it more compact with lambdas.

textMTU.addTextChangedListener(object : EditTextValidator(textMTU) {
    override fun validate(textView: EditText, text: String) {
        val textToInt = if (text.isEmpty()) 0  else text.toInt()
        if (textToInt < 1280 || textToInt > 1500) {
            textView.error = getString(R.string.errorTroubleshoot)
        }
        else {
            textView.error = null
            val input = if (textMTU.rawText.isEmpty()) defaultSize else textMTU.rawText.toInt()
            if (input in 1281..1499) {
                prefs.mtuSize = input
            }
        }
    }

EditTextValidator here is simply extended TextWatcher without beforeTextChanged and onTextChanged methods


texts: A recursive_transform for std::array with various return type

texts:
This is a follow-up question for A recursive_transform for std::vector with various return type. Thanks to G. Sliepen provide further review suggestions. After digging into the topic of achieving a more generic recursive_transform function in both various output type and various container type, I still have no simple solution. However, based on G. Sliepen's answer, the case of the std::vector, std::deque and std::list container types may be resolved. I am trying to implement additional another overload recursive_transform function for std::array. Here's my implementation.
template<class T, std::size_t S, class F>
auto recursive_transform(std::array<T, S>& input, const F& f)
{
    using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));

    std::array<TransformedValueType, S> output;
    std::transform(input.cbegin(), input.cend(), output.begin(),
        [f](auto& element)
        {
            return recursive_transform(element, f);
        }
    );
    return output;
}

The test case of std::array:
//  std::array<int, 10> -> std::array<std::string, 10>
std::array<int, 10> test_array;
for (int i = 0; i < 10; i++)
{
    test_array[i] = 1;
}
auto recursive_transform_result5 = recursive_transform(
    test_array,
    [](int x)->std::string { return std::to_string(x); });                          //  For testing
std::cout << "string: " + recursive_transform_result5.at(0) << std::endl;

Here's the Godbolt link. The code in this link including the test cases for std::vector, std::deque and std::list.
All suggestions are welcome.
The summary information:

Which question it is a follow-up to?
A recursive_transform for std::vector with various return type

What changes has been made in the code since last question?
The handleable container type in the previous version of recursive_transform function is std:vector. With G. Sliepen's answer, this handleable container type list is extended to std::vector, std::deque and std::list. Then, I am trying to deal with std::array here.

Why a new review is being asked for?
In this version of recursive_transform function, it seems that working well in the mentioned test case std::array<int, 10> -> std::array<std::string, 10>. However, there is some issues when it comes to the more complex case like std::array<std::array<int, 10>, 10> -> std::array<std::array<std::string, 10>, 10> (the scalability to be improved!) If there is any suggestion or possible idea about this, please let me know.


texts: Variable assign expression with multiple expressions

texts:
I have three types of variable assign expression with multiple expressions.

It looks ugly, but I'm not sure how to make it more readable.

Type 1

  following_triggers = alarm_test_group.map{ |alarm_test|
      self.class.where{ sony_alarm_test_id.eq(alarm_test.id) }
      .where{ utc_time.gt(my{utc_time}+TIME_CORRECTION) }
      .where{ name =~ my{self.name} }
      .first
  }.select!{|t| t != nil}

Type 1-1

  following_triggers = alarm_test_group.map do |alarm_test|
                      self.class.where{ sony_alarm_test_id.eq(alarm_test.id) }
                      .where{ utc_time.gt(my{utc_time}+TIME_CORRECTION) }
                      .where{ name =~ my{self.name} }
                      .first
                      end.select!{|t| t != nil}

Type 2

  q = self.class
      .where{ (utc_time.gt(my{utc_time}+time_correction)) & utc_time.lt(closest_trigger_utc_time) }
      .where{ name =~ event_name }
      .where{ sony_alarm_test_id.eq(my{sony_alarm_test.id})}

Type 3

previous_alarms = \
  get_alarm_tests_in_the_same_group.map do |alarm_test|
    self.class
    .where{sony_alarm_test_id.eq(alarm_test.id)}
    .where{ name =~ "AlarmLogger" }
    .where{utc_time.lt(my{self.utc_time})}
    .last
  end

    @@following[event_type.to_sym] = \
      followed.following(event_type)
      .where{ sony_alarm_test_id == followed.sony_alarm_test_id }
      .limit(CACHE_UPPER_BOUND).to_a.dup


texts: Software drivers for the mcu peripherals in C++

texts:
I have been developing software drivers for the mcu peripherals in C++. My approach how to implement the drivers is following.
Each peripheral has its software driver modeled by C++ class with its interface
Peripheral.h
#include <cinttypes>
#include "DriversCfg.h"

class Peripheral {
public:

    Peripheral(const PeripheralCfg& peripheral_cfg, uint32_t base_address);

    void enable();
    void toggleReset();
    bool isEnabled();

private:

    struct ControlReg
    {
        uint32_t enable_bit:    1;
        uint32_t reset_bit:     1;
        uint32_t cfg_bit_01:    1;
        uint32_t cfg_bit_02:    1;
        uint32_t cfg_bit_03:    1;
    };

    struct PeripheralRegs
    {
        volatile ControlReg control_reg;
    };

    PeripheralRegs* regs;

};

and its implementation
Peripheral.cpp
#include <new>
#include "Peripheral.h"

Peripheral::Peripheral(const PeripheralCfg& peripheral_cfg, uint32_t base_address) {
    regs = new (reinterpret_cast<void*>(base_address)) PeripheralRegs;

    regs->control_reg.cfg_bit_01 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_1);
    regs->control_reg.cfg_bit_02 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_2);
    regs->control_reg.cfg_bit_03 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_3);
}

void Peripheral::enable()
{
    regs->control_reg.enable_bit = 1;
}

bool Peripheral::isEnabled()
{
    return ((regs->control_reg.enable_bit) != 0);
}

void Peripheral::toggleReset()
{
    if(regs->control_reg.reset_bit)
    {
        regs->control_reg.reset_bit = 0;
    }
    else
    {
        regs->control_reg.reset_bit = 1;
    }
}

Each peripheral has fixed part of its configuration i.e. part of configuration which is not changeable  during run-time
PeripheralCfg.h
enum class FunctionUsage
{
  kNotUsed,
  kUsed
};

struct PeripheralCfg
{
  FunctionUsage cfg_bit_1;
  FunctionUsage cfg_bit_2;
  FunctionUsage cfg_bit_3;
};

There is a "container" containig the fixed part of the configuration for all the peripherals
DriversCfg.h
#include "PeripheralCfg.h"

struct DriversCfg
{
    PeripheralCfg periph_cfg_01 = {FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcUsed,
                                   FunctionUsage::kAdcUsed};
    PeripheralCfg periph_cfg_02 = {FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcNotUsed,
                                   FunctionUsage::kAdcUsed};
};

There is a "container" containing instances of all the drivers
Hal.h
#include "Peripheral.h"
#include "DriversCfg.h"

class Hal {
public:

    Peripheral *periph_01;
    Peripheral *periph_02;

    Hal();

private:

    DriversCfg configuration;

};

Hal.cpp
#include "Hal.h"
#include "DriversCfg.h"
#include "Registers.h"

Hal::Hal() {
    periph_01 = new Peripheral(configuration.periph_cfg_01, PERIPH_01_BASE_ADDRESS);
    periph_02 = new Peripheral(configuration.periph_cfg_02, PERIPH_02_BASE_ADDRESS);
}

The intended usage is
main.cpp
int main(int argc, char** argv)
{
    Hal hal;

    hal.periph_01->enable();
    hal.periph_02->enable();
}

I have tested this approach and it works. Nevertheless I have some doubts regarding namely following aspects:

container DriversCfg with configuration for the peripherals in which the individual configurations are public - is it a problem here?
order of instantiation of the private attribute DriversCfg configuration in the class Hal more precisely whether there is a chance that the DriversCfg configuration will not be created at the moment when a reference to it will be passed into the peripheral drivers?

Thanks in advance for any remarks and suggestions.


texts: How to better organize the declarations of these functions?

texts:
So as I understand it, you should always declare a function before it gets called.

However in the code below, how could this be restructured so that this philosophy is satisfied?

fetchTags is declared here as the 3rd function, somewhere below here I call it from a loadTags function.

After the tags are loaded, I then attached the EventListener and attach the 2nd function scrollingTags.

Once scrollingTags hits bottom and calls loadMoreItems which returns checkScrollLimit and if this !LIMIT_REACHED is true, limit is not reached, it calls fetchTags again which is declared below checkScrollLimit.

My code works so maybe this is a non-issue, just curious how other developers would treat this.

const checkScrollLimit = () => {
    if (!LIMIT_REACHED) {
        const infiniteScroll = true;
        PARAMS.start += this.limit;
        maxlimitCheck() ? LIMIT_REACHED = true : fetchTags(infiniteScroll);
    }
};

const scrollingTags = () => {
    const reachedBottom = () => tagsCol.scrollHeight - tagsCol.scrollTop === tagsCol.offsetHeight;
    const loadMoreItems = () => checkScrollLimit();
    if (reachedBottom()) loadMoreItems();
};

const fetchTags = (infiniteScroll) => {
    LIMIT_REACHED = false;
    return GetTagsFactory.getTags(false, Util.encodeTicker(this.ticker), PARAMS).then((tags) => {
        TOTAL_TAGS = tags.total;
        this.tags = fillTagsList(tags, infiniteScroll);
        tagsCol.addEventListener('scroll', scrollingTags);
        return this.tags;
    });
};


texts: Using the Return Value of a Function to Select an Element in a Struct Array

texts:
I'm learning MATLAB (still trying to "think in vectors") and have the following piece of code:

stats = regionprops(bwconncomp(mask), 'all');

% find the object nearest our nucleus
smallest_dist = flintmax;
location = [cell_x, cell_y];
for j = 1:numel(stats)
    stat = stats(j);
    dist = pdist([location;[stat.Centroid]], 'euclidean');
    if dist < smallest_dist
        regions{channel} = stat;
        smallest_dist = dist;
    end
end

All that is doing is searching through a struct array for the region which has a location (centroid) closest to my known cell's X/Y.  I'm sure this is not canonical and that it could be improved.


texts: Exercise to create an insertString function to linked-list

texts:
Working from 'Programming in C' by Kochan. I'm on an exercise in the chapter 'Pointers'.

This was the exercise:

'Write a function called insertEntry() to inset a new entry into a linked list. Have the procedure take as arguments a pointer to the list entry to be inserted (of type struct entry as defined in chapter), and a pointer to an element after which the new entry is to be inserted.

I've been struggling through this book but this exercise only took me a few minutes, I'm concerned I'm missing the point. Can you please make some suggestions regarding if I've gone wrong?

It compiles and runs fine.

Could I have done this better?

#include <stdio.h>

struct entry
    {
        int value;
        struct entry *next;
    };

void insertEntry(struct entry *addOn, struct entry *element);

int main (void)
{

    struct entry n1, n2, n3, addOn;
    struct entry *list_pointer = &n1;

    n1.value = 100;
    n1.next = &n2;

    n2.value = 200;
    n2.next = &n3;

    n3.value = 300;
    n3.next = (struct entry *) 0;

    while(list_pointer != (struct entry *) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }

    list_pointer = &n1;
    insertEntry(&addOn, &n3);

    while(list_pointer != (struct entry *) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }

    return 0;
}

void insertEntry(struct entry *addOn, struct entry *element)
{
    element->next = addOn;
    addOn->value = 400;
    addOn->next = (struct entry *) 0;
}


texts:
I'm generating domains with random names. I used the map function because it packages the results into a list which I can then join() into a string but the way I used the lambda function could be confusing to people reading this later.

def generateHost():
  charSet = 'abcdefghijklmnopqrstuvwxyz1234567890'
  minLength = 5
  maxLength = 30
  length = random.randint(minLength, maxLength)

  return ''.join(map(lambda unused : random.choice(charSet), range(length)))+".com"

This function calls generateHost() 'size' times and creates an array of hosts. I could write it like the above but it would be the same problem. I wrote it with a for loop which I'm still not satisfied with.

def generateHostList(size):
  result = []
  for i in range(size):
    result += [generateHost()]
  return result


texts: Program to count the number of lines of code

texts:
I need to get this program reviewed. It is counting the lines of code in all files in the
given directory.

I'm new to python and need some advice on pretty much everything.

#!/usr/bin/python
import os
import sys

def CountFile(f):
    counter = 0
    f = open(f, "r")
    for line in f.read().split('\n'):
        counter = counter + 1
    f.close()
    return counter

def CountDir(dirname):
    counter = 0
    for f in os.listdir(dirname):
        fa = os.path.join(dirname, f)
        if os.path.isdir(fa):
            dcount = CountDir(fa)
            counter = counter + dcount
        else:
            fcount = CountFile(fa)
            counter = counter + fcount
    return counter

print CountDir(sys.argv[1])


texts:
Will you review the syntax, structure, and logic of my code. It can be tested using the main.

using iTextSharp.text.pdf;
using iTextSharp.text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AddCopyRightPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            string PDFPath = "D:\\SamplePDF\\SamplePDF.PDF";
            string PDFPathUpdated = "D:\\SamplePDF\\SamplePDFUpdated.PDF";

            byte[] b = AddCopyrighttoPDF(PDFPath);

            System.IO.File.WriteAllBytes(PDFPathUpdated, b);

        }

        public static byte[] AddCopyrighttoPDF(string path)
        {
            byte[] b = null;
            string CopyRighText;
            try
            {

                CopyRighText = "Copyright © " + DateTime.Now.Year + " All Rights Reserved.";
                PdfStamper pdfStamper = null;
                PdfReader pdfReader = null;
                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        pdfReader = new PdfReader(new RandomAccessFileOrArray(path), System.Text.ASCIIEncoding.UTF8.GetBytes("1111"));
                        pdfStamper = new PdfStamper(pdfReader, ms);
                        for (int i = 1; i <= pdfReader.NumberOfPages; i++)
                        {
                            if (i > 1)
                            {
                                Rectangle pageSizeWithRotation = pdfReader.GetPageSizeWithRotation(i);
                                PdfContentByte overContent = pdfStamper.GetOverContent(i);
                                overContent.BeginText();
                                BaseFont baseFont = BaseFont.CreateFont("Helvetica", "Cp1250", false);
                                overContent.SetFontAndSize(baseFont, 7F);
                                overContent.SetRGBColorFill(0, 0, 0);
                                float n2 = 15F;
                                float n3 = pageSizeWithRotation.Height - 10F;
                                overContent.ShowTextAligned(0, CopyRighText, n2, n3, 0F);
                                overContent.EndText();

                            }
                        }

                        pdfStamper.FormFlattening = true;
                        pdfStamper.Close();
                        b = ms.ToArray();

                        ms.Flush();
                        ms.Close();
                    }
                }
                catch
                {
                    b = null;
                }
                finally
                {
                    if (pdfReader != null) { pdfReader.Close(); }
                }
            }
            catch { b = null; }
            return b;

        }
    }
}


texts:
I built this code as part of a test project that was given to me by a company. They had given me a .csv file that contained over 9000 records and wanted me to build a program that would upload it to Firebase.
Firebase has limits on how much data can be uploaded at one time, so uploading a large .json file would not have been possible (I know this cause I tried).
Tried my luck with promises also- not sure if I did that right, but the program worked lol.
The code below works just fine, but I feel as though I could do better- perhaps make it cleaner?
I was working with Typescript for the first time. So if anyone has any tips on this please let me know. Typescript and I are not friends.
Tell me your thoughts please!
#!/usr/bin/env node

import csv from 'csvtojson';
import program from 'commander';
import * as fs from 'fs';
import * as path from 'path';
import * as firebase from 'firebase';
import firebaseConfig from './config';
import { resolve, parse } from 'path';
const ShardingToCsv = require('sharding-to-csv').ShardingToCsv;
const filehound = require('filehound');

// Set up Arguments in Command Line
program
  .version('1.0.0')
  .option('-s, --src <path>', 'Path to .csv file')
  .parse(process.argv);

// Initialize Firebase Config
firebase.initializeApp(firebaseConfig);

// Set DB for Referenced to firebase database
const db = firebase.database();

// If No DB Connection- let me know.
if (!db) {
  console.log('No Database Detected');
}

// Because the .CSV file is to large to parse and upload, break it into 10 different pieces.
const shardFiles = () => {
  // Set a Variable for the source path that the user inputs in
  const srcPath = program.src;

  // If no source path is entered, give this error message
  if (!srcPath) {
    console.log('Please provide valid path to .csv File');
  }

  // a Promise!
  return new Promise((resolve, reject) => {
    console.log('starting sharding process....');
    // Shard Larger .csv Files to Smaller versions for Firebase upload
    var sharding = new ShardingToCsv(srcPath, {
      encoding: 'iso-8859-1',
      maxFileSize: 1000000,
    }).shard();
    sharding.on('error', (err: any) => console.log(err), reject);
    sharding.on('completed', () => {
      console.log('Done Sharding, not to be confused with sharting!');
      // resolve promise
      resolve(sharding);
    });
  });
};

const fromDir = async () => {
  // Await the sharding of the files
  await shardFiles();

  // Actions to create .json files for each shard.

  // variable for shard directory
  // Change this Directory per your application

  const dir = './utils';
  // Read Shard Directory
  const files: any = fs.readdirSync(dir);
  // Interate over the Files
  for (const file of files) {
    const rawData: any = file;
    try {
      // Parse .csv shards into json files using csvtojson
      await csv()
        .fromFile(`utils/${rawData}`)
        .then((data) => {
          fs.writeFile(
            `./utils/${file}.json`,
            JSON.stringify(data, null, 4),
            (err) => {
              if (err) {
                throw err;
              }
              console.log(`created json file with ${file} name`);
            }
          );
        });
    } catch (err) {
      console.log(err);
    }
  }
};

// New Function to upload to database
const uploadToDatabase = async () => {
  // await creation of .json files
  await fromDir();

  filehound
    .create()
    .paths('./utils')
    .ext('.json')
    .find((err: any, jsonFiles: any) => {
      if (err) {
        return console.log(err);
      }
      const readFile = jsonFiles.map((jsonFile: any) => {
        const dbItem = jsonFile;
        const item: any = fs.readFileSync(dbItem);
        const parsedItem = JSON.parse(item);
        // console.log(parsedItem);

        firebase.database().ref('funds').set({ parsedItem });
        console.log('uploaded to database!');
      });
    });
};

uploadToDatabase();


texts: Initializing local variable to generic interface

texts:
Below is my working code written as an exercise in wildcards in generics and Java 8 type inference.  My question will be about the commented line in union() method.

I needed to create an instance of the interface type that does not include a static factory, so I was left with (seemingly) two choices:

Use concrete implementation (as in my code below)
Use Reflection to retrieve the actual run-time class and call its constructor (similar to my earlier question).

I chose to use the first approach and used a constructor of a concrete class HashSet<E> (that implements Set). I picked HashSet among other publicly available implementations rather arbitrarily.

My reasoning was that any would suffice, since it will be returned by a method as just Set<E> and, though it will retain its HashSet-specific members, they will not interfere with a client process.

Was my decision safe and sound or is there a legitimate way to break my method code?

import java.util.*;

public class TypeInference {

    public static <E> Set<E> union (Set<? extends E> s1, Set<? extends E> s2) {
        Set<E> result = new HashSet<E>();  // or any other concrete Set
        result.addAll(s1);
        result.addAll(s2);
        return result;
    }

    public static void main(String[] args) {

        Set<Integer> ints = new TreeSet<>(Arrays.asList(1, 2, 3, 4, 5));
        Set<Double> doubles = new TreeSet<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0));

        Set<Number> numbers = union(ints, doubles);
        System.out.println(numbers);
    }

}


texts:
Can someone review my timer class that runs some code every second, please? The void it's calling (runCode) is just a void with some code in it.

using Reality.Game.Sessions;
using System;
using System.Threading;

namespace Reality.Game.Misc
{
    public static class UserTimer
    {
        public static void Initialize()
        {
                /* Lets rev this bad boy up... */
            Timer timer = new Timer(callback, "Some state", TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
        }

        private static void callback(object state)
        {
            foreach (Session s in SessionManager.Sessions.Values)
            {
                if (s != null && s.Authenticated && !s.Stopped)
                {
                    workTimer(s);
                }
            }
        }

        private static void workTimer(Session s)
        {
            JobCacheWorker.runCode(s);
        }
    }
}


texts:
I have been using the following function (in the kohana html class in a table) to generate tables.

function table($columns,$reverse=false,$fill=false,array $attr=null){
    $c = '';
    //ugly hack, looking for fix
    $max=sizeof(max($columns));
    for($i=0;$i<sizeof($columns);$i++){
            $column = $columns[$i];

        if($fill==true){
            $l = ($max-sizeof($column));
            for($ii=0;$ii<$l;$ii++){
                array_push($column,'');
            }
        }
        if($reverse==true){
            $columns[$i] = array_reverse($column);
        }else{
            $columns[$i] = $column;
        }
    }
    for($i=0,$l=sizeof($columns);$i<$l;$i++){
        $column = $columns[$i];
        $c.="
";
        for($ii=0,$ll=sizeof($column);$ii<$ll;$ii++){
            $c.="".$column[$ii]."	";
        }
        $c.="
";
    }
    return "
".$c."
";
}

And then I have been calling it like so:

echo html::table(array(
    array('colunm 1 row 1','colunm 2 row 1'),
));

And a reversed table that auto fills the columns.

echo html::table(array(
    array('colunm 1 row 1','colunm 2 row 1'),
    array('column 1 row 2','column 2 row 2')
),true,true);


texts: Vector-based flood-fill algorithm queue class

texts:
I want to implement the flood-fill algorithm for https://stackoverflow.com/questions/12995378/is-there-a-proper-algorithm-for-detecting-the-background-color-of-a-figure. I did it recursively, but I had a stack-overflow error. No matter - Wikipedia has a spot for a non-recursive, iterative solution.

It requires a queue. For school, we're not supposed to use Lists nor the Java Queue class (I don't even know if it does what I think it does, but it doesn't matter - I can't use it).

public class QueueOfPixeles
{
    public Pixel[] elements;
    public int numberOfElements;

    public QueueOfPixeles()
    {
        numberOfElements = 0;
        elements = new Pixel[1];
    }

    // Next pixel is supposed to return the last pixel element in the queue.
    // When a pixel element is returned, it will become null in the system.
    public Pixel nextPixel() {
        Pixel result = null;
        for (int i = elements.length - 1; i >= 0 && result == null; --i) {
            result = elements[i];
            if (result != null) {
                elements[i] = null;
            }
        }
        return result;
    }

    // Adds a new pixel to the queue.
    // Then, it checks if the capacity of the vector has been reached.
    public void add(Pixel pixel) {
        elements[numberOfElements] = pixel;
        ++numberOfElements;
        fixVector();
    }

    // If the vector capacity has been reached, create a new vector with all old elements
    // but with more capacity.
    private void fixVector() {
        if (numberOfElements >= elements.length) {
            Pixel[] newVector = new Pixel[(elements.length * 2) + 1];
            for (int i = 0; i < numberOfElements; ++i) {
                newVector[i] = elements[i];
            }
            elements = newVector;
        }
    }
}

WHAT IS IT SUPPOSED TO DO?

You should be able to add pixels to the end of the queue, and get the next pixel by using nextPixel(). When you retrieve the next pixel, it should be removed from the queue automatically.

DOES IT WORK?

Yes, it seems to be working. I've done a few tests and it has indeed returned all I expected.

WHAT'S THE PROBLEM?

I'd like to get some feedback about this. I can only use vectors for this project, and I feel there is something rather not-efficient with the way I manage the pixels in the queue (converting the elements to null and just that etc, or asking for more capacity size instead of using the null-spaces I made).

What do you think?


texts: Converting colours in an image using Python Imaging Library

texts:
I have written the beginning of a map engine which runs off PIL and some JavaScript client side. Ignoring the rest of the code that is in the same file as this function, can you suggest any improvements to this code here?

def convert_colour(region_number, incolour, outcolour):
    #print(region_list.regions_d[region_number][0].split('\\')[7], incolour, outcolour)
    img = Image.open(region_list.regions_d[region_number][0])
    img = img.convert("RGBA")
    newData = []
    newData = [outcolour if item==incolour else item for item in img.getdata()]
    img.putdata(newData)
    img.save(region_list.regions_d[region_number][0], "PNG")
    colour_change_single(region_number, outcolour)

Further to a suggestion I have tried to include numpy but recieve the following error:

Traceback (most recent call last):
  File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 227, in <module>
    run_function_tests()
  File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 219, in run_function_tests
   run_engine_test(change_list)
  File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 161, in run_engine_test
    convert_colour(x[0], region_list.regions_d[x[0]][1], x[1])
  File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 115, in convert_colour
    new_img = _convert_colour(img, incolour, outcolour)
  File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 108, in _convert_colour
    img[_colour_mask(img, incolour)] = outcolour
ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing result of shape (216,4)

I realised there needs maybe some clarity about this traceback.
run_function_tests() this has code to run a short test with my old code.

def run_engine_test(change_list):
for x in change_list:
    convert_colour(x[0], region_list.regions_d[x[0]][1], x[1])

change_list = [(n,random.choice(colour_list.colour_list)) for n in region_list.regions_d]

We also have a function called colour detect which will check for patterns in the colour

def colour_detect():
#Detect if colours in the image match the colours on the palette and re-maps the dictionary if a region colour is changed
    detected_colours = []
        for x in region_list.regions_d:
            region_colour = print_img_data(region_list.regions_d[x][0])
            region_list.regions_d[x] = [region_list.regions_d[x][0], region_colour]
        if region_colour not in detected_colours:
            detected_colours.append(region_colour)

This is intended to be run at the beginnig of a "game or round" and then in between the engine ticks when actions like wars are comitted. Hence why it checks all of the images to ensure that the dictionary has been updated correctly.

After that the traceback comes from your functions.

[Edit]
The error was related to a typo in my code. The suggestion provided reduced the time to do the functions by 2/3rds!!!!

This is the image i am editing (c)


texts: Batch rename files recursively, and number the directory index

texts:
When dealing with iOS app bundle, It is not convenient to get the file by its path, but loading it by its name.

Need to batch rename images recursively, with Mac Bash. And to make the name unique, the directory index should be numbered.

To rename files ,turn

Root----A----0.png
|       |
|        ----C----9.png
|
 -------B----0.png
|
 -------0.png
|
 -------0.sh

to

Root----A----1_0.png
|       |
|        ----C----3_9.png
|
 -------B----2_0.png
|
 -------0_0.png
|
 -------0.sh

Just to rename the .png files. Keep the other file's name before.

Here is my code, it is ok to deal with the situation that dir A has a name of spacing.

 n=0
rename(){
    varN=$n
    for f in * ; do
        if [[ -f $f ]]; then
            extension="${f##*.}"
            if [[ $extension == "png" ]]; then
                mv "$f" $n"_$f"
                (( varN++ ))
            fi
        fi
    done
    if (( $varN > $n )); then
        ((n++))
    fi
    for d in */ ; do
    ( cd "$d" && rename)
    (( n++ ))
    done
}

rename

Any way to make it more brilliant?


texts: Merging two dictionaries together whilst adding keys but multiplying values

texts:
I have two dictionaries and a merged dictionary:

dict1 = {-3: 0.3, -2: 0.1, 1: 0.8}
dict2 = {0: 0.3, 1: 0.5, -1: 0.7}
dict_merged = {}

I have code that basically merges the two together by adding keys together and multiplying values:
e.g.

for k1, v1 in dict1.items():
   for k2, v2 in dict2.items():
      new_key = k1 + k2
      if new_key in dict_merged:
          dict_merged[new_key] += v1 * v2
      else:
          dict_merged[new_key] = v1 * v2

Is there a faster way to do this, it feels like there should but dict comprehension doesn't seem helpful here. In the above example, we are going to get several contributes to the key "-3" for example.


texts:
I have +-645 IRL links I need to validate. The code below is my attempt, but my problem is that it takes forever to check all links and sometimes times out. Is there a better way of validating so many links?

index.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$notValid = [];

// This array contains +-645 url in this array, http://www.example.com is just for example purposes.
$companyData = ['http://www.example.com','http://www.example.com', 'http://www.example.com', 'http://www.example.com'];
// Basic structure of $companyData array

Array
(
    [0] => Array
        (
            [Name] => Name-Ltd
            [Code] => XYZ
            [Url] => http://www.example.co.za/example-click-a-company/Name-Ltd
        )

    [1] => Array
        (
            [[Name] => Name-Ltd
            [Code] => ZXY
            [Url] => http://www.example.co.za/example-click-a-company/Name-Ltd
        )

    [2] => Array
        (
            [Name] => Name-Ltd
            [Code] => ZYX
            [Url] => http://www.example.co.za/example-click-a-company/Name-Ltd
        )

    [3] => Array
        (
            [Name] => Name-Ltd
            [Code] => YZX
            [Url] => http://www.example.co.za/example-click-a-company/Name-Ltd
        )

    [4] => Array
        (
            [Name] => Name-Ltd
            [Code] => XZY
            [Url] => http://www.example.co.za/example-click-a-company/Name-Ltd

)

// This is to loop through all url's
for ($i=0; $i < count($companyData); $i++)
{
    $url = $companyData[$i]['Url'];

    $headers = get_headers($url, 1);

    if(@$headers['Content-Length'] == 1153)
    {
        $exists = 'not valid';

        $notValid[$i] = $companyData[$i]['Url'];
    }
    else
    {
        $exists = 'valid';
    }
}

foreach ($notValid as $not)
{
    echo "The following URL's need your attention: <br>";
    echo $not;
}

?>