texts: Export Hero information and list of his items to excel sheet/csv

texts:
I created simple export tool for my project. My requirments was to create one csv file for details of my hero which contains name, level, gold etc. And second file for list of items.
Both of files contains static header and generated Data.
First, let me share my model classes:
public class Hero {
    private String name;
    private int level;
    private List<Item> items = new ArrayList();
    private String className;
    private BigDecimal gold;

//getters setters constructors
}

public class Item {

    private int id;
    private String name;
    private double weight;
//getters setters constructors
}

public class Weapon extends Item {

    private int dmg;
    private int level;
//getters setters constructors
}

public class Food extends Item {

    private int capacity;
    private int hpRegen;
//getters setters constructors
}

I wont share real classes, because they are a little too big, so I have prepared sample classes.
And here we go with example 'exporter'. This class has two public methods which return CSVWriter which we can use to save data to file.
public class HeroWriter {

    private Hero hero;

    private final static String[] HERO_INFO_HEADER = {
            "server",
            "date",
            "name",
            "class",
            "level",
            "gold"
    };

    private final static String[] ITEM_LIST_HEADER = {
            "id",
            "name",
            "weight",
            "dmg",
            "hp",
            "required level",
            "capacity"
    };

    public HeroWriter(Hero hero) {
        this.hero = hero;
    }

    public CSVWriter writeHeroInformation() {
        CSVWriter writer = new CSVWriter(null);
        writer.writeNext(HERO_INFO_HEADER);

        String[] heroInformation = {
                "Mocked Server",
                new Date().toString(),
                hero.getName(),
                hero.getClassName(),
                hero.getLevel()+"",
                hero.getGold().toString()
        };

        writer.writeNext(heroInformation);

        return writer;
    }

    public CSVWriter writeItemList() {
        CSVWriter writer = new CSVWriter(null);
        writer.writeNext(ITEM_LIST_HEADER);

        for (Item item : hero.getItems()) {
            if(item instanceof Weapon) {
                Weapon weapon = (Weapon) item;

                String[] weaponDetail = {
                        weapon.getId() + "",
                        weapon.getName(),
                        weapon.getWeight() + "",
                        weapon.getDmg() + "",
                        "-",
                        weapon.getLevel() + "",
                        "-"
                };
                writer.writeNext(weaponDetail);

            } else if (item instanceof Food) {
                Food food = (Food) item;

                String[] foodDetail = {
                        food.getId() + "",
                        food.getName(),
                        food.getWeight() + "",
                        "-",
                        food.getHpRegen() + "",
                        "-",
                        food.getCapacity() + ""
                };
                writer.writeNext(foodDetail);
            }
        }

        return writer;
    }
}

I would like to as you to review HeroWriter class, because I have problem with OOP and would like to improve in this aspect.
I was thinking that maybe I could create Exportable interface which contains method like String[] export(); and I would implement it in Hero/Weapon/Item class that would help me remove instanceof part of code. But I am not sure if it is good idea.


texts:
I wrote this interpreter for a code challenge. Can this be written any cleaner/smaller? Could I reduce the amount of nested conditional/loops?

def brain_luck(code, input)
  output = ''
  cp = 0 # code pointer
  dp = 0 # data pointer
  ip = 0 # input pointer
  data = Array.new(10, 0)
  while cp < code.length
    case code[cp]
    when '>'
      dp += 1
      if dp == data.length
        data.push(0)
      end
    when '<'
      dp -= 1
      if dp == -1
        dp = 0
        data.unshift(0)
      end
    when '+'
      data[dp] = (data[dp].ord+1)%256
    when '-'
      data[dp] = (data[dp].ord-1)%256
    when '.'
      output += data[dp].chr
    when ','
      data[dp] = input[ip].ord
      ip += 1
    when '['
      if data[dp] == 0
        nest_count = 1
        while nest_count > 0
          case code[cp += 1]
          when '[' then nest_count += 1
          when ']' then nest_count -= 1
          end
        end
      end
    when ']'
      if data[dp] != 0
        nest_count = 1
        while nest_count > 0
          case code[cp -= 1]
          when ']' then nest_count += 1
          when '[' then nest_count -= 1
          end
        end
      end
    end
    cp += 1
  end
  output
end


texts: Singly Linked List Implementation (With Nodes)

texts:
This code was recommended to me by my dear friend Jon after I wrote an implementation using arrays. With his help, I managed to create a Singly linked List similar to std::vector using Nodes.

#include <iostream>

template <class T>
class LinkedList
{
private:
    size_t _size;
public:

    class Node
    {
    public:
        Node* next;
        T value;
        Node(T val) : value(val), next(NULL) {}
    };

    Node* head;

    LinkedList() : _size(0), head(NULL) {}

    ~LinkedList() {
        std::cout << "Linked List Deleted!" << std::endl;
    }

    void push(T val) {
        Node* node = new Node(val);
        node->next = head;
        head = node;
        ++_size;
    }
    size_t size() {
        return _size;
    }
    bool empty() const {
        return head == NULL;
    }
    T pop() {
        Node* n = head;
        if (n == NULL) return NULL;
        head = n->next;
        _size--;
        return n->value;

    }
};

int main() {
    LinkedList<int> list;
    std::cout << "Empty: " << list.empty() << std::endl;
    list.push(5);
    list.push(6);
    list.push(7);
    list.push(8);
    list.push(9);
    list.push(10);
    std::cout << "Empty: " << list.empty() << std::endl;

    std::cout << "Size: " << list.size() << std::endl;
    list.pop();

    std::cout << "Size: " << list.size() << std::endl;
    LinkedList<int>::Node* n = list.head;
    while (n != NULL) {
        std::cout << n->value << std::endl;
        n = n->next;
    }
}


texts: Finding the sum of all the multiples of 3 or 5 below 1000, using list comprehension

texts:
I'm trying to compare my own implementation with another solution of Project Euler problem #1, which uses a list comprehension:

module Progression1 (sumProgressions) where
    import Prelude

    sumProgressions :: Integer -> Integer -> Integer -> Integer
    sumProgressions d1 d2 limit =
        sum [n | n <- [1 .. limit], (n `mod` d1) == 0 || (n `mod` d2) == 0]

Mine is directly inspired by user nicocarlos' PHP solution on the PE site. It avoids using hard-coded constants, instead computing most of the values (with as much algebraic simplification as possible):

module Progression2 (sumProgressions2) where
    aN               :: Integer -> Integer -> Integer -> Integer
    pSum             :: Integer -> Integer -> Integer -> Integer
    sumProgressions2 :: Integer -> Integer -> Integer -> Integer

    aN a1 d n = a1 + (n - 1) * d  -- Calculating the value of the Nth term

    pSum 0  d lim  = pSum d d lim -- a1 == 0 produces invalid pSum() result
    pSum a1 d lim =
        let n1 = (lim `div` d)            -- Using simplified method for finding n
            n2 = ((lim - a1) `div` d + 1) -- Use non-simplified formula for calculation
        in if (a1 == d)
            then (d * n1 * (n1 + 1)) `div` 2      -- Assumes n1 is simplified
            else (n2 `div` 2) * (a1 + aN a1 d n2) -- Non-simplified calculation

    sumProgressions2 d1 d2 lim = let d3 = d1 * d2
        in (pSum d1 d1 lim) + (pSum d2 d2 lim) - (pSum d3 d3 lim)

I'm new to Haskell and inexperienced with functional programming; I'd like suggestions for improving this code's performance and style.

Currently criterion is showing similar mean benchmark times for each solution, calculated for d1 = 3, d2 = 5, limit = 100000-1.

Updated with current code:

This solves the bug mentioned in the accepted answer, and takes much of its advice on style (as well as discarding the simplified algebra.)

-- Using arithmetic progression formula for the Nth element aN, we can determine
-- the value aN = a1 + (N - 1) * d. Rearranging yields N = (aN - a1) / d + 1.
-- Calculates N, then the last aN, and uses it to find S = (N / 2) * (start + last)
pSum 0     diff limit = pSum diff diff limit
pSum start diff limit = truncate ((fromIntegral n / 2) * fromIntegral(start + last))
    where n    = (limit - start) `div` diff + 1
          last = start + (n - 1) * diff

-- Add the sums of two progressions and subtract sum of similar elements
sumProgressions2 :: Integer -> Integer -> Integer -> Integer
sumProgressions2 diff1 diff2 limit =
    (pSum 0 diff1 limit) + (pSum 0 diff2 limit) - (pSum 0 diff3 limit)
        where diff3 = lcm diff1 diff2


texts:
Please can you review my standard exception handler for Python 3.x. It is located under the # +=+= line. The code above the line is to create an exception and so the code is code complete and runs standalone.
The code is just a standard exception formatter, so users are presented with easier to read messages rather than stack traces. This is a common idiom in many Python projects. But many / all don't format to the extent I have.
I have searched a lot, but I can't find anything better. I expected to find something on GitHub, but was unfruitful. If you find a way to improve this, please post it here so that I and others will know.
import inspect
import os
import sys
import traceback

if __name__ == '__main__':
    try:
        x = 42/0

    # +=+=+=+=+=+=+=+=+=+=+=+=+=
    except KeyboardInterrupt as e: # Ctrl-C
        raise e
    except SystemExit as e: # sys.exit()
        raise e
    except Exception as e :
        exc_type, exc_obj, exc_tb = sys.exc_info()
        scriptName = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        functionName = inspect.currentframe().f_code.co_name
        print('=======================================================================================================')
        print('Unhandled exception: ', exc_type, scriptName, 'at line', exc_tb.tb_lineno)
        print('                      in function', functionName)
        print('                     ', str(e))

        traceback.print_exc()
        sys.exit(1)


texts: Which way should I use while writing this method?

texts:
I've got a homework that is about methods. So first part is

  Write a method that prompts the customer for the car type. There are
  three acceptable car types (E: Economy, M: Midsize, F: Fullsize). Your
  method will return a valid car type.

But the thing that I don't understand is, should I read input from the user first and then make the method give a valid car type, or should method also read from user?

char type;
System.out.println("(E) Economy  - 50 TL");
System.out.println("(M) Midsize  - 70 TL");
System.out.println("(F) Fullsize - 100 TL");
do{
    System.out.println("Enter the car type (E/M/F) : ");
    type = input.next().charAt(0);
    type = Character.toUpperCase(type);
} while (type != 'E' && type != 'M' && type != 'F' );
carType(type);

and;

public static String carType(char y){

    String x ="";
    if(y == 'E')
        x = "Economy";
    if(y == 'M')
        x = "Midsize";
    if(y == 'F')
        x = "Full size";
    return x;

Do you think this is the right way to do it? Because it says "Write a method that prompts the user..." but what's the point of using method if I move all of the code above into method?


texts:
Q: Write a method that transforms a list into an array (don't use
  collections or already implemented methods in lists, make your own
  method)

I've come with this solution:

public static Object[] toArray(List<Object> list) {

    Object[] arr = new Object[list.size()];
    for (int i = 0; i < list.size(); ++i) {
        arr[i] = list.get(i);
    }
    return arr;
}

I've read this Convert a generic list to an array, and seems like they overcomplicated the solution. Why they choose to use generics? Is there something wrong with my approach?


texts: Adding/removing map values: unsymmetric implementation

texts:
I am learning Clojure by implementing a simplistic resource reservation system. At its core are the two functions for placing/canceling reservations for a given resource:

; thread-safe map of {resource -> #{reservations}}
(def known-reservations (atom {}))

(defn place-reservation
  [new-res]
  (swap! known-reservations
         #(merge-with clojure.set/union % {(:resource new-res) #{new-res}})))

(defn cancel-reservation
  [canceled-res]
  (swap! known-reservations
         #(update % (:resource canceled-res) disj canceled-res)))

They seem to work correctly, but the lack of symmetry bothers me. Placing and canceling reservations are symmetric operations, but this is not reflected by the above code: merge-with clojure.set/union doesn't even resemble update ,,, disj.

I tried the following variant:

(defn place-reservation
  [new-res]
  (swap! known-reservations
         #(update % (:resource new-res) conj new-res)))

but since conj nil :x returns a list rather than a set, this leads to duplicate reservations which I want to prevent.

What is the most idiomatic fix to my problem?

PS: if anyone can come up with a more expressive question title, I'll thankfully accept the edit!

edit: here's a simple usage example for experimentation:

(defrecord Resource [name])
(defrecord Reservation [^Resource resource user])

(def car (->Resource "car"))
(def my-res (->Reservation car "me"))
(def your-res (->Reservation car "you"))

(place-reservation my-res)
(place-reservation your-res)
(place-reservation my-res) ;; duplicate reservation must not change anything

(cancel-reservation my-res)


texts:
I'm practicing my C coding and I wanted to implement my own version of the getline function in C for learning purposes. I'd like a review on coding style, correctness, improvements I can make for performance, and overall quality of the code. My main concerns are correctness and performance (in that order).

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_LINE_LENGTH 255

/* Retrieves a line of text from the stream provided
 * and places it into @buf until a new line character is
 * reached or the number of characters read is > @size - 1.
 * This function will null-terminate the provided buffer.
 *
 * @param[in] -- stream -- the stream
 * @param[in] -- buf -- a buffer big enough for @size chars.
 * @param[in] -- size -- the maximum number of chars to read (must
 *    include room for a null terminator
 * @return -- the number of characters read from the stream.
 */
size_t getline(FILE *stream, char *buf, size_t size)
{
    size_t count = 0;
    char c;
    while ((c = (char)getc(stream)) != '\n' && count < size - 1) {
        buf[count++] = c;
    }
    buf[count] = '\0';
    return count;
}

int main()
{
   char line[MAX_LINE_LENGTH];
   while (true) {
       size_t count = getline(stdin, line, MAX_LINE_LENGTH);
       printf("The line gotten was \"%s\" and was %zu chars long.\n", line, count);
   }
}


texts: Action to transmit queued messages over a socket

texts:
I have this action and it works but looks rather clunky to me. Is there any way I could improve that?

transMit :: Serialize a => Socket -> POSIXTime -> KEY -> a -> TPSQ -> TMap a -> IO ()
transMit s time key newmsgs q m = do
     loopAction <- atomically $ do
                       mT <- readTVar m
                       qT <- readTVar q
                       let (a, b) = key  -- extract IPv4 address a and protocolID b from KEY
                       let mT' = Map.delete key mT
                       let qT' = PSQ.delete key qT
                       writeTVar q (PSQ.insert key time qT')
                       writeTVar m (Map.insert key [newmsgs] mT')
                       case b of
                              11 -> return $ case Map.lookup key mT of
                                                  Nothing -> return ()
                                                  Just messages -> sendq s (B.snoc (S.encode messages) b ) (show a) 4711
                              72 -> return $ case Map.lookup key mT of
                                                  Nothing -> return ()
                                                  Just messages -> sendqr s (B.snoc (S.encode messages) b ) (show a) 4711

     loopAction


texts: Counting occurrences of substring in string

texts:
I need to know how many times a substring occurs in a given string.  I figured that I might as well create an extension method:

public static int Occurences(this string str, string val)
{
    string copy = str;

    int instancesOf = 0;
    int indexOfVal;

    while ((indexOfVal = copy.IndexOf(val)) != -1)
    {
        copy = copy.Remove(indexOfVal, val.Count());
        instancesOf++;
    }

    return instancesOf;
}

I'm not sure that the assignment in the while loop is good practice.  Should I change this to compute the value once outside the loop, and once in the loop, like this?

int indexOfVal = copy.IndexOf(val);

while (indexOfVal != -1)
{
    copy = copy.Remove(indexOfVal, val.Count());
    instancesOf++;
    indexOfVal = copy.IndexOf(val);
}

Any and all comments appreciated, the more the better.


texts:
My co-worker claims that using a parameterized Like statement is equivalent to dynamic sql and won't have its execution plan cached for reuse. He says that using sp_executesql will allow the execution plan to be cached, increasing the performance of identical searches. However, in the context of this query, the argument doesn't seem to make sense.

Any way to prove one way or the other?

CREATE PROCEDURE [dbo].[SP_Get_Person]
        @SearchText varchar(50)
AS
BEGIN
        SET NOCOUNT ON;

        ------------------------------------------------------------------------------------
        Declare @SQLString nvarchar(500)
        Declare @ParmDefinition nvarchar(500)
        SET @ParmDefinition = N'@SearchText varchar(50)';

        SET @SQLString = N'Select * FROM PERSON Where LASTNAME Like ''%'' + @SearchText + ''%''';

        EXECUTE sp_executesql @SQLString, @ParmDefinition,
                              @SearchText = @SearchText;
        ------------------------------------------------------------------------------------

        --OR

        ------------------------------------------------------------------------------------
        Select * FROM PERSON Where LASTNAME Like '%' + @SearchText + '%'
        ------------------------------------------------------------------------------------
END


texts: Hacking Ruby Hash: Fastest #to_struct method

texts:
I am trying to make the fastest #to_struct method in Ruby's Hash.

I am including a use case and benchmark so you can run and see if you have really improved the code.

This is my implementation and the benchmark is included. The time at the bottom is the time it takes on my machine. How can I make this faster?

require "json"
require 'benchmark'
require 'bigdecimal/math'

class Hash
  def to_struct
    k = self.keys
    klass = k.map(&:to_s).sort_by {|word| word.downcase}.join.capitalize
    begin
      Kernel.const_get("Struct::" + klass).new(*self.values_at(*k))
    rescue NameError
      Struct.new(klass, *(k)).new(*self.values_at(*k))
    end
  end
end

# You have a hash that you have built in your app
sample_hash = {
  foo_key: "foo_val",
  bar_key: "bar_val",
  baz_key: "baz_val",
  foo1_key: "foo_val",
  bar1_key: "bar_val",
  baz1_key: "baz_val",
  foo2_key: "foo_val",
  bar2_key: "bar_val",
  baz2_key: "baz_val",
  foo3_key: "foo_val",
  bar3_key: "bar_val",
  baz3_key: "baz_val",
  foo4_key: "foo_val",
  bar4_key: "bar_val",
  baz4_key: "baz_val",
  foo5_key: "foo_val",
  bar5_key: "bar_val",
  baz5_key: "baz_val",
  foo6_key: "foo_val",
  bar6_key: "bar_val",
  baz6_key: "baz_val",
  foo7_key: "foo_val",
  bar7_key: "bar_val",
  baz7_key: "baz_val",
}

# Then you have JSON coming from some external api
json_response = "{\"qux_key\":\"qux_val\",\"quux_key\":\"quux_val\",\"corge_key\":\"corge_val\"}"
hash_with_unknown_keys = JSON.parse(json_response)

# Merge these two together
sample_hash.merge!(hash_with_unknown_keys)

iterations = 100_000

Benchmark.bm do |bm|
  bm.report "#to_struct" do
    iterations.times do
      # Would be super nice if I could convert this to a struct with a method
      # Somehow a bit faster than the explicit example below and much faster than open struct
      sample_struct = sample_hash.to_struct
      unless sample_struct.foo_key == "foo_val"
        raise "Wrong value"
      end
    end
  end

  bm.report "Struct" do
    iterations.times do
      sample_struct = Struct.new(*sample_hash.keys)
        .new(*sample_hash.values)
      unless sample_struct.foo_key == "foo_val"
        raise "Wrong value"
      end
    end
  end

  bm.report "OpenStruct" do
    iterations.times do
      sample_open_struct = OpenStruct.new(sample_hash)
      unless sample_open_struct.foo_key  == "foo_val"
        raise "Wrong value"
      end
    end
  end
end

#       user     system      total        real
# #to_struct  4.030000   0.010000   4.040000 (  4.072031)
#     Struct  6.870000   0.290000   7.160000 (  7.320459)
# OpenStruct 23.550000   0.210000  23.760000 ( 23.895187)


texts:
I have recently coded my own authentication system and wondered if there was any way I could make it better? I coded it with Laravel 5.4. getView is called on Route::get and onPost is called on Route::post

use Auth;
use App\User;
use App\Http\Controllers\Controller;
use Validator;
use Redirect;
use Illuminate\Http\Request;
use App\Database\Frontend\User\Player;
use App\Database\Frontend\WebsiteLogin;

class LoginController extends Controller
{
    public function getView()
    {
        return view('frontend.login');
    }

    public function onPost(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mail'     => 'required|email|exists:users',
            'password'  => 'required'
        ]);

        if ( $validator->fails()) {
            return Redirect::to('/login')->withErrors($validator->messages());
        }
        else {
            if (!Auth::attempt(['mail' => $request->input('mail'), 'password' => $request->input('password')])) {
                $this->addNewWebsiteLogin($request, Player::where('mail', $request->input('mail'))->pluck('id')->first(), "0");
                return Redirect::to('/login')->withMessage('Email and password do not match')->withColor('danger');
            }
            else {
                $this->addNewWebsiteLogin($request, Auth::user()->id, "1");

                $user = Auth::user();
                $user->last_online = time();
                $user->save();

                if (config('frontend.government_only') && (Auth::Guest() || Auth::user()->roleplay->government_id == 0)) {
                    Auth::logout();
                    return Redirect::to('/login')->withMessage(config('frontend.site_name') . ' is only open to government individuals at this moment, too bad.')->withColor('danger');
                }

                return Redirect::to('/home')->withMessage('Welcome back!');
            }
        }
    }

    private function addNewWebsiteLogin(Request $request, $userId, $status) {
        $websiteLogin                    = new WebsiteLogin;
        $websiteLogin->user_id           = $userId;
        $websiteLogin->request_ip        = $request->ip();
        $websiteLogin->request_system    = 'TODO';
        $websiteLogin->request_browser   = 'TODO';
        $websiteLogin->login_status      = $status;
        $websiteLogin->save();
    }
}


texts: Efficiency of grouping a List of case classes by more than one field

texts:
I have the following input:

case class Client(key: String, time: Option[Instant], bool: Boolean)
val l = List (
  Client("87658763", Some(Instant.EPOCH), false),
  Client("87658769", Some(Instant.EPOCH), false),
  Client("87658769", Some(Instant.EPOCH), true)
)

For context, this data is the result of concatenated Lists from two API calls - one to get all Clients, and one to specifically get all Clients where bool is true.

I want the info to be distinct on the key and time. Also, where there are multiple Clients with the same key and time, if at least one of the Clients contains bool = true, I want to return a single client with bool = true otherwise return a single client with bool = false ... ie I want the output of above to be:

List (
  Client(87658763,Some(1970-01-01T00:00:00Z),false),
  Client(87658769,Some(1970-01-01T00:00:00Z),true)
)

What I have so far is the following code:

import java.time.Instant

case class Client(key: String, time: Option[Instant], bool: Boolean)

val l = List (
  Client("87658763", Some(Instant.EPOCH), false),
  Client("87658769", Some(Instant.EPOCH), false),
  Client("87658769", Some(Instant.EPOCH), true)
)

l.groupBy(client => (client.key, client.time)).map {
  case (_, v) if v.exists(_.bool) => v.head.copy(bool = true)
  case (_, v) => v.head
}.toList

I am curious about efficiency and code style - this is the only way to solve this problem that I could come up with, but I wonder if there is a more efficient way to do this (I don't know much about what the Scala compiler does under the hood with things like groupBy and copy), or a more elegant way to do this.

I've not had to make elements distinct by more than one field before and this call will be made hundreds of times in my application (I am writing this as part of a Play! app) so need it to be as efficient as possible.


texts: Replace characters using multiple dependent regular expression substitutions

texts:
I've written the following Python module to iterate over field values in the following two fields: "NAME_LABEL", "CATEGORY". I'm using regular expressions in the following function: "correct_invalid_char", to substitute characters over three expressions that are dependent on each other. The first expression replaces the following characters "/-space" with an underscore, the result is then passed onto the second expression to remove non-alphanumeric and non-numeric characters. The last regular expression removes duplicate underscores that were originally in the field values or generated due to the first regular expression.

Is there more Pythonic way of writing the following regular expressions to achieve the same result, that would allow me to write better unit tests for the following function?

Original field values:

OBJECTID,NAME,NAME_LABEL,FACILITY_TYPE,CATEGORY,SHAPE_Length,SHAPE_Area
1,Ward 27 - New 1,Ward 27 - New 1,Settlements,Settlements 2,533.176039669,12288.746516
2,429 (Block R),(Block R) 429,Settlements,Settlements 4,508.411033555,9622.22635621
3,Kondelelani (Block 1),Kondelelani (Block 1),Settlements,Settlements 4,738.203751902,22815.0234794
4,Yebo Gogo,Yebo \ Gogo,Settlements,Settlements 1,674.979301727,23413.6988572
5,Tebogo Bottle Store,Tebogo / Bottle Store,Settlements,Settlements 1,329.239037836,7157.39741934
6,Block 1 Y,Block 1 [Y],Settlements,Settlements 2,1893.89651205,82883.9076782
7,Stand 1427, Ga-Rankuwa X25,Stand_ 1427, Ga-Rankuwa X25,Settlements,Settlements 3,1209.46585836,66852.9597381
8,Stand 1719, Ga-Rankuwa X23,Stand 1719, Ga-Rankuwa X23,Settlements,Settlements 3,997.901714538,51299.0275644

Original values: CSV

Updated field values:

"""
Created on 23 Oct 2018

Remove invalid characters

found in SAA fields values:

NAME_LABEL; CATEGORY

@author: Peter Wilson
"""
# import site-packages and modules
import re
import argparse
import arcpy

# set environment settings
arcpy.env.overwriteOutput = True

def sites_fields_list(sites):
    """
    Validate fields found
    and create list for
    update cursor.
    """
    fields = ['NAME_LABEL', 'CATEGORY']
    sites_fields = [f.name for f in arcpy.ListFields(sites) if f.name in fields]
    return sites_fields

def correct_invalid_char(field_value):
    """
    Correct field values
    by replacing characters,
    removing non-alphanumeric,
    non-numeric characters,
    duplicate underscores,
    and changing to title case.
    """
    try:
        underscore = re.sub('[/\- ]', '_', field_value)
        illegal_char = re.sub('[^0-9a-zA-Z_]+', '', underscore)
        dup_underscore = re.sub(r'(_)+', r'\1', illegal_char)
        update_value = dup_underscore.title()
        return update_value
    except TypeError as e:
        print("There's no value in the field: {0}".format(e))
        raise

def update_field_values(sites):
    """
    Iterate over field values
    in: NAME_LABEL; CATEGORY
    and correct field values
    by replacing characters.
    """
    sites_fields = sites_fields_list(sites)
    with arcpy.da.UpdateCursor(sites, sites_fields) as cursor:
        for row in cursor:
            for idx, val in enumerate(row):
                row[idx] = correct_invalid_char(val)
            cursor.updateRow(row)

if __name__ == '__main__':
    description = 'Remove invalid characters in SAA fields NAME_LABEL and CATEGORY'
    parser = argparse.ArgumentParser(description)
    parser.add_argument('--sites', metavar='path', required=True,
                        help='path to input sites feature class')
    args = parser.parse_args()
    update_field_values(sites=args.sites)


texts:
Improved version of the original question
I've created a simple npm module and CLI program to get the latest GitHub and Bitbucket release from their APIs using Node.js. Please tell me if there's anything to improve!
GitHub
npm
RunKit
Improved module code
#!/usr/bin/env node
const fetch = require("node-fetch");

/**
 * @param {string} string
 * @return {string}
 */
const normalize = (string) => {
    try {
        return string.toUpperCase().trim()
    } catch (e) {
        return string
    }
}

/**
 * @param {string} url
 * @return {string}
 */
const getJSON = async (url) => {
    return (await (await fetch(url)).json())
}

module.exports.providerMethods = {
    GITHUB: async ({user, repo, part = ""}) => {
        let json = await getJSON(`https://api.github.com/repos/${user}/${repo}/releases/latest`)
        if (json.message === "Not Found") throw "Invalid repository"
        if (!("assets" in json)) throw "Rate limit exceeded"
        let browser_download_urls = json.assets.map(asset => asset.browser_download_url)
        return browser_download_urls.filter(url => url.includes(part))
    },
    BITBUCKET: async ({user, repo, part = ""}) => {
        let json = await getJSON(`https://api.bitbucket.org/2.0/repositories/${user}/${repo}/downloads/`)
        if (json.type === "error") throw "Invalid repository"
        let links = json.values.map(value => value.links.self.href)
        return links.filter(url => url.includes(part))
    }
}

/**
 * @param {string} provider
 * @param {string} user
 * @param {string} repo
 * @param {string} part
 */
module.exports.getRelease = async ({provider, user, repo, part = ""}) => {
    if (!(module.exports.providerMethods[normalize(provider)])) {
        throw "Invalid provider"
    }
    return module.exports.providerMethods[normalize(provider)]({user, repo, part})
}

const usage = _ => {
    console.log(
        `Usage: get-release (github|bitbucket) user repo [partofreleasefile]
   Ex: get-release github phhusson treble_experimentations
       get-release github phhusson treble_experimentations arm64-ab-gapps
       get-release bitbucket JesusFreke smali
       get-release bitbucket JesusFreke smali baksmali`
    )
    process.exit(1)
}

// If via CLI
if (require.main === module) {
    let args = process.argv.slice(2)
    if (args.length !== 3 && args.length !== 4) {
        usage()
    }
    module.exports.getRelease({
        provider: args[0],
        user: args[1],
        repo: args[2],
        part: args[3]
    }).then(result => {
        if (result.length !== 1) {
            console.log(result)
        } else {
            console.log(result[0])
        }
    }).catch(error => {
        console.log(error)
        usage()
        process.exit(1)
    })
}

To be called using
/**
 * Options:
 * {
 *     provider: (github | bitbucket),
 *     user: username,
 *     repo: repository,
 *     part: part of release file name - optional
 * }
 *
 */

const { getRelease, providerMethods } = require("get-release")
;(async _ => {
  let url = await getRelease(
      {
          provider: "github",
          user: "phhusson",
          repo: "treble_experimentations",
          part: "arm64-ab-gapps"
      }
  )
  console.log(url[0])
})()

Custom providers can be defined using
const { getRelease, providerMethods } = require("get-release")
providerMethods.GITLAB = async ({user, repo, part = ""}) => {
  // Custom code, should return a string
}


texts: Can you replace a REPLACE statement, or 9?

texts:
I would really like something to replace all of these REPLACE Statements.

SELECT DISTINCT
CAH.CaseNbr
    , REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
            (SELECT table1.Degree
            FROM SDUJS.dbo.fnWorstDegreeCharge(CB.CaseID) AS table1), 'F1', 'F')
            ,'F2','F'),'F3','F'),'F4','F'),'F5','F'),'F6','F'),'FA','F'),'FB','F')
            ,'FC','F') AS Degree
    , dbo.fncasecounty(CB.CaseID) AS County
FROM
    Justice.dbo.CaseBase AS CB
    INNER JOIN Justice.dbo.xCaseBaseChrg AS xCBC WITH (NOLOCK) ON xCBC.CaseID = CB.CaseID
    INNER JOIN Justice.dbo.Chrg AS Chrg WITH (NOLOCK) ON Chrg.ChargeID = xCBC.ChargeID
    INNER JOIN Justice.dbo.CaseAssignHist AS CAH WITH (NOLOCK) ON CAH.CaseID = CB.CaseID
    INNER JOIN Justice.dbo.ClkCaseHdr AS CCH WITH (NOLOCK) ON CCH.CaseID = CB.CaseID
WHERE
    CCH.DtFile BETWEEN '07/01/2010' AND '06/30/2011'
    AND
    CCH.CaseUTypeID IN (858,4330,865,4329,6362,5112)
ORDER BY CaseNbr

All possible entries for that column

  M1, M2, MO, PO, CHINS, F1, F2, F3, F4, F5, F6, FA, FB, FC, 00

I want all the Felonies to be represented by F

Code after the review

I decided not to do this as a follow up question because there isn't much that I think can be done to this query now to make it faster, except for get rid of the DISTINCT which I don't feel comfortable doing right now.

SELECT DISTINCT
    CAH.CaseNbr
    , (SELECT table1.Degree FROM SDUJS.dbo.fnWorstDegreeCharge(CB.CaseID) AS table1) AS Degree
    , dbo.fncasecounty(CB.CaseID) AS County
FROM
    Justice.dbo.CaseBase AS CB
    INNER JOIN Justice.dbo.CaseAssignHist AS CAH WITH (NOLOCK) ON CAH.CaseID = CB.CaseID
    INNER JOIN Justice.dbo.ClkCaseHdr AS CCH WITH (NOLOCK) ON CCH.CaseID = CB.CaseID
WHERE
    CCH.DtFile BETWEEN '07/01/2010' AND '06/30/2011'
    AND
    CCH.CaseUTypeID IN (858,4330,865,4329,6362,5112)

Missing REPLACE statement

I moved the "REPLACE" to the function that I am calling, but I used @rolfl's wonderful Case Statement idea to get rid of all the REPLACE statements inside that function.


texts: Improving on John Resig's Simple JavaScript Inheritance: avoiding `new`

texts:
I've recently read this article, and I agree that the new keyword is not good practice.

Thus, I've made an improvement on John Resig's Simple JavaScript Inheritance in order to use the Class.create method instead of new:

// The dummy class constructor
function Class() {
   // I remove the initialization procedure in constructor function,
   // Initialization will done by Class.create which I defined below
}

// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;

// And make this class extendable
Class.extend = arguments.callee;

// What I improved
Class.create = function () {
  var instance = new this();
  if (instance.init) {
      instance.init();
  }
  return instance;
}

The initialization case in his article could be rewritten like this:

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  }
});

var p = Person.create();

Have I done this well or not? Please help me check it.


texts: Assign variables to save each directories from a folder

texts:
I want to assign corresponding variables based on the name to save each directory from a folder, including its subfolders, so I can get access to the file in each folder easily. The code created by myself doesn't look concise. Any suggestions?

import os

modelFld = r'C:\model'

baseInputFld = [os.path.join(modelFld, x) for x in os.listdir(modelFld) if 'base' in x.lower()][0]

oilWellFld = [os.path.join(baseInputFld, x) for x in os.listdir(baseInputFld) if 'oilwell' in x.lower()][0]
diswaterWellFld = [os.path.join(baseInputFld, x) for x in os.listdir(baseInputFld) if 'waterwell' in x.lower()][0]
quarryFld = [os.path.join(baseInputFld, x) for x in os.listdir(baseInputFld) if 'quar' in x.lower()][0]
linearRefFld = [os.path.join(baseInputFld, x) for x in os.listdir(baseInputFld) if 'linear' in x.lower()][0]
txCountyFld = [os.path.join(baseInputFld, x) for x in os.listdir(baseInputFld) if 'county' in x.lower()][0]
tigerFld = [os.path.join(baseInputFld, x) for x in os.listdir(baseInputFld) if 'tiger' in x.lower()][0]

step1Fld = [os.path.join(modelFld, x) for x in os.listdir(modelFld) if 'step1' in x.lower()][0]
step2Fld = [os.path.join(modelFld, x) for x in os.listdir(modelFld) if 'step2' in x.lower()][0]
step3Fld = [os.path.join(modelFld, x) for x in os.listdir(modelFld) if 'step3' in x.lower()][0]
step4Fld = [os.path.join(modelFld, x) for x in os.listdir(modelFld) if 'step4' in x.lower()][0]
step5Fld = [os.path.join(modelFld, x) for x in os.listdir(modelFld) if 'step5' in x.lower()][0]
step6Fld = [os.path.join(modelFld, x) for x in os.listdir(modelFld) if 'step6' in x.lower()][0]

step1InputFld = [os.path.join(step1Fld, x) for x in os.listdir(step1Fld) if 'input' in x.lower()][0]
step2InputFld = [os.path.join(step2Fld, x) for x in os.listdir(step2Fld) if 'input' in x.lower()][0]
step3InputFld = [os.path.join(step3Fld, x) for x in os.listdir(step3Fld) if 'input' in x.lower()][0]
step4InputFld = [os.path.join(step4Fld, x) for x in os.listdir(step4Fld) if 'input' in x.lower()][0]
step5InputFld = [os.path.join(step5Fld, x) for x in os.listdir(step5Fld) if 'input' in x.lower()][0]
step6InputFld = [os.path.join(step6Fld, x) for x in os.listdir(step6Fld) if 'input' in x.lower()][0]

step1OutputFld = [os.path.join(step1Fld, x) for x in os.listdir(step1Fld) if 'output' in x.lower()][0]
step2OutputFld = [os.path.join(step2Fld, x) for x in os.listdir(step2Fld) if 'output' in x.lower()][0]
step3OutputFld = [os.path.join(step3Fld, x) for x in os.listdir(step3Fld) if 'output' in x.lower()][0]
step4OutputFld = [os.path.join(step4Fld, x) for x in os.listdir(step4Fld) if 'output' in x.lower()][0]
step5OutputFld = [os.path.join(step5Fld, x) for x in os.listdir(step5Fld) if 'output' in x.lower()][0]
step6OutputFld = [os.path.join(step6Fld, x) for x in os.listdir(step6Fld) if 'output' in x.lower()][0]


texts:
Please critique my code. (Specifically, I'm not sure if my use of member variables is appropriate.)

Here is the main structure of my BST class:

public class bst {

    private Node root;

    public class Node {

        int data;
        Node left, right;

        private Node(int data) {
            this.data = data;
            left = null;
            right = null;
        }
    }
}

The bst class contains the following methods to find kth max/min element

private static int min;
private static int max;
private static int target;
private static boolean isFound;
private static int level;
private static int nodes;

public int KthMin(int k) {

    //initializing helper variables
    target = k;
    isFound = false;
    min = 0;
    level = 1;
    nodes = 0;

    KthMinHelper(root);

    if (target > nodes) {
        throw new IndexOutOfBoundsException();
    }

    return min;
}

private void KthMinHelper(Node n) {

    if (isFound) {
        return;
    }

    nodes++;

    if (n.left != null) {
        KthMinHelper(n.left);
    }

    if (level == target) {
        min = n.data;
        isFound = true;
    }
    level++;

    if (n.right != null) {
        KthMinHelper(n.right);
    }
}

public int KthMax(int k) {

    //initializing helper variables
    target = k;
    max = 0;
    isFound = false;
    level = 1;
    nodes = 0;

    KthMaxHelper(root);

    if (target > nodes) {
        throw new IndexOutOfBoundsException();
    }

    return max;
}

private void KthMaxHelper(Node n) {

    if (isFound) {
        return;
    }

    nodes++;

    if (n.right != null) {
        KthMaxHelper(n.right);
    }

    if (level == target) {
        max = n.data;
        isFound = true;
    }
    level++;

    if (n.left != null) {
        KthMaxHelper(n.left);
    }

}

This is how my test driver looks like:

 public static void main(String[] args) {
    bst tree = new bst();
    int[] a = {11, 5, 2, 9, 7, 6, 3};

    for (Integer n : a) {
        tree.insert(n);
    }

    System.out.println("\nkth min:" + tree.KthMin(3));
    System.out.println("kth max:" + tree.KthMax(2));
}


texts: Find if a number is equal to the sum of its divisors

texts:
A number is perfect if it is equal to the sum of all its divisors. For example divisors of 6 are 1, 2, 3. I want to read numbers, and for each number to print 1 if it is perfect and 0 if it's not perfect. Numbers are smaller than 10 ^ 19. How would I do it faster? My version:

#include <stdio.h>
#include <stdlib.h>
double perfectCheck( double number )
{
    double i, sum = 0;
    for( i = 1; i <= number / 2; i++ )
        if(( int )( number / i ) * i == number )
            sum += i;
    return sum;
}

int main()
{
    double n, i, m;
    scanf( "%lf", &n );
    for( i = 0; i < n; i++ )
    {
        scanf( "%lf", &m );
        if( perfectCheck( m ) == m )
            printf( "1 " );
        else
            printf( "0 " );
    }
    return 0;
}

Input:

5
28 7 8 9 6

Output:

1 0 0 0 1

I use C89.


texts: Parallelizing an algorithm with OpenMP using a dynamic work queue

texts:
I'm looking for comments on the design, correctness and performance (not so much style) of a dynamic work queue for OpenMP worker threads.

I have an algorithm that can be thought of in terms of some number of work items (how many is not known beforehand), each of which is executed and may then spawn two child work items. I start with a root work item and continue until there are no more tasks, then terminate. Tasks that are not ancestor and descendant are independent (and therefore can be run in parallel).

I want to use OpenMP to parallelize the work by having threads pop work from a queue. The difficult bit is:

waiting for work to become available in an efficient way
terminating when there are no work items left, and new ones can't be created any more, but not before

I'm most concerned about the correctness of the termination condition and of my use of the OpenMP functions.

In the version below, the work items are dummies, but the idea is that you could drop in arbitrary work (as long as mutually non-ancestral work is independent).

#include <mutex>
#include <condition_variable>
#include <stack>

#include "omp.h"

using namespace std;

// Dummy nlogn algorithm work item
class Work {
public:
    Work() : n() {}
    Work(int n) : n(n) {}

    // Returns true iff child work created
    bool go(Work& childA, Work& childB) {
        if (n > 1) {
            childA = Work(n - 1);
            childB = Work(n - 1);
            return true;
        }
        return false;
    }

    int n;
};

int main() {
    Work rootWorkItem(20);

    int numWaiting = 0;
    std::mutex m;
    std::condition_variable cv;
    std::stack<Work> workStack;

    workStack.push(rootWorkItem);

#pragma omp parallel
    while (true) {
        std::unique_lock<std::mutex> lock(m);

        if (workStack.empty()) {
            // Register as waiting for work
            numWaiting++;

            // If everybody is now waiting, it means that no one has more work to push
            if (numWaiting >= omp_get_num_threads()) {
                cv.notify_all();
                break;
            }

            // Wait for one of two things:
            //  a) more work has been pushed to the stack
            //  b) everything's done
            while (true) {
                cv.wait(lock);
                if ((numWaiting >= omp_get_num_threads()) || !workStack.empty()) break;
            }

            // If it was b), exit
            if (numWaiting >= omp_get_num_threads()) break;

            // Otherwise, tell everybody that we're no longer waiting
            numWaiting--;
        }

        // Pop a work item to start executing
        Work work = workStack.top();
        workStack.pop();

        lock.unlock();

        // Execute work and, if it spawned children, push them
        Work childA, childB;
        if (work.go(childA, childB)) {
            // Push child work items and tell somebody to get working on them
            lock.lock();
            workStack.push(childA);
            workStack.push(childB);
            cv.notify_one();
            lock.unlock();
        }
    }

    return 0;
}


texts: Stack data structure implementation in Java

texts:
I recently made a data structure, stack implementation in Java and I would like feedback on my code to improve it (other than commenting/documenting my code).

public class Stack {

    private int topIndex, maxSize;
    private int[] stack;

    public Stack(int size) {
        maxSize = size;
        stack = new int[maxSize];
        topIndex = -1;
    }

    public int maxSize() {
        return maxSize;
    }

    public int size() {
        return topIndex + 1;
    }

    public boolean isEmpty() {
        return topIndex == -1;
    }

    public boolean isFull() {
        return (topIndex + 1) == maxSize;
    }

    public void push(int value) {
        if (!isFull()) {
            topIndex++;
            stack[topIndex] = value;
        }
    }

    public int peek() {
        if (!isEmpty()) {
            return stack[topIndex];

        } else {
            return 0;
        }
    }

    public void pop() {
        if (!isEmpty()) {
            topIndex--;
        }
    }

    public static void main(String[] args) {

    }

}


texts:
There is a custom summary function needed as to receive an integer input (e.g. 32456) and returns 3+2+4+5+6. Can you think of any other (or better) solution besides this?

public class CustomSum {
    public int sum(int input) {
        int sum = 0;

        while ( input >= 1 ) {
            sum += input % 10;
            input = input / 10;
        }

        return sum;
    }

    public static void main(String[] args) {
        int input = Integer.parseInt(args[0]); //assuming args[0] is integer

        CustomSum c = new CustomSum();
        int sum = c.sum(input);

        System.out.println("sum: " + sum);
    }
}

In every iteration I intended to extract the right digit by input % 10, and omit the extracted right digit for next iteration by input / 10. Now consider when we are in last iteration and have a 1 digit number. The input / 10 would be greater than 0 and less than 1 (if actually it was float or double not int). So I didn't actually changed that specific condition, although with int it will always be 0.


texts:
A slick way to write the zip function in Scheme/Racket:

(define (zip . lsts)
  (apply map list lsts))

(zip '(a b c) '(1 2 3))
'((a 1) (b 2) (c 3))

Is using cons instead of list in zip to get a list of dotted-pairs correct?

(define (zip-dot . lsts)
  (apply map cons lsts))

(zip-dot '(1 2 3) '(a b c))
'((1 . a) (2 . b) (3 . c))


texts: Merge sort in one Single Function in Scala

texts:
I have implemented a sortmerge in Scala in one single function. I would like to have it reviewed, so that I can have it well organized, and it is then doing what needs to do.

val a = Array(5, 4, 1, 8, 7, 2, 6, 3)

def mergeSort(a: Array[Int]): Array[Int] = {
  val size = a.length

  if (size == 1) {
    return a
  }
  val a1 = new Array[Int](size / 2)
  val a2 = new Array[Int](size / 2)

  val upTo = (a.length / 2) - 1
  for (i <- 0 to upTo) {
    a1(i) = a(i)
  }
  var pos = 0
  for (i <- upTo+1 to a.length - 1) {
    a2(pos) = a(i)
    pos += 1
  }

  val aR1 = mergeSort(a1)
  val aR2 = mergeSort(a2)
  val aFinalR = new Array[Int](size)

  var i = 0
  var j = 0
  var upBoundR1 = false;
  var upBoundR2 = false;
  for (k <- 0 to aFinalR.length - 1) {
    if (aR1(i) < aR2(j) && !upBoundR1) {
      aFinalR(k) = aR1(i)
      if (i == aR1.length - 1) {
        upBoundR1 = true
      }
      else{
        i = i+1
      }
    } else if (aR2(j) < aR1(i) && !upBoundR2) {
      aFinalR(k) = aR2(j)
      if(j == aR2.length  -1) {
        upBoundR2 = true
      }
      else{
        j = j+1
      }
    } else {
      if(upBoundR1) {
        aFinalR(k) = aR2(j)
        j = if (j == aR2.length - 1) j else j + 1
      } else {
        aFinalR(k) = aR1(i)
        i = if (i == aR1.length - 1) j else i + 1
      }
    }
  }
  return aFinalR
}

val r = mergeSort(Array(1,2,5,4,3,7))

How can I use this function for arrays of different sizes?

And how can I clean up this code a bit more, I feel like the code is a little too big.

I would like to avoid the use of pattern matching, but rather, intentionally sort Arrays by iterating through them, at the same time, I would like to do a canonical merge sort, how can I get there?


texts: More correct way to avoid using a list for dropdown

texts:
This is my code

Any status &#9662;
        <form>

                    <input class="option" type="submit" name="status" value="Active" />

                    <input class="option" type="submit" name="status" value="Inactive" />

        </form>

Any date &#9662;
        <form>

                    <input class="option" type="submit" name="date" value="Today" />

                    <input class="option" type="submit" name="date" value="This Week" />

        </form>

In this example I have a dropdown with a list that I then make an effort to style not like a list (i.e removing bullet points, etc).

Is it possible to produce cleaner code to achieve the same result, without using a list structure, or is a list actually the right approach to this problem?


texts: Word ladder solution in Java using matrix

texts:
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that only one letter can be changed at a time and each intermediate word must exist in the dictionary. For example, given:

start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

  One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", the program should return its length 5.

The following is my implementation of Word Ladder problem. Can anybody review the code to compare its efficiency with other solutions?

package arrays;

import java.util.Hashtable;
import java.util.Set;

public class WordLadder {

public static void main(String[] args) throws Exception {
    wordLadder();
}

private static void wordLadder() throws Exception {
    String source = "hit";
    String destination = "cog";
    Hashtable<Integer, String> dict = new Hashtable<Integer, String>();
    dict.put(1, source);
    dict.put(2, "hot");
    dict.put(3, "dot");
    dict.put(4, "dog");
    dict.put(5, "lot");
    dict.put(6, "log");
    dict.put(7, destination);
    formHammingDistanceMat(dict);
}

private static void formHammingDistanceMat(
        Hashtable<Integer, String> dict) throws Exception {
    int mat[][] = new int[dict.size()][dict.size()];
    for (int[] row : mat) {
        java.util.Arrays.fill(row, 99999);
    }

    Set<Integer> keySet = dict.keySet();
    for (int i = 0; i < keySet.size() - 1; i++) {
        String mainString = dict.get(i + 1);
        for (int j = i + 2; j <= dict.size(); j++) {
            if (j == 7)
                System.out.println();
            mat[i][j - 1] = findHamming(mainString, dict.get(j));
        }
    }
    System.out.println(findShortestPath(mat, 0, 1,dict));
}

private static int findShortestPath(int[][] mat, int row, int col,
        Hashtable<Integer, String> dict) {
    if (col == dict.size()-1) {
        return 0;
    }
    if (mat[row + 1][col + 1] == 1) {
        return 1 + findShortestPath(mat, row + 1, col + 1, dict);
    } else if (mat[row][col + 1] == 1) {
        return 1 + findShortestPath(mat, row, col + 1, dict);
    } else
        return 1 + findShortestPath(mat, row + 1, col, dict);
}

private static int findHamming(String mainString, String str)
        throws Exception {
    if(mainString.length()!=str.length()) throw new Exception();
    int count = 0;
    for (int i = 0; i < mainString.length(); i++) {
        if (mainString.charAt(i) != str.charAt(i))
            count++;
    }
    return count;
}
}


texts: What is a safe way to lock a thread in a single-threaded application?

texts:
I was looking at the different possible threading methods that I could use in my single-threaded application. What I have written so far is a class that will lock the thread when I instantiate the object, then unlock the thread when the object becomes out of scope. Here is what the class looks like:

ProcessCritSec.h

#ifndef AFX_PROCESS_CRIT_SEC_H_
#define AFX_PROCESS_CRIT_SEC_H_

class CProcessCritSec
{
    public:
        CProcessCritSec(CCriticalSection* pcCriticalSection);
        virtual ~CProcessCritSec();

    private:
        CCriticalSection*   m_pcProcessCritSect;
};

#endif // !defined(AFX_PROCESS_CRIT_SEC_H_)

ProcessCritSec.cpp

#include "StdAfx.h"
#include "ProcessCritSec.h"

CProcessCritSec::CProcessCritSec(CCriticalSection* pcCriticalSection)
{
    m_pcProcessCritSect = pcCriticalSection;

    if (m_pcProcessCritSect != NULL)
    {
        m_pcProcessCritSect->Lock();
    }
}

CProcessCritSec::~CProcessCritSec()
{
    if (m_pcProcessCritSect != NULL)
    {
        m_pcProcessCritSect->Unlock();
    }
}

When I want to lock a thread I call this in a function:

CProcessCritSec cThreadSafety(&m_cCriticalSection);

Is this a safe way to locking a thread? Or is there a safer way to making my application single-threaded? Also I have a side question: When I instantiate this object in a try/catch block like so:

try
{
    CProcessCritSec cThreadSafety(&m_cCritialSection);

    Foo();
}
catch(...)
{
    //Log Exception
}

Will the thread become unlocked if an exception occurred within Foo() and the catch block catches the exception?


texts: Ohms law calculator + whitelist of user. Learning use

texts:
I've been learning a ton of c++ lately on Codecademy and I'm soon done with the course of c++.

(Still need to learn classes, object-oriented programming and harder projects.)

But I wanted to get a review of my recent program.

And I also wanted to know if its possible to make an Unique ID, that only fits me, kinda like the cicada.

Psst, the program is to solve Ohm's Formular in physics and actively takes input to solve exactly your case.

Leave suggestions on what I could do better in this project + what I should try to program next too.

//Include
#include <iostream>
#include <string>
using namespace std;

 int main(){

    //Declare variables
    double Wolt;
    double Ohm;
    double Amp;
    std::string Formular;
    std::string Username;
    std::string Whitelist;

    //Login sequence:
    std::cout << "Hvad er dit username?: ";
    cin >> Username;

    //Whitelist
    Whitelist = "Fred267s", "Seb4572s", "Popp4593s";

    //Check if username is on whitelist
    if (Username == Whitelist){

        std::cout << "Velkommen til fysik formel udregner til strøm " << Username << " \n";
        std::cout << "Lavet af Frederik Schmidt 1.S \n";
    }

    //If username is NOT on the whitelist
    else if (Username != "Fred267s", "Seb4572s", "Popp4593s" ){

        std::cout << "Sorry, you do not have access! \n";
        return 0;
    }

    //Questions
    std::cout << "Hvad er det du skal udregne? ";
    cin >> Formular;

    //Wolt formular

    if (Formular == "Wolt"){

        //Questions
        std::cout << "Hvad er Ohmen?: ";
        cin >>Ohm;
        std::cout << "Hvad er Amperen?: ";
        cin >> Amp;

        //Formular
        Wolt = Ohm*Amp;

        //Return
        std::cout << "Volten er: " << Wolt << " \n";
    }

    //Amp formular

    else if (Formular == "Amp"){

        //Questions
        std::cout << "Hvad er Volten?: ";
        cin >>Wolt;
        std::cout << "Hvad er Ohmen?: ";
        cin >>Ohm;

        //Formular
        Amp = Wolt/Ohm;

        //Return
        std::cout << "Amperen er: " << Amp << " \n";
    }

    //Ohm formular

    else if (Formular == "Ohm"){

        //Questions
        std::cout << "Hvad er Volten?: ";
        cin >>Wolt;
        std::cout << "Hvad er Amperen?: ";
        cin >>Amp;

        //Formular
        Ohm = Wolt/Amp;

        //Return
        cout << "Ohmen er: " << Ohm << " \n";
    }

    //If the Formular inputtet is NOT on the list.

    else {

        cout << "Error in the formular, please try again!";

    }
}


texts: Collecting data from different positions in a given array

texts:
I'm writing a PHP function to collect data from different positions in a given array.  I've done it as follows which gives me what I require.

for ($a=9; $a < 13; $a++) {
     $n = $arr[$a][2];
     $p = $arr[$a][3];
     $c = $p;
     $v1[] = array($n,$p,$c);
}

for ($b=3; $b < 16; $b+=4) {
 $h = $arr[6][$b];
     $m = $arr[5][$b];
     $l = $arr[4][$b];
     $v2[] = array($h,$m,$l);
}

foreach ($v1 as $k=>$o) {
    $r[] = array( 'na'=> $o[0], 'pr'=> $o[1], 'cu' => $o[2], 'val1' => $v2[$k][0], 'val2' => $v2[$k][1], 'val3' => $v2[$k][2]);
}

To get the output in this format, without repeating the fields:

[0] = > Array
           [na] => Text
           [pr] => 1
           [cu] => Text
           [val1] => 1
           [val2] => 2
           [val3] => 3

[1] = > Array
           ....
           ....

[3] = > Array
           [na] => Text3
           [pr] => 1-3
           [cu] => Text-22
           [val1] => 101
           [val2] => 22
           [val3] => 34

Is there a better, more efficient way to do this?


texts: Building a string with only two repeating characters

texts:
The below is the C# implementation for the a function for given parameters int a, int b - both represent characters 'A' and 'B' respectively, where the function should return a string containing both characters 'A' and 'B' occurring a times and b times respectively but neither 'A' nor 'B' repeating consecutively for more than 2 times. Both values for a and b are given in a way that a string can be build using those numbers - so eg: Foo(0,3) or Foo(1,7) shall not be invoked.
eg:
Foo(3,3) returns "BBAABA" or "AABBAB"
Foo(4,1) returns "AABAA"
Foo(3,5) returns "BAABBABB" or "BBAABBAB"
Code:
static string Foo(int a, int b)
{
    int total = a + b;
    StringBuilder sb = new StringBuilder();
    char charToPrint = a > b ? 'A' : 'B';
    int flag = 0;

    for(int x =0; x< total; x++)
    {
        if(flag == 2)
        {
            flag = 0;
            charToPrint = SwapChar(charToPrint);
        }
        if(charToPrint == 'A' && a == 0 || charToPrint == 'B' && b == 0)
        {
            charToPrint = SwapChar(charToPrint);
        }

        if (charToPrint == 'A')
            a--;
        else
            b--;

        sb.Append(charToPrint);
        flag++;
    }
    return sb.ToString();
}

static char SwapChar(char thisChar)
{
    return thisChar == 'A' ? 'B' : 'A';
}

This is working but I would like to receive some feedback on this code.


texts: Optimize query containing too many inner join and rows

texts:
I have the following query:

SELECT *
INTO ##TempStaffT
FROM Staff HF
WHERE  HF.[businessline_id]='T'
AND HF.[offices_id] IN (SELECT * FROM ##TempParamOffice)
AND HF.[specialism_id]IN (SELECT * FROM ##TempParamSpecialism)
AND HF.[onetouch]IN (SELECT * FROM ##TempParamConsultant)

 SET @sql4 = N'

INSERT INTO ##TempFees(' + @columns1 + ',CALF_AN ,BusinessName)
SELECT distinct ' + @columns2 + ',p.CALF_AN ,CB.[TempBusinessName] as BusinessName
   FROM
     dbo.WTEFAC EF
  inner JOIN  dbo.WTFAC F ON EF.EFAC_NUM = F.EFAC_NUM
  inner JOIN  dbo.WTFACINFO BS ON F.FAC_NUM = BS.FAC_NUM
  inner JOIN dbo.WTLFAC LF ON F.FAC_NUM = LF.FAC_NUM
  inner JOIN dbo.WTRUBVARIANTEFAC WRU ON LF.RINT_ID = WRU.RINT_ID
  inner JOIN dbo.WTACUMFAC WTA ON WRU.RUV_ID = WTA.RUV_ID
  inner JOIN ##CUM_CODEHT WTA1 ON WTA.CUM_ID = WTA1.CUM_ID
  inner JOIN dbo.WTVTAT TAT ON BS.TIE_ID = TAT.TIE_ID AND BS.RFAN_ID = TAT.RFAN_ID AND BS.PER_ID = TAT.PER_ID AND BS.CNT_ID = TAT.CNT_ID
  inner JOIN dbo.PYCONTRAT CC ON TAT.PER_ID = CC.PER_ID AND TAT.CNT_ID = CC.CNT_ID
  inner JOIN dbo.WTMISS M ON CC.PER_ID = M.PER_ID AND CC.CNT_ID = M.CNT_ID
  inner JOIN dbo.WTCNTI COT1 ON M.PER_ID = COT1.PER_ID AND M.CNT_ID = COT1.CNT_ID
  inner JOIN dbo.WTQUAEU Q ON COT1.TIE_ID = Q.TIE_ID AND COT1.QEU_CDE = Q.QEU_CDE
  inner JOIN dbo.WTSCCT C ON CC.RGPCNT_ID = C.RGPCNT_ID AND CC.PER_ID = C.PER_ID AND CC.CNT_ID = C.CNT_ID --AND''SECT3'' = C.STTQ_COD
  INNER JOIN ##TempStaffT HF ON C.VAPO_CODE = HF.onetouch  COLLATE Latin1_General_CI_AS
  inner JOIN
##TempA AS p  ON p.CNT_ID = COT1.CNT_ID  inner JOIN
 ##TempB AS p1  ON p1.CNT_ID = COT1.CNT_ID
  CROSS JOIN [dbo].[CustBusinessTable] CB
WHERE  CB.[TempBusinessName]=''Pure Temp Fees''

GROUP BY p.CALF_AN,CB.[TempBusinessName]
'
;
PRINT @sql4;

My problem is that the query above took 20 min to be executed because ##TempStaffT contains too many rows.  How can I optimize it? I use many temp tables but it seems to not be working.


texts: how to pass a block to a function as a parameter

texts:
I'd like to refactor the following code:

case @request.path
when '/'
  Rack::Response.new do |response|
    do_stuff
  end
when '/env' then Rack::Response.new(@env.to_html)
end

And extract Rack::Response.new, something like the following:

Rack::Response.new case @request.path
when '/'    then Proc.new {|response| do_stuff }
when '/env' then @env.to_html
end

But I get

  stringable or iterable required

What's the correct implementation (Ruby 1.9.2)?


texts:
Source: careercup.com

  You are given an array of integers(with all valid input) You have to
  write a function which will produce another array, where the value in
  each index of the array will be the product of all values in the given
  array exccept that index.

  Example

  Array 1: 1 2 3 4 5

  Array 2: 120 60 40 30 24

  Come up with a solution of \$O(n^2)\$ can you improve it?

I would like to get code review comments for my code:

void createIndexlessArrayProduct()
{
   int arr1[]= {1,2,3,4,5};
   int arr2[5];

   arr2[0] = 1;

   for(auto& val : arr1)
   {
       arr2[0] *= val;
   }

   for(int i = 1; i < 5; ++i)
   {
       arr2[i] = arr2[0] / (i+1);
   }

   for( auto& val : arr2)
   {
      std::cout << val << "\n";
   }
}


texts: Emplace a lambda which captured a unique_ptr into container like queue

texts:
I'd like to emplace a lambda which captured a unique-pointer into a container, but it failed to compile under GCC 7.3.0 as C++17. From the error messages, it's calling the copy constructor of unique_ptr when constructing function.
compile
#include <memory>
#include <functional>
#include <string>
#include <queue>

int main (){
    auto ptr = std::make_unique<std::string>("123456");
    auto l = [p = std::move(ptr)] () mutable {
        p.reset();
    };
    std::queue<std::function<void()>> q;
    q.emplace(std::move(l));
    return 0;
}

Actually, I have many lambdas with the same parameter list and same return type, and I need to emplace them to one container. So I need a common type to wrap, like std::function<void()>.
In addition, I don't want add something else, like using std::shared_ptr to make it copyable, or using another lambda to wrap again.
Based on the above, I designed LambdaWrapper to use instead of std::function. The variable which captured won't be copied, because of the non-copyable LambdaWrapper.
class LambdaWrapper {
 public:
  template <class T, typename = std::is_invocable<decltype(std::mem_fn(&T::operator()))>>
  LambdaWrapper(T&& lambda) {
    MemberFunction memfn;
    // This forced type conversion is refers to std::_Function_base::_Base_manager::_M_init_functor
    new (&memfn)(decltype(&T::operator()))(&T::operator());
    // Member function pointer is 16B. The first 8B is the address of function, and the last 8B is the offset of this pointer. Because the lambda type is not inherited from other classes, the offset is 0 and it can be ignored.
    new (&func_) void*(memfn.func);
    new (&deleter_)(void (*)(T*))(&DeleterImpl<T>::f);
    data_ = malloc(sizeof(T));
    new (data_) T(std::forward<T>(lambda));
  }
  ~LambdaWrapper() {
    if (data_ != nullptr && deleter_ != nullptr) {
      deleter_(data_);
    } else if (data_ != nullptr || deleter_ != nullptr) {
      // something wrong
    }
  }
  void operator()() { func_(data_); }

  LambdaWrapper(LambdaWrapper&& T) {
    data_ = T.data_;
    func_ = T.func_;
    deleter_ = T.deleter_;
    T.data_ = nullptr;
    T.func_ = nullptr;
    T.deleter_ = nullptr;
  }

  LambdaWrapper& operator=(LambdaWrapper&& T) {
    data_ = T.data_;
    func_ = T.func_;
    deleter_ = T.deleter_;
    T.data_ = nullptr;
    T.func_ = nullptr;
    T.deleter_ = nullptr;
    return *this;
  }

 private:
  LambdaWrapper(const LambdaWrapper&) = delete;
  LambdaWrapper& operator=(const LambdaWrapper&) = delete;
  struct MemberFunction {
    void* func;
    void* ptr;
  };
  void (*func_)(void*);
  void (*deleter_)(void*);
  void* data_;
  template <class T>
  struct DeleterImpl {
    static void f(T* t) { delete t; }
  };
};

Finally, is there any better solution? And is there any problem with LambdaWrapper?


texts: Any use for this kind of self invoking function?

texts:
I am wondering if the self invoking function as displayed below, mainly the part of using the same function twice ('foo')('bar'), would ever be seen as a good practice?

And more important, is there a good reason to use this? Personally in this particular example I would rather go for multiple attributes and loop those.

The HTML is just filler.

<!DOCTYPE html>
<meta charset='utf-8'>
<title>Foo Bar Foobar</title>

Foo

Bar

Foobar


texts: Convert an integer to 4 bytes without bitshift operators

texts:
This code is applicable to either GLSL or C due to virtually identical syntax. Before GLSL 1.3, bitshift operators were not present and I am aiming for backwards compatibility to GLSL 1.2.

float lut[3] = {256,65536,16777216};

vec4 getBytes(float n)
 {
   vec4 bytes;
   bytes.x = floor(n / lut[2]);
   bytes.y = floor((n- bytes.x*(lut[2]) )/ lut[1]);
   bytes.z = floor((n - bytes.y*(lut[1]) - bytes.x*lut[2] )/ lut[0]) ;
   bytes.w = n - bytes.z*lut[0] - bytes.y*lut[1] - bytes.x*lut[2];
   return bytes;
 }

 float getid(vec4 bytes)
 {
   return bytes.w + bytes.z*lut[0]+ bytes.y*lut[1] + bytes.x*lut[2];
 }

This code will be used to pack a value greater than 8 bits into an 8-bit texture with 4 channels.

I also ported the code to Lua to run a unit test.

 lut = {256,65536,16777216}
 function getBytes(n)

   bytes = {}
   bytes.x = math.floor(n / lut[3]);
   bytes.y = math.floor((n- bytes.x*(lut[3]) )/ lut[2]);
   bytes.z = math.floor((n - bytes.y*(lut[2]) - bytes.x*lut[3] )/ lut[1]) ;
   bytes.w = n - bytes.z*lut[1] - bytes.y*lut[2] - bytes.x*lut[3];
   return bytes
 end

 function getid(bytes)

   return bytes.w + bytes.z*lut[1]+ bytes.y*lut[2] + bytes.x*lut[3]
 end

for i=1,math.pow(2,24),1 do
  if not (getid(getBytes(i)) == i) then

    print("Fail " .. i)
  end

end


texts: Proof that two lines intersect each other at precisely one point in Idris

texts:
I recently attempted to prove that given two lines, they intersect at one and only one point in Idris. Here is what I came up with:

interface (Eq line, Eq point) => Plane line point where
  -- Abstract notion for saying three points lie on the same line.
  colinear : point -> point -> point -> Bool
  coplanar : point -> point -> point -> Bool
  contains : line -> point -> Bool

  -- Intersection between two lines
  intersects_at : line -> line -> point -> Bool

  -- If two lines l and m contain a point a, they intersect at that point.
  intersection_criterion : (l : line) ->
                           (m : line) ->
                           (a : point) ->
                           (contains l a = True) ->
                           (contains m a = True) ->
                           (intersects_at l m a = True)

  -- If l and m intersect at a point a, then they both contain a.
  intersection_result : (l : line) ->
                        (m : line) ->
                        (a : point) ->
                        (intersects_at l m a = True) ->
                        (contains l a = True, contains m a = True)

  -- For any two distinct points there is a line that contains them.
  line_contains_two_points : (a :point) ->
                             (b : point) ->
                             (a /= b) = True ->
                             (l : line ** (contains l a = True, contains l b = True ))

  -- If two points are contained by l and m then l = m
  two_pts_define_line : (l : line) ->
                        (m : line) ->
                        (a : point) ->
                        (b : point) ->
                        ((a /= b) = True) ->
                        contains l a = True ->
                        contains l b = True ->
                        contains m a = True ->
                        contains m b = True ->
                        ((l == m) = True)

  same_line_same_pts : (l : line) ->
                       (m : line) ->
                       (a : point) ->
                       (b : point) ->
                       ((l /= m) = True) ->
                       contains l a = True ->
                       contains l b = True ->
                       contains m a = True ->
                       contains m b = True ->
                       ((a == b) = True)

  -- There exists 3 non-colinear points.
  three_non_colinear_pts : (a : point ** b : point ** c : point **
                           (colinear a b c = False,
                           (a /= b) = True,
                           (b /= c) = True,
                           (a /= c) = True))

  -- Any line contains at least two points.
  contain_two_pts : (l : line) ->
                    (a : point ** b : point **
                    (contains l a = True, contains l b = True))

-- If two lines intersect at a point and they are not identical, that is the o-
-- nly point they intersect at.
intersect_at_most_one_point : Plane line point =>
  (l : line) -> (m : line) -> (a : point) -> (b : point) ->
  ((l /= m) = True) ->
  (intersects_at l m a = True) ->
  (intersects_at l m b = True) ->
  ((a == b) = True)

intersect_at_most_one_point l m a b l_not_m int_at_a int_at_b =
  same_line_same_pts
  l
  m
  a
  b
  l_not_m
  (fst (intersection_result l m a int_at_a))
  (fst (intersection_result l m b int_at_b))
  (snd (intersection_result l m a int_at_a))
  (snd (intersection_result l m b int_at_b))

My main concerns is that I have an "inefficient" (possibly incorrect?) formulation of the axioms. The code runs and compiles, but it feels like for instance, somehow, intersection_criterion and intersection_result could be somehow made into one axiom. Nevertheless, any advice is appreciated.

(This is also on Github here in the file hilbert.idr)


texts: Is there a better way to write this jQuery UI effect animation?

texts:
I'm writing some code to perform some simple form validation and I would like to display error messages inside the actual relevant textarea by means of a text fadeout/fadein effect.

To achieve this I am using jQquery UI to do the following:

Step 1: Animate the color to match the background colour
Step 2: Modify the text to show the error message then fade it in
Step 3: Fade the error message out, change the text back to its
previous    content
Step 4: Fade the text back in
Step 5: Finally, Focus the    textarea    and put the cursor at the
end

This works fine, however to do this I have had to nest a lot of anonymous function which is something I really don't like to do.

Is there a better way of achieving the same effect?

if (replyto == body) {
    $textarea.prop("disabled", true).animate({ color: 'rgb(41, 41, 41)'},500, function(){
        $textarea.text('Please enter your reply here')
            .animate({ color: 'white'},500, function(){
                $textarea.delay('1000')
                    .animate({ color: 'rgb(41, 41, 41)'},500, function(){
                        $textarea.text(body)
                            .animate({ color: '#a7a7a7'},500)
                            .prop("disabled", false)
                            .focus()
                            .putCursorAtEnd();
                    });
            });
    });
    return false;
}


texts: Slow SQL Server performance with multiple PreparedStatement loop

texts:
I have a need to update thousands of database records at a time. I am using a loop to generate the necessary PreparedStatement updates, but am hoping for a more efficient method.

Normally, I would try to use a batch operation, but since the number of fields I need to update for each record differs, I need a new PreparedStatement for each update.

As it is, updates around 2,000 records takes 3-4 minutes.

            for (AgentUpdate update : updateList) {

                Agent thisAgent = update.getAgent();

                // Prefix for updating each agent
                StringBuilder sql = new StringBuilder(
                        "UPDATE REP_ASSIST.AGENTS SET\n"
                );

                // Create a map of all changes
                Map<String, String> updateMap = new HashMap<>();
                for (AgentDiffs diff : update.getChanges()) {
                    updateMap.put(diff.getAgentField().toString(), diff.getNewValue());
                }

                // Iterate through the map and build the SQL statement,
                // including all fields to be updated
                Iterator iterator = updateMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry pair = (Map.Entry) iterator.next();
                    sql.append(pair.getKey()).append("=?");

                    if (iterator.hasNext()) {
                        sql.append(",\n");
                    }
                }
                sql.append("\nWHERE AGENT_CODE=? AND UPN=?;");
                Utility.printTempMsg(sql.toString());

                // Create the PreparedStatement and fill each ? with the
                // appropriate new value.
                ps = connection.prepareStatement(sql.toString());
                int paramNum = 1;
                for (String fieldName : updateMap.keySet()) {
                    String newValue = updateMap.get(fieldName);
                    ps.setString(paramNum, newValue);

                    // Increase the parameter count
                    paramNum++;
                }

                // We are now to our last two parameters, fill them
                ps.setString(paramNum++, thisAgent.getAgentCode());
                ps.setInt(paramNum, thisAgent.getAgentUpn());

                ps.executeUpdate();
                count++;

                Utility.printTempMsg(sql.toString());

                // Update the progress based on total count so far
                updateProgress(count, totalOperations);

            }

So how does one handle large dynamic updates of this sort?


texts: Converting std::string to int without Boost

texts:
I'm trying to convert an std::string to an int with a default value if the conversion fails. C's atoi() is way too forgiving and I've found that boost::lexical_cast is quite slow in the case where the cast fails.  I imagine it's because an exception is raised. I don't have C++11, so stoi() is out.

The Delphi function StrToIntDef is the ideal, and it's also available in C-Builder (where I'm working currently).  But I want something more portable that works with std::string.

I've created the following function, which uses atoi() but first tests for error conditions. It also allows for leading and trailing spaces, which are harmless in my situation.

int stringtoIntDef(const std::string & sValue, const int & DefaultValue) {
// convert a std::string to integer with a default value returned
// in the case where the string doesn't represent a valid integer
// - accepts leading or trailing spaces as valid

   bool hasDigits = false;
   bool TrailingSpace = false;
   for (std::string::size_type k = 0; k < sValue.size(); ++k) {
      if ((sValue[k] == ' ') || (sValue[k] == '\t')) {
         TrailingSpace = hasDigits;
      } else if ((sValue[k] == '0') || (sValue[k] == '1') || (sValue[k] == '2') || (sValue[k] == '3') ||
                  (sValue[k] == '4') || (sValue[k] == '5') || (sValue[k] == '6') || (sValue[k] == '7') ||
                  (sValue[k] == '8') || (sValue[k] == '9')) {
         if (TrailingSpace) {
            return DefaultValue;
         } else {
            hasDigits = true;
         }
      } else if ((sValue[k] == '-') && !hasDigits) {
         hasDigits = true; // this protects against "--"
      } else {
         return DefaultValue;
      }
   }
   return atoi(sValue.c_str());
}

In my testing, I've compared it against StrToIntDef and it is just as fast, but lexical_cast is much slower in the case where the default is returned. For 1000 iterations, lexical_cast took 5 seconds while the other 2 weren't measurable.

For my lexical_cast function, I've used this:

try {
    return boost::lexical_cast<int>(sValue);
}
catch (boost::bad_lexical_cast &) {
    return DefaultValue;
}

Are there any gotchas I might have missed here?


texts:
I want to search some or all public properties of a class and for this requirement I have implemented a Property Searcher.

The Input for a Search is always a string. The Output contains the SearchString, the SearchContent in which the SearchString is contained and the searched Property.The Output is wrapped in a SearchResult object.

This is what i have implemented:

SearchResult.cs

public class SearchResult
{
    public PropertyInfo Property { get; private set; }

    public string SearchString { get; private set; }

    public string SearchContent { get; private set; }

    public ISearchable Item { get; private set; }

    public SearchResult(ISearchable item,
                        PropertyInfo property,
                        string searchString)
    {
        this.Property = property;
        this.SearchString = searchString;
        this.Item = item;
        this.SearchContent = property.GetValue(item).ToString();
    }
}

ISearchable.cs

public interface ISearchable
{
    IEnumerable<SearchResult> Search(string searchString);
}

Extension Methods for easier usage:

Extension.cs

public static class Extension
{
    public static SearchResult Search(this ISearchable source, string searchString, PropertyInfo info)
    {
        if (info.GetValue(source).ToString().Contains(searchString, StringComparison.OrdinalIgnoreCase))
        {
            return new SearchResult(source, info, searchString);
        }

        return null;
    }

    public static IEnumerable<SearchResult> Search(this IEnumerable<ISearchable> source, string searchString)
    {
        return source.SelectMany(searchable => searchable.Search(searchString)).Where(x => x != null);
    }

    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        return source.IndexOf(toCheck, comp) >= 0;
    }
}

I also want to show you the example and test code for e.g. searching in the property of a Book with a Description (the code is simplified and more complex in the original project).

Book.cs

public class Book : ISearchable
{
    public DescriptionInfo DescriptionInfo { get; set; }
    public string Title { get; set; }

    public IEnumerable<SearchResult> Search(string searchString)
    {
        yield return this.Search(searchString, this.GetType().GetProperty(nameof(this.Title)));
        foreach (var searchResult in this.DescriptionInfo.Search(searchString))
        {
            yield return searchResult;
        }
    }
}

Description.cs

public class DescriptionInfo : ISearchable
{
    public string Description { get; set; }

    public string ShortDescription { get; private set; }

    public DescriptionInfo(string description)
    {
        if (!string.IsNullOrEmpty(description))
        {
            this.Description = this.ShortDescription = description;
        }
    }

    public IEnumerable<SearchResult> Search(string searchString)
    {
        yield return this.Search(searchString, this.GetType().GetProperty(nameof(this.Description)));
    }
}

Program.cs

internal class Program
{
    private static void Main(string[] args)
    {
        var one = new Book
        {
            Title = "This Test Title is Amazing",
            DescriptionInfo = new DescriptionInfo("This i a nice Test Book Description")
        };
        var two = new Book
        {
            Title = "This second Test Title is Amazing",
            DescriptionInfo = new DescriptionInfo("This i a nice Book Description")
        };
        var three = new Book {Title = "Boring Title", DescriptionInfo = new DescriptionInfo("No Description")};

        var list = new List<Book>(new[] {one, two, three});
        var results = list.Search("Test").ToList();
    }
}

In results are three SearchResult objects. The string "Test" was found two times in a Title Property and one time in the Description Property of the Description class.

I do not know if this is the best solution to solve the problem. If you have a better one in mind please let me know.


texts: Finding nth lowest value without any Math max or min methods

texts:
So I decided to make a more efficient solution to a Google interview question where they ask you to either find the lowest or second lowest value in an array without using the max or min methods. I believe it is more efficient because you can use my method to find any nth lowest value in the array so it solves for all cases.

Please let me know if there is anything I can do to improve this solution or if there is anything I am missing:

/*Algorithm:
-first sort the array from ascending order
-Then iterate over the array with a loop
-if(array[i + nth lowest input you want])
-return the output

function nThOrderStatistic(array, number):
 -if you want to find the lowest number sub in 0 for number
 -for every nth lowest number you would sub in n - 1 for the number */

function nThOrderStatistic(array, number) {
  array.sort(function(a,b){return a -b});
  for(i = 0; i < array.length; i++)
  {
    if(array[i + number] < array[i + (number + 1)])
  {
     return array[i + number];
    }
  }
}

nThOrderStatistic([6,7,43,2,95], 2);

//sample output for 3rd lowest value is: 7 //


texts:
Task:

Write a function which returns true if a given substring is found within a given string. If the substring isn't found, then return false.

My implementation:
#!/usr/bin/env ruby
def custom_include?(string, substring)
    len = substring.size
    last_feasible = string.size - len

    for i in 0..last_feasible
        current_slice = string[i...i + len]

        if current_slice == substring
            return true
        end
    end

    false
end

puts custom_include? "The Ruby Programming Language is amazing!", "Language" # true
puts custom_include? "The Ruby Programming Language is amazing!", "language" # false
puts custom_include? "The Ruby Programming Language is amazing!", "amazing!" # true
puts custom_include? "The Ruby Programming Language is amazing!", "The"      # true
puts custom_include? "The Ruby Programming Language is amazing!", "Test"     # false

Is there a way to avoid the for-loop? Should I try to "save" variables?
Using variables make it easier for me to development a solution for such an exercise. Moreover I think it makes the script for readable and understandable. What's your opinion about that approach?


texts: Unique letter counter for string in Python

texts:
I'm trying to create a program that creates a record of how many times letters appear in a given string (ignoring blank spaces) using recursion.

s = "Hello there this is the string"

new_s = ""
for i in s:
    if i != " ":
        new_s += i
new_s = new_s.lower()
com_dict = {}
def merge_count(s):
    global com_dict
    if len(s) == 1:
        if s[0] in com_dict:
            com_dict[s[0]] += 1
        else:
            com_dict[s[0]] = 1
    else:
        merge_count(s[:int(len(s)/2)])
        merge_count(s[int(len(s)/2):])

merge_count(new_s)
for i in com_dict:
    print i, com_dict[i]

Is the global variable necessary? Should I be using a different data structure instead of a dictionary? I will need to rank the results based on the most frequently appearing letters. Is using recursion in this scenerio generally a bad idea? Would iterating be a better choice?


texts:
In my ASP.NET form I have a file upload control where I am letting users upload image files, converting it into base64String to store it in the database.

I am using following code to do so,

     if (FileUploadControl.HasFile)
            {
                var img = new Bitmap(FileUploadControl.FileContent);
                if (img.Height > 133 || img.Width > 133)
                {
                    img = ResizeImage(img, 132, 132);
                }

                u.Photo = ImageToBase64String(img);
            }

    private static string ImageToBase64String(Bitmap img)
    {
        var ms = new System.IO.MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] byteImage = ms.ToArray();
        var base64String = Convert.ToBase64String(byteImage);
        return base64String;
    }

    private static Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
    {
        var destRect = new Rectangle(0, 0, width, height);
        var destImage = new Bitmap(width, height);

        destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

        using (var graphics = Graphics.FromImage(destImage))
        {
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            using (var wrapMode = new ImageAttributes())
            {
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
            }
        }

        return destImage;
    }

Now I am worried about followings,

Overall code review
Creating two Bitmap classes they are disposable but am not sure if I can dispose them at all
I seem to be doing unnecessary conversion because I don't have enough knowledge.

Goal

Convert uploaded images to 132 x 132 if they are over it and save them as base64String.


texts: Trying to avoid null types using lazy and lateinit Kotlin

texts:
I am using Kotlin from quite some time now, but I could not able to achieve not-null types for all the properties in Kotlin.

After what I learned by watching Kotlin in Google IO and a bit of research, I made all properties not nullable.

Please check my code and correct me if any mistakes.

Thanks in advance.

class MusicService : Service(), PlaybackManager.PlaybackServiceCallback {

    //NotNull
    private val mDelayedStopHandler = DelayedStopHandler(this)
    private val eventBus = EventBus.getDefault()

    //Lateinit
    lateinit var mSessionToken: MediaSessionCompat.Token
    lateinit var mTransportControls: MediaControllerCompat.TransportControls

    //Lazy
    private val mSession: MediaSessionCompat by lazy { MediaSessionCompat(this, "MusicService") }
    private val mMediaNotificationManager: MediaNotificationManager by lazy {
        try {
            MediaNotificationManager(this)
        } catch (e: RemoteException) {
            throw IllegalStateException("Could not create a MediaNotificationManager", e)
        }
    }
    val mPlaybackManager: PlaybackManager by lazy {
        PlaybackManager(mPlayback = LocalPlayer(this), mServiceCallback = this)
    }

    override fun onCreate() {
        LogHelper.d(TAG, "onCreate")
        super.onCreate()

        //Init MediaSessionCompat and TransportControls
        mSessionToken = mSession.sessionToken
        mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS)
        mTransportControls = MediaControllerCompat(this, mSession).transportControls
        mSession.setCallback(mPlaybackManager.mMediaSessionCallback)

        //EventBus Reg
        eventBus.reg(this)
        eventBus.post(GetAllMediaEventRequest())

    }

    @Subscribe
    fun onGetAllMediaEventResponse(event: GetAllMediaEventResponse) {
        Timber.d("GetAllMediaEventResponse event.status = ", event.status)
        mPlaybackManager.mMediaData = event.mediaItems
    }
}


texts: Checking for all query parameters before inserting into a database

texts:
The code works as it is but it's very messy. Is there a way to clean up the null checking in the if statement?

public function submitCoil ($data) {
    $db = Database::getInstance();

    //Define certain query values
    $uniqueID = $this->hash("id");
    $queryData = array(
        'fields' => array(
            'uniqueid',
            'uploaded',
            'name',
            'resistance',
            'wrapped',
            'category',
            'description',
            'wraps',
            'images',
            'wire_one',
            'wire_two',
            'wire_three',
            'wire_four',
            'wire_five',
            'wire_six'
        ),
        'values' => array(
            'uniqueID' => $uniqueID,
            'uploaded' => date("F j, Y", time()),
            'name' => $data['name'],
            'resistance' => $data['resistance'],
            'wrapped' => $data['wrapped'],
            'category' => $data['category'],
            'description' => $data['description'],
            'wraps' => $data['wraps'],
            'images' => "coils/" . $uniqueID . "/",
            'wire_one' => $data['wire_one'],
            'wire_two' => $data['wire_two'],
            'wire_three' => $data['wire_three'],
            'wire_four' => $data['wire_four'],
            'wire_five' => $data['wire_five'],
            'wire_six' => $data['wire_six']
        )
    );

    //Make sure mandatory datas are filled out
    if (!empty($queryData['values']['name']) && !empty($queryData['values']['resistance']) && !empty($queryData['values']['wrapped']) && !empty($queryData['values']['description']) && !empty($queryData['values']['wraps'])) {
        $db->insertFew("coils", $queryData['fields'], $queryData['values']);
    } else {
        echo "Please fill all fields";
    }


texts: Golang function to clean a string of scripts

texts:
I am trying to make an efficient algorithm for removing script tags from an HTML string. Can someone point out any flaws in this? This seems to be the best I could think of.

func removeScripts(s string) string {
    startingScriptTag := "<script"
    endingScriptTag := "</script>"

    var script string

    for {
        startingScriptTagIndex := strings.Index(s, startingScriptTag)
        endingScriptTagIndex := strings.Index(s, endingScriptTag)

        if startingScriptTagIndex > -1 && endingScriptTagIndex > -1 {
            script = s[startingScriptTagIndex:endingScriptTagIndex + len(endingScriptTag)]
            s = strings.Replace(s, script, "", 1)
            continue
        }

        break
    }

    return s
}


texts:
I was recently given an interview and was asked to write my own lock implementation using atomics, but not necessary reentrant.

I didn't answer the question, but at home, I wrote this code. Please asses my implementation and suggest better solutions.

public class MyLock {

    AtomicBoolean locked = new AtomicBoolean(false);

    ThreadLocal<Boolean> threadLocal = new ThreadLocal();

    public void lock() {
        while (true) {
            if (locked.compareAndSet(false, true)) {
                threadLocal.set(true);
                return;
            }
        }
    }

    public void unLock() {
        if (threadLocal.get()) {
            locked.compareAndSet(true, false);
            threadLocal.set(false);
        }
    }

}

class Main {

    public static void main(String[] args) {
        MyLock myLock = new MyLock();
        for (int i=0;i<10;i++)
            new MyThread(myLock).start();
    }
}

class MyThread extends Thread {

    final MyLock myLock;

    MyThread(MyLock myLock) {
        this.myLock = myLock;
    }

    @Override public void run() {
        myLock.lock();
        System.out.println("start - " + Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        System.out.println("finish - " + Thread.currentThread().getName());
        myLock.unLock();
    }
}


texts:
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?

I have written the following program in python and am new to programming in Python. I am looking for suggestions for making efficient programs and developing good programming habits.
import math
data ={}

def isPrime(n):
    global data
    if n in data:
        return data[n]

    for num in range(2,math.floor(math.sqrt(n)+1)):
        if n%num == 0:
            data[n]=False
            return False
    data[n]=True
    return True
count =0
data ={}

for num in range (2,1000000):
    q=False
    num=str(num)
    for i in range(len(num)):
        if (isPrime(int(num[i:]+num[:i]))):
            q=True
        else:
            q=False
            break
    if q:
        count+=1
print (count)


texts:
After spending a few months learning python I decided to build a basic Rock Paper Scissors game.

Basic construct of the game:

Allows you to pick best of 3,5,7
Allows you to put in the name
Computer choices are completely random

I know there are probably a million different ways to write this code. But based on the way that I built it, are there any ways to make my code more efficient?

# Rock Paper Scissors

import random as rdm

print("Welcome to Rock/Paper/Scissors!!! \n")

gl = input("Would you like to play a best of 3, 5 or 7: ")
while gl not in ["3", "5", "7"]:
    gl = input("Incorrect Response, please select 3, 5, or 7: ")

gl = int(gl)

human_1 = input("Please enter your name: ")

GameOptions = ['Rock', 'Paper', 'Scissors']

hmn_score = 0
cpt_score = 0

rps_running = True

def rps():
    global cpt_score, hmn_score
    while rps_running:
        hmn_temp = input("""Please select from the following:
                                            1 - Rock
                                            2 - Paper
                                            3 - Scissors
                        \n""")
        while hmn_temp not in ["1", "2", "3"]:
            print("That was not a acceptable input!")
            hmn_temp = input("""Please select from the following:
                                    1 - Rock
                                    2 - Paper
                                    3 - Scissors
                \n""")

        hmn_final = int(hmn_temp) - 1

        print('You Chose: ' + GameOptions[hmn_final])

        cpt = rdm.randint(0, 2)

        print('Computer Chose: ' + GameOptions[cpt] + '\n')

        if hmn_final == cpt:
            print('Tie Game!')

        elif hmn_final == 0 and cpt == 3:
            print('You Win')
            hmn_score += 1
        elif hmn_final == 1 and cpt == 0:
            print('You Win')
            hmn_score += 1
        elif hmn_final == 2 and cpt == 1:
            print('You Win')
            hmn_score += 1
        else:
            print('You Lose')
            cpt_score += 1

        game_score()
        game_running()

def game_score():
    global cpt_score, hmn_score
    print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')

def game_running():
    global rps_running, gl
    if gl == 3:
        if hmn_score == 2:
            rps_running = False
            print(f"{human_1} Wins!")

        elif cpt_score == 2:
            rps_running = False
            print(f"Computer Wins!")

        else:
            rps_running = True

    elif gl == 5:
        if hmn_score == 3:
            rps_running = False
            print(f"{human_1} Wins!")
        elif cpt_score == 3:
            rps_running = False
            print(f"Computer Wins!")
        else:
            rps_running = True

    elif gl == 7:
        if hmn_score == 4:
            rps_running = False
            print(f"{human_1} Wins!")
        elif cpt_score == 4:
            rps_running = False
            print(f"Computer Wins!")
        else:
            rps_running = True

rps()