texts: Should I set a license in the constructor or a static constructor?

texts:
We are using the Aspose PDF library to work with PDF files. Aspose requires the license to be set once per process. Accordingly, I have created the following common static method that sets the license. Any code that needs Aspose will call into this method.

public class ConfigurationService
{
    private static bool isAsposePdfLicenseSet = false;

    public static void SetAsposePdfLicense()
    {
        if (isAsposePdfLicenseSet)
        {
            return;
        }

        // Set the license... (Moderately expensive - accesses the file system)

        isAsposePdfLicenseSet = true;
    }
}

I need to make sure the license is set before using my class, PdfInspector, but I only need to set it once, so I gave that class a static constructor:

static PdfInspector()
{
    ConfigurationService.SetAsposePdfLicense();
}

However, when I run Code Analysis in Visual Studio, it tells me that static constructors should be avoided. The alternative is to set the license in the constructor:

internal PdfInspector()
{
    ConfigurationService.SetAsposePdfLicense();
}

While this would be called every time the class is instantiated, the SetAsposePdfLicense would short circuit before doing any real logic. Bottom line, which implementation is preferable or is there an alternative that I haven't considered?


texts: Navigation strategies for a SwiftUI-based app using MVVM pattern

texts:
I'm finding it difficult to decide on the best architectural pattern for a SwiftUI app but, for the moment, I'm sticking with MVVM as I found this a good fit conceptually.
I'm trying to avoid the SwiftUI layer knowing too much about the business logic and navigation structure but am struggling to decide how best to achieve this.
Here is the prototype view model (without implementation for the navigation):
@dynamicMemberLookup
final class PatientListViewModel: ViewModelType {
    struct State {
        var patients: [PatientSummaryViewModel]
    }
    @Published var state: State = State(patients: []) {
        willSet { print("Received: \(newValue)") }
    }

    enum Input {
        case onNewPatient
    }

    private let service: PatientServiceType
    private var cancellables = Set<AnyCancellable>()

    init(service: PatientServiceType) {
        self.service = service

        service.fetchAll()
            .receive(on: DispatchQueue.main)
            .map { patients in
                patients.map {
                    PatientSummaryViewModel(patient: $0)
                }
            }
            .sink { [weak self] patientViewModel in
                self?.state.patients = patientViewModel
            }
            .store(in: &cancellables)
    }

    func action(_ input: Input) {
        switch input {
        case .onNewPatient:
            print("Create new view and associated viewModel here but how does SwiftUI access it?")
        }
    }

    subscript<Value>(dynamicMember keyPath: KeyPath<State, Value>) -> Value {
        state[keyPath: keyPath]
    }
}

Associated SwiftUI view:
struct PatientListView: View {
    @ObservedObject var viewModel: PatientListViewModel

    var body: some View {
        NavigationView {
            List(viewModel.patients) { viewModel in

                NavigationLink(
                    destination:
                        PatientSummaryView(viewModel: viewModel),
                    label: {
                        PatientCell(patient: viewModel.patient)
                    })

            }
            .navigationBarItems(leading: EditButton(),
                                trailing: Button(action: {
                                    // call to viewmodel to get new view and correctly constructed viewModel
                                },
                                                 label: { Image(systemName: "plus")
                                                    .font(.title2)
                                                 }))
            .navigationBarTitle("Patients")
        }
    }
}

At this point in time, there are several solutions that present themselves:

Modify action(_ input:) to create the View in situ, returning it to the View that called it. Not all actions will need navigation to take place and so I'd need to add @discardableresult with many actions having to return EmptyView() and then there's the little dance I'd need to do with type erasing the views to consider.

Modify the view model State internal struct to include a "next view" property that is updated by action(_:) when new views are required. Although the idea of keeping state in one place appeals this feels a little clunky somehow.

Finally I have some vague ideas about a callback/closure that is passed to the view model and used to construct the required view but I'm struggling to visualise this as I still find closure syntax confusing, doubly so when working with Views.


texts: JavaScript tournament scheduling (fixture generation) algorithm

texts:
I have just developed a match scheduling algorithm and had to use some pretty funny modular arithmetic. While it works fine i would like to know if my calculations could be simplified any further.

Though it looks a little complicated it's in fact very simple and seems to work very efficiently.

A little bit explanation on my approach;

So for starters, i have 10 teams to match up. Each team will play 9 matches in a fixture such that all teams play with a separate competition at every round.

Accordingly i have an array of team objects as follows;

var teams = [{id: team_0, matches : []}, ... ,{id: team_9, matches: []}]

I would like to show the general layout of the fixture in the table below;

Where mc is the match count, which is 9 in this example. The items with green background are the ones we calculate by iterating over and the red foreground ones are calculated automatically from the iterated ones. Dark green background is the starting index for insertion of the competitors into the matches array.

So for T0 we start with an empty 9 item matches array to be filled with the competitors. However our first competitor will be the last one and then we will continue from the first one like T9 -> T1 -> T2... -> T8. As I have experienced this odd initial ordering results simpler code but i am open to suggestions.

While we are filling the matches array of T0 with a value such as T9 (T0 line first item with dark green background) we also fill same index of the matches array of T9 with T0. (T9 line first item in red)

When we finish T0's matches and come to T1, we already have one item of T1's matches filled while we were calculating the T0 matches. (row T1 column 1, T0 in red) So we start after that one again with T9 and continue with T2 (not T1, since T1 can not play with itself) up until we reach T8. This is where the modulus arithmetic starts showing itself by assigning T8 at index 0.

So this is why I had to come up with some funny modular arithmetic;

(2*i+j) % mc: Is the calculated index to start inserting results
from T9 on.
(j+mc-i-1) % (mc-i)+i+1: Is the calculated index to pick
the competitor from the teams array.

Again i can not make exactly sure if they can be simplified any further but they seem perfectly functional as they are. This is where i need your help.

So the code is;

function fixture(ts){
  var mc = ts.length-1,  // match count is one less than the total number of teams.
      sp = 0,            // calculated start position to insert matches in the matches array.
      tm = 0;            // competing team's calculated index at the input (ts) array.
  return ts.map((t,i,a) => (a.slice(i+1)
                             .forEach(function(_,j,b){
                                        sp = (2*i+j) % mc;
                                        tm = (j+mc-i-1) % (mc-i)+i+1;
                                        t.matches[sp] = a[tm].id;
                                        a[tm].matches[sp] = t.id;
                                      })
                           ,t));
}

var tc = 10,
 teams = Array(tc).fill().map((_,i) => ({id: "Team_"+i, matches: Array(tc-1)}));
result = fixture(teams);
console.log(teams);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Advises to further simplify this code are most welcome.


texts: De Casteljau's algorithm to draw Bezier Curves in OOP and C++ (iterative version)

texts:
#include <iostream>
#include "Point2d.h"
#include "Collection.h"
#include "Coordinates2d.h"
#include "graphics.h"

#define PRECISION 0.01

Point2d Approximate(double t, Point2d const & pt1, Point2d const & pt2)
{
    double x = pt1.x * (1-t) + pt2.x * t;
    double y = pt1.y * (1-t) + pt2.y * t;

    return Point2d(x, y);
}

Collection<Point2d> GetBezierPoints(Collection<Point2d> const & points)
{
    Collection<Point2d> bezierPoints;

    for(double t = 0 ; t < 1 ; t = t + PRECISION)
    {
        Collection<Point2d> temp1 = points;

        while(temp1.size()>1)
        {
            Collection<Point2d> temp2;

            for(int i = 0 ; i<temp1.size()-1 ; i++)
            {
                Point2d pt1 = temp1[i];
                Point2d pt2 = temp1[i+1];

                temp2.Add(Approximate(t, pt1, pt2));
            }

            temp1 = temp2;
        }

        bezierPoints.Add(temp1[0]);//finally only one point will be left
    }

    return bezierPoints;
}

int main()
{
    Coordinates2d::ShowWindow("De Casteljau's algorithm");

    Collection<Point2d> points;

    points.Add(Point2d(0,0));
    points.Add(Point2d(80,300));
    points.Add(Point2d(120,-150));
    points.Add(Point2d(200,0));

    Collection<Point2d> list = GetBezierPoints(points);

    Coordinates2d::Draw(list);

    Coordinates2d::Wait();

    return 0;
}

NOTE: I am in love with my Collection<T> class, which is a wrapper around std::vector.


texts: Limit acceptable values for function parameter in VBA

texts:
I wrote a function in VBA for Excel that finds the highest row and highest column number in a range, which may include multiple, non-contiguous areas.

The function contains a parameter I call rowOrColumnOptionand I want to only allow values r or c (to return either a row or column number).

I was able to do this with an enumerated variable type:

Public Enum rowOrColumnOption
    ' Custom variable type, used to limit allowed values in a
    ' function parameter to either r (row) or "c" (column).
    r = 0: Row = 0
    c = 1: Column = 1
End Enum

I then assigned this variable type to a parameter in my function:

Public Function GetHighestRowOrCol(ByVal targetRange As Range, ByVal rowOrColumn As rowOrColumnOption) As Long

...some code...

If rowOrColumn = 0 Then
    ' Return the highest row number.
    '  0 corresponds to "Row" in the custom variable type "rowOrColumnOption".
    GetHighestRowOrCol = maxRow
ElseIf rowOrColumn = 1 Then
    ' Return the highest column number.
    '  1 corresponds to "Column" in the custom variable type "rowOrColumnOption".
    GetHighestRowOrCol = maxCol
Else
    ' Return an error value of zero.
    GetHighestRowOrCol = 0
End If

End Function

While this does work, I wonder if there is a better, simpler, faster, clearer, smarter way to do this, without using Enum. I am also open to any general critique/advice about the code overall.


texts: Munging select rows in CSV files using Pandas

texts:
I'm learning Pandas. I have a project where I need to munge some CSV files and resave them as CSV. I can use dictionaries and CSV module, but decided to use DataFrames to get more exposure and practice with Pandas.

The task is to sum() values for some keys while others are not summed. My solution was to add a column called "Line" where items with the same line number would be summed.

sales = [{"Line": 1, "KEY": "Apples", "AMOUNT": 3.99},
         {"Line": 1, "KEY": "Apples", "AMOUNT": 3.99},
         {"Line": 2, "KEY": "Oranges", "AMOUNT": 5.99},
         {"Line": 3, "KEY": "Pears", "AMOUNT": 2.99},
         {"Line": 3, "KEY": "Pears", "AMOUNT": 2.99},
         {"Line": 4, "KEY": "Carrots", "AMOUNT": .99},
         {"Line": 5, "KEY": "Carrots", "AMOUNT": .99},
        ]

df = pd.DataFrame(sales)

Now, Pandas groupby might seem like a perfect solution, but since I need to export the munged file as CSV, this seemed like something I could do only to have to undo.

# Find duplicate Line entries
# Subset df into just duplicate `Line` values
df_tmp = df[df.duplicated(subset="Line", keep=False)]

# Save a list of Line numbers to sum
line_dups = df_tmp['Line'].unique()

for x in line_dups:
    # Sum every line in the DF; one value sum is unchanged
    # asum = df.loc[df['Line'] == x, 'AMOUNT'].sum()
    # or
    # Subset the subset
    df_tmp2 = df_tmp[df_tmp["Line"] == x]
    # sum the sub-subset
    asum = df_tmp2['AMOUNT'].sum()
    # set the value of all keys with the same Line value
    df.loc[df['Line'] == x, 'AMOUNT'] = asum
    # take the inverse of the duplicate subset on the original df
    # Keep only the first duplicate line
    df2 = df[~df.duplicated(subset="Line", keep='first')]

The solution is effective, df2:

  AMOUNT    KEY     Line
0   7.98    Apples  1
2   5.99    Oranges 2
3   5.98    Pears   3
5   0.99    Carrots 4
6   0.99    Carrots 5

And yet, this solution is sort of hairy with all of the temp dataframes. Maybe a more seasoned Pandas user will have something to add which might help me better understand Pandas?


texts: A cross platform function to get current time in seconds with precision of micro second

texts:
double time_in_seconds() {
    std::chrono::time_point<std::chrono::system_clock,std::chrono::microseconds> tp = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now());
    auto tmp = std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch());
    std::time_t time_micro = tmp.count();
    return time_micro / 1000000.0;
}

Here C++11 chrono is used to be able run on multi platform. Use high_resolution_clock to hope to get precision of micro second. std::time_t should be enough to hold this number.


texts: Classifying the aspect ratio of the screen dimensions

texts:
In my project, I have three different userforms to display, optimized for three different aspect ratios. I need my code to call the screen resolution of the user's monitor, then check to see which category it belongs to, and finally choose the appropriate userform.

I've gotten as far as categorizing, but I'm self-taught and have been using absolutely horrendous code. I've just taken every aspect ratio available on our machines and put it into an if  then statement; when the correct if statement is triggered, it populates the variable Asp.

I'm absolutely certain there's a better way to do this. I would like to;

find a mathematical way to represent a "range" of ratios, as not every resolution in the 16:9 category, for example, is exactly 16/9, and
clean up the validation system that picks the right category for the user's setup. Possibly an array or a Case statement?

Declare Function getsystemmetrics32 Lib "User32" _
    Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long

Sub callAspectRatio()

Dim w As Long
Dim h As Long
Dim Asp As String

w = getsystemmetrics32(0)
h = getsystemmetrics32(1)

If w = 1920 And h = 1080 Then Asp = "16:9"
If w = 1680 And h = 1050 Then Asp = "16:9"
If w = 1600 And h = 900 Then Asp = "16:9"
If w = 1366 And h = 768 Then Asp = "16:9"
If w = 1360 And h = 768 Then Asp = "16:9"
If w = 1280 And h = 720 Then Asp = "16:9"
If w = 1280 And h = 600 Then Asp = "16:9"

If w = 1440 And h = 900 Then Asp = "8:5"
If w = 1280 And h = 1024 Then Asp = "8:5"
If w = 1280 And h = 960 Then Asp = "8:5"

If w = 1600 And h = 1200 Then Asp = "4:3"
If w = 1400 And h = 1050 Then Asp = "4:3"
If w = 1280 And h = 1024 Then Asp = "4:3"
If w = 1280 And h = 960 Then Asp = "4:3"
If w = 1152 And h = 864 Then Asp = "4:3"
If w = 1024 And h = 768 Then Asp = "4:3"
If w = 800 And h = 600 Then Asp = "4:3"

MsgBox Asp

End Sub


texts: Find if one list is a subsequence of another

texts:
So the problem of verifying if a list is a subsequence of another came up in a discussion, and I wrote code that seems to work (I haven't rigorously tested it).

IsSubequence.py

def is_subsequence(lst1, lst2):
    """
        *   Finds if a list is a subsequence of another.

        *   Params:
            *   `lst1` (`list`): The candidate subsequence.
            *   `lst2` (`list`): The parent list.
        *   Return:
            *   (`bool`): A boolean variable indicating whether `lst1` is a subsequence of `lst2`.
    """
    l1, l2 = len(lst1), len(lst2)
    if l1 > l2:  #`l1` must be <= `l2` for `lst1` to be a subsequence of `lst2`.
        return False
    i = j = 0
    d1, d2 = l1, l2
    while i < l1 and j < l2:
        while lst1[i] != lst2[j]:
            j += 1
            d2 -= 1
            if d1 > d2:  #At this point, `lst1` cannot a subsequence of `lst2`.
                return False
        i, j, d1, d2 = i+1, j+1, d1-1, d2-1
        if d1 > d2:
            return False
    return True

I'm primarily concerned about performance.


texts: PHP function to convert a Portuguese word from plural to singular

texts:
I know, this sounds really difficult, but it is really easy.

I needed to convert a single Portuguese word in the plural into singular. I know there's a right name for that, but it is escaping me.

The rules are simple, and will compile them from http://www.easyportuguese.com/portuguese-lessons/plural/ (but applying in reverse):

If the word ends in a vowel, remove the s at the end
Words ending in ões, ães and ãos should end with ão
Words ending in is, remove the is and add l to the end
Special case: accents should be removed, if needed. The only cases I saw were anéis and pastéis, which have to be anel and papel.
Words ending in ns get it replaced with m
Words ending with [rsz]es should lose the es
Special case: words ending in eses need the first e replaced with ê, like in meses => mês
Some words are always used in the plural, like óculos, parabéns and férias.

Below, here's the code:

function plural_to_singular($string)
{
    if(preg_match('/^(?:[oó]culos|parab[eé]ns|f[eé]rias)$/iu', $string))
    {
        return $string;
    }

    $regexes = array(
        '[õã]es' => 'ão',
        '[áó].*eis' => 'el',
        '[eé]is' => 'el',
        '([^eé])is' => '$1l',
        'ns' => 'm',
        'eses' => 'ês',
        '([rzs])es' => '$1',
        's' => ''
    );

    foreach($regexes as $fragment => $replace)
    {
        $regex = '/' . $fragment . '$/ui';
        if(preg_match($regex, $string))
        {
            return preg_replace($regex, $replace, $string);
        }
    }

    return $string;
}

You can try it on http://sandbox.onlinephpfunctions.com/code/7947a0efd16f361e89491e4a64f71b578d2278df with some testcases

In your opinion, what can I improve?

Is there any obvious butchering or performance killer?


texts:
I would really like to hear how I can improve my form validator. Next, I want to refactor it into OO and learn a testing framework like Jasmine.

Some things I know I could improve:

Don't make it tied to the DOM as much (using parent().parent(), for ex.).
Combined validations can't be used. For example, using isBlank and isInteger will not validate properly because if isInteger fails, it throws an error and isBlank passes and clears all errors.
Make a config object to update with custom error messages.
Possibly make a jQuery plugin so passing the object to validate is easier.

Github repo

  jQuery -> # on Document ready

    errorCount = null

    valEl = $('.validate')  # cache .validate elements
    submitBtn = valEl.parent().parent().find('input[type=submit]')

    valEl.on "blur", ->
      input = $(this)
      validate(input)

    validate = (input) ->
      inputVal = input.val()
      inputLen = inputVal.length
      validations = input.data()         #cache data-xxx tags

      if validations.notblank is on
        if inputLen <= 0
          throwError("This field can't be blank", input)
        else
          removeError(input)

      if validations.minchars > 0
        if inputLen < validations.minchars
          throwError("You need at least 5 chars", input)
        else
          removeError(input)

      if validations.isinteger is on
        isInteger = /^\d+$/
        if isInteger.test(inputVal) is false
          throwError("Must be a whole number", input)
        else
          removeError(input)

    throwError = (message, input) ->
      if !input.hasClass('has-error')
        errorCount += 1
        input.addClass "has-error"
        input.nextAll('.errorContainer').append(message)

    removeError = (input) ->
      if input.hasClass('has-error')
        errorCount -= 1
        input.removeClass("has-error")
        input.nextAll('.errorContainer').empty()

    submitBtn.on "click", (e) ->
      e.preventDefault()
      if errorCount is 0
        valEl.parent().parent().submit()


texts:
My question has to do with :

(a) Can this be made more secure?

(b) Are there best practices in relation to setting timezone?

(c) What best approach should be taken defining use of utf8?

        $my_success = 0;
        $my_message = '';
        $my_id = 0;

        try {

            # declare & set variables using $my_env
            list ($db_dbdriver, $db_hostname, $db_database, $db_username, $db_password) = Connection::dbConnect($my_env);

            # set default timezone
            date_default_timezone_set('America/Los_Angeles');

            # create & set connection
            $db_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
            $conn = new PDO($db_dbdriver . ":host=" . $db_hostname . ";dbname=" . $db_database . ";charset=utf8", $db_username, $db_password, $db_options);
            $conn->exec("set names utf8");
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

            # Prepare an SQL statement
            $my_sql = 'INSERT INTO Role (Role_Name, Role_CDate, Role_CBy, Role_EDate, Role_EBy)
                VALUES (:Role_Name, NOW(), :Role_CBy, NOW(), :Role_EBy)';
            $stmt = $conn->prepare($my_sql);

            # bind parameters to prevent SQL Injection
            $stmt->bindValue(':Role_Name', $role_name);
            # defaults to Now()...
            $stmt->bindValue(':Role_CBy', $role_cby);
            # defaults to Now()...
            $stmt->bindValue(':Role_EBy', $role_cby);

            # execute the SQL statement
            $stmt->execute();

            # closes the cursor, enabling the statement to be executed again
            $stmt->closeCursor();

            # grab ID value of the new record
            $my_id = $conn->lastInsertId();

            # close & unset the connection
            $stmt = null;
            unset($stmt);
            $conn = null;
            unset($conn);

            # Set success value to TRUE
            $my_success = 1;
            $my_message = 'success';

        } catch(PDOException $e) {

            # Catch error message
            $error_message = $e->getMessage();

            # Append error message to error log
            # ...

            # Set success value to FALSE & return an error message
            $my_success = -1;
            $my_message = $error_message;
            $my_id = 0;

        }


texts:
I have an Outlook PST file of a pretty big size (13 GB). For some indexing purpose I needed to scan through the full PST file to get all the PR_SEARCH_KEY and then write into a text file. This recursive procedure is used to loop through all folders and subfolders to get the PR_SEARCH_KEY from each email and non-email item. It took nearly 30 minutes to complete the full scan and writing into the text file.

How can I make this faster, such as for completing the process within 5 minutes?
  Is there any efficiency I'm missing here? I'm very new to Outlook and VB.NET.

Dim dict = New Dictionary(Of String, String)

Sub PrepareIndexing()
    Dim oApp As Outlook.Application
    Dim objName As Outlook.NameSpace
    Dim sFolder As Outlook.Folder
    oApp = CreateObject("Outlook.Application")
    objName = oApp.GetNamespace("MAPI")
    sFolder = objName.Folders.Item("pstname")

    dict.Clear()

    Call InitIndexing(sFolder)

    For Each d As KeyValuePair(Of String, String) In dict
        Using outputFile As New StreamWriter("E:\" & Convert.ToString("file.txt"), True)
            outputFile.WriteLine(d.Key & "," & d.Value)
        End Using
    Next
    dict.Clear()
End Sub

Sub InitIndexing(f As Outlook.Folder)
    Dim PropName, skey As String
    Dim oPA As Outlook.PropertyAccessor
    PropName = "http://schemas.microsoft.com/mapi/proptag/0x300B0102" 'Pr_Search_Key

    If f.Folders.Count > 0 Then
        For c = 1 To f.Folders.Count
            Dim Folder As Outlook.Folder = f.Folders.Item(c)
            Dim r As String = Folder.FolderPath
            For Each ml In Folder.Items
                oPA = ml.PropertyAccessor
                skey = oPA.BinaryToString(oPA.GetProperty(PropName))
                If Not dict.ContainsKey(skey) Then
                    dict.Add(skey, r)
                End If
            Next
            Call InitIndexing(Folder)
        Next
    End If
End Sub


texts:
My goal: I want to ping every single IPv4 address and record whether or not they responded.

The way I have it set up is every IP address corresponds to an index. For example 0.0.0.0 is index 0 and 0.0.1.0 is index 256. So if 0.0.0.0 responded, then the 0th element of the bitarray is true. At the end I write the bitarray to a file.

Here is the code:

import subprocess
from bitarray import bitarray
import threading
import time

response_array = bitarray(256 * 256 * 256 * 256)
response_array.setall(False)

def send_all_pings():
    index = 0
    for f1 in range(256):
        for f2 in range(256):
            for f3 in range(256):
                for f4 in range(256):
                    thread = PingerThread(".".join(map(str, [f1, f2, f3, f4])), index)
                    thread.start()
                    index += 1

    time.sleep(30)
    print("Writing response array to file")
    with open('responses.bin', 'wb') as out:
        response_array.tofile(out)

class PingerThread(threading.Thread):
    def __init__(self, address, index):
        threading.Thread.__init__(self)
        self.address = address
        self.index = index

    def run(self):
        if subprocess.call(["ping", "-c", "1", "-w", "1", self.address]) == 0:
            response_array[self.index] = True
        else:
            response_array[self.index] = False

What can I do to make this run faster? Any optimisations at all, even if very small, are welcome!


texts: Building array keys using a span of numbers for like values


texts:
I'm trying to learn basic algorithms which are typically taught in an introduction to CS course, which is usually taught in a compiled language like Java.  However, I want to focus on JavaScript, so I wrote the algorithms in JavaScript and encapsulated them into a library.

I'm looking for feedback on the efficiency of my implementations (bubbleSort, selectionSort, insertionSort):

/***************************************************************************************************
**ALGORITHMS
***************************************************************************************************/

(function () {
    "use strict";
    var $A,
        $P = {};

    (function manageGlobal() {
        if (window.$A && window.$A.pack) {
            $A = window.$A;
            $A.pack.algo = true;
        }
    }());

    $P.swap = function (arr, i, j) {
        var temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    };

    // checks to see if sorted
    $P.isSorted = function (arr) {
        var index_outer,
            length = arr.length;
        for (index_outer = 1; index_outer < length; index_outer++) {
            if (arr[index_outer - 1] > arr[index_outer]) {
                return false;
            }
        }
        return true;
    };

    // repeatedly orders two items ( a bubble ) at a time
    $P.bubbleSort = function (arr) {
        var index_outer,
            index_inner,
            swapped = false,
            length = arr.length;
        for (index_outer = 0; index_outer < length; index_outer++) {
            swapped = false;
            for (index_inner = 0; index_inner < length - index_outer; index_inner++) {
                if (arr[index_inner] > arr[index_inner + 1]) {
                    $P.swap(arr, index_inner, index_inner + 1);
                    swapped = true;
                }
            }
            if (swapped === false) {
                break;
            }
        }
        return arr;
    };

    // repeatedly finds minimum and places it the next index
    $P.selectionSort = function (arr) {
        var index_outer,
            index_inner,
            index_min,
            length = arr.length;
        for (index_outer = 0; index_outer < length; index_outer++) {
            index_min = index_outer;
            for (index_inner = index_outer + 1; index_inner < length; index_inner++) {
                if (arr[index_inner] < arr[index_min]) {
                    index_min = index_inner;
                }
            }
            if (index_outer !== index_min) {
                $P.swap(arr, index_outer, index_min);
            }
        }
        return arr;
    };

    // repeatedly places next item in correct spot using a "shift"
    $P.insertionSort = function (arr) {
        var index_outer,
            index_inner,
            value,
            length = arr.length;
        for (index_outer = 0; index_outer < length; index_outer++) {
            value = arr[index_outer];
            for (index_inner = index_outer - 1; (index_inner >= 0 && (arr[index_inner] > value));
                    index_inner--) {
                arr[index_inner + 1] = arr[index_inner];
            }
            arr[index_inner + 1] = value;
        }
        return arr;
    };

    // module complete, release to outer scope
    $A = $A.extendSafe($A, $P);
}());


texts: Creating a user profile from an omniauth hash

texts:
I have this code that creates (or updates) a user from an omniauth hash parameter:

  def self.find_or_create_from_auth_hash(auth_hash)
    uid = auth_hash['uid']
    provider = auth_hash['provider']

    user = find_or_create_by(uid: uid, provider: provider)

    user.name = auth_hash['info']['name'] || ''
    user.email = auth_hash['info']['email']
    user.nickname = auth_hash['info']['nickname']
    user.avatar = auth_hash['info']['image'] || ''

    user.access_token = auth_hash['credentials']['token']

    user.location = auth_hash['extra']['raw_info']['location'] || ''
    user.company = auth_hash['extra']['raw_info']['company'] || ''
    user.member_since = auth_hash['extra']['raw_info']['created_at'] || ''

    user if user.save
  end

It is working, but it looks unpleasant. What can be changed in this piece of code, making it easier to read and/or beautiful?


texts: Python program to solve the "rod-cutting problem"

texts:
An assignment at school required me to write a program for this task:

  In the rod-cutting problem, we are given a rod of length n inches and
  a table of prices p[i] for i = 1, 2, …, n. Here p[i] is the price of a
  rod of length iinches. We have to find the optimal way of cutting the
  rod so that maximum revenue can be generated by selling the pieces.

Here is my solution to this task (in Python):

def cut_rod(p, n):
    """
    Take a list p of prices and the rod length n and return lists r and s.
    r[i] is the maximum revenue that you can get and s[i] is the length of the
    first piece to cut from a rod of length i.
    """
    # r[i] is the maximum revenue for rod length i
    # r[i] = -1 means that r[i] has not been calculated yet
    r = [-1]*(n + 1)

    # s[i] is the length of the initial cut needed for rod length i
    # s[0] is not needed
    s = [-1]*(n + 1)

    cut_rod_helper(p, n, r, s)

    return r, s

def cut_rod_helper(p, n, r, s):
    """
    Take a list p of prices, the rod length n, a list r of maximum revenues
    and a list s of initial cuts and return the maximum revenue that you can get
    from a rod of length n.

    Also, populate r and s based on which subproblems need to be solved.
    """
    if r[n] >= 0:
        return r[n]

    if n == 0:
        q = 0
    else:
        q = -1
        for i in range(1, n + 1):
            temp = p[i] + cut_rod_helper(p, n - i, r, s)
            if q < temp:
                q = temp
                s[n] = i
    r[n] = q

    return q

n = int(input('Enter the length of the rod in inches: '))

# p[i] is the price of a rod of length i
# p[0] is not needed, so it is set to None
p = [None]
for i in range(1, n + 1):
    price = input('Enter the price of a rod of length {} in: '.format(i))
    p.append(int(price))

r, s = cut_rod(p, n)
print('The maximum revenue that can be obtained:', r[n])
print('The rod needs to be cut into length(s) of ', end='')
while n > 0:
    print(s[n], end=' ')
    n -= s[n]

where s[n] gives us the length of the first piece, s[n – s[n]] gives us the length of the second piece and so on.

Here is an example output -

Enter the length of the rod in inches: 3
Enter the price of a rod of length 1 in: 3
Enter the price of a rod of length 2 in: 7
Enter the price of a rod of length 3 in: 2
The maximum revenue that can be obtained: 10
The rod needs to be cut into length(s) of 1 2

Times taken for each function -

%timeit cut_rod(p, n)
7.65 µs ± 71.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit cut_rod_helper(p ,n, r, s)
266 ns ± 3.97 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

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

Any help would be highly appreciated.


texts: AutoSuggest: Better way to implement focus after inserting a snippet

texts:
Introduction:

I am working on a javascript plugin AutoSuggest, My aim is to create an IDE like autocomplete experience in web applications using JavaScript.

One of the features I have implemented is focusing a particular portion of inserted snippet after insertion. This is how I am asking input for focus.

  focusText: [StartIndex, EndIndex]

  StartIndex and EndIndex of the content that should be in focus
  after inserting the text. As of now these indexes should be calculated
  as (0 - numberOfCharactersFromEnd)

  focusHtml: [StartIndex, EndIndex]

  StartIndex and EndIndex of the content that should be in focus after  inserting the HTML. As of now these indexes should be calculated as (0 -  numberOfCharactersFromEnd). This should not include the characters from  HTML tags

Example:

{
    value: 'script',
    insertText: '


texts:
I've been working on a 3D mathematical vector class which should be as streamlined as possible for use in numerical simulations. It will be used to model 3D-physical vectors.

Here, 3D-vector should be taken in mathematical sense, meaning a tuple (a,b,c).

I hoped to design it in a modern and fast way - but one is never perfect. So, I would be interested in some input from your side.  Any tips for making this faster?

//threevector.h
#ifndef threevector_h_
#define threevector_h_

#include <fstream>
#include <cmath>
#include <array>

template <class T>
class threevector
{
private:
  static const int dim = 3; //dimension of vector
  std::array<T,dim> container;

public:

  //constructors and assignment
  threevector(const double a = 0, const double b = 0, const double c = 0):
  container({{a,b,c}}) {}; //standard constructor
  threevector(const threevector& a): container(a.container) {};
  //copy constructor

// add once gcc 4.7 is used
//   threevector(threevector&& other): threevector() {swap(*this, other);}
  // move constructor

  threevector& operator=(threevector rhs) //assignment
  {
    swap(*this, rhs);
    return *this;
  }

  void swap(threevector& first, threevector& second)
  {first.container.swap(second.container);}

  //operators
  threevector& operator+=(const threevector& rhs)
  {
    container[0] += rhs.container[0];
    container[1] += rhs.container[1];
    container[2] += rhs.container[2];
    return *this;
  }

  threevector& operator-=(const threevector& rhs)
  {
    *this += -rhs;
    return *this;
  }

  threevector& operator*=(const double rhs) //scalar multiplication assignment
  {
    container[0] *= rhs;
    container[1] *= rhs;
    container[2] *= rhs;
    return *this;
  }

  threevector& operator/=(const double rhs) //scalar division assignment
  {
    *this *= 1./rhs;
    return *this;
  }

  threevector operator+() const //unary plus
  {
    threevector a(*this);
    return a;
  }

  threevector operator-() const //unary minus
  {
    threevector a(*this);
    a *= -1;
    return a;
  }

  T& operator[](const int input) {return container[input];} //access operator

  const T& operator[](const int input) const {return container[input];}
  // const access operator

  //utility functions
  double abs() const
  {return sqrt(container[0]*container[0]+container[1]*container[1]+
   container[2]*container[2]);}
  double abs_sq() const {return pow(abs(),2);}
  void reset() { container[0] = 0; container[1] = 0; container[2] = 0;}
};

//output operator
template<class T>
std::ostream& operator<<(std::ostream& os, const threevector<T>& obj)
{
  os << std::fixed << "(" << obj[0] << "," << obj[1] << "," << obj[2] << ")";
  return os;
}

//addition operator
template<class T>
inline threevector<T> operator+(threevector<T> lhs, const threevector<T>& rhs)
{
  lhs += rhs;
  return lhs;
}

//subtraction operator
template<class T>
inline threevector<T> operator-(threevector<T> lhs, const threevector<T>& rhs)
{
  lhs -= rhs;
  return lhs;
}

//scalar product
template<class T>
inline double operator*(const threevector<T>& lhs, const threevector<T>& rhs)
{return lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2];}

//product with scalar
template<class T>
inline threevector<T> operator*(const double lhs, threevector<T> rhs)
{
  rhs[0] *= lhs;
  rhs[1] *= lhs;
  rhs[2] *= lhs;
  return rhs;
}

//product with scalar
template<class T>
inline threevector<T> operator*(threevector<T> lhs, const double rhs){return rhs*lhs;}

// scalar division
template<class T>
inline threevector<T> operator/(threevector<T> lhs, const double rhs){return lhs*(1./rhs);};

#endif


texts:
Here is my code for printf() implementation in C. Please share your thoughts for improvements.

#define PRINTCHAR(c) putchar(c)
#define MAXLEN 256

// Write a printf function which simulates printf() in C.
int formatAndPrintString(char *pcFmt, va_list lList)
{
    //Holds the number of characters printed, 0 on error
    int nChars = 0;

while(*pcFmt != '\0')
{
    if(*pcFmt == '%')
    {
        pcFmt++;

        int iTemp = 0;
        char acTemp[MAXLEN] = "";
        char *pcTemp = NULL, cTemp = 0;

        switch (*pcFmt)
        {
        case 'd':
            iTemp = va_arg(lList, int);
            itoa(iTemp, acTemp, 10);

            for(int i = 0; i < strlen(acTemp); i++)
            {
                PRINTCHAR(acTemp[i]); nChars++;
            }
            break;
        case 's':
            pcTemp = va_arg(lList, char*);

            while(*pcTemp != '\0')
            {
                PRINTCHAR(*pcTemp); nChars++;
                pcTemp++;
            }
            break;
        case 'c':
            cTemp = va_arg(lList, int);
            PRINTCHAR(cTemp);
            nChars++;
            break;
       default:
          break;
       }
       pcFmt++;
    }
    else
    // print the char to console
    {
       PRINTCHAR(*pcFmt);
       pcFmt++; nChars++;
    }
}
return nChars;
}

// Print function identical to printf() in stdio.h
int printfunc(char *pcFormat, ...)
{
    if(!pcFormat)
    {
        return 0;
    }

    va_list lList;
    va_start(lList, pcFormat);

    return(formatAndPrintString(pcFormat, lList));
}


texts: Find valid triples for a sorted list of integers

texts:
I'm working on a problem in which I have an input array, sorted positive unique integers, and have to try to find all possible triples \$(x,y,z)\$ which satisfy \$x+y>z\$ and \$x<y<z\$. For example, \$(1,2,3)\$ is not a valid triple since \$1+2\$ is not \$> 3\$, and \$(3,4,5)\$ is a valid triple since \$3<4<5\$ and \$3+4>5\$.

This code leverages binary search, and I'm wondering if this can be improved in terms of time complexity. Please also help to point out any code issues/bugs or improvement areas.

Implementation

# find upper bound of value, including value itself
def findUpperBound(numbers, value, start):
    if not numbers:
        raise 'value eror'
    low = start
    high = len(numbers) - 1
    while low <= high:
        mid = (low + high) // 2
        if numbers[mid] == value:
            return mid
        elif numbers[mid] > value:
            high = mid - 1
        else:
            low = mid + 1
    # if reach here, means find an upper bound
    return low

if __name__ == "__main__":

    result = set()
    numbers=[1,2,4,5,6,7,8,10]
    for i in range(0, len(numbers)-2):
        for j in range(i+1, len(numbers)-1):
            k = findUpperBound(numbers, numbers[i] + numbers[j], j+1)
            for p in range(j+1, k):
                result.add((numbers[i], numbers[j], numbers[p]))

    print result

Output

set([(5, 7, 10), (4, 6, 8), (5, 7, 8), (4, 8, 10), (6, 8, 10), (2, 6, 7), (5, 6, 7), (4, 5, 6), (5, 6, 8), (2, 4, 5), (5, 6, 10), (2, 7, 8), (5, 8, 10), (4, 7, 8), (7, 8, 10), (6, 7, 8), (2, 5, 6), (6, 7, 10), (4, 5, 7), (4, 5, 8), (4, 6, 7), (4, 7, 10)])


texts: Converting double to string without scientific notation and without losing digits

texts:
Requirements:

Must convert a double to a string, without losing any digits.
Cannot use scientific notation.

In C#, no format string exists that you can you pass into Double.ToString(format) to accomplish this, because ToString will use only 15 digits, even though a double can have 17. Although R and G17 can use 17 digits, it may or may not use scientific notation.

Please correct me if I am wrong.

Therefore, I wrote a function to do this. I'm posting it here as an optimization question. If you see flaws, feel free to point them out. I'm confident the code works, but there's plenty of room for improvement.

[Fact]
public void NumberFormats()
{
    double d1 = 123456789012171.23;
    double d2 = 0.0000000000000001;
    double d3 = 10000000000000000;

    string s1 = DoubleToString(d1);
    string s2 = DoubleToString(d2);
    string s3 = DoubleToString(d3);

    Assert.Equal("123456789012171.23", s1);
    Assert.Equal("0.0000000000000001", s2);
    Assert.Equal("10000000000000000", s3);
}

private string DoubleToString(double d)
{
    string R = d.ToString("R", CultureInfo.InvariantCulture).Replace(",", "");
    int i = R.IndexOf('E');

    if (i < 0)
        return R;

    string G17 = d.ToString("G17", CultureInfo.InvariantCulture);

    if (!G17.Contains('E'))
        return G17.Replace(",", "");

    // manual parsing
    string beforeTheE = R.Substring(0, i);
    int E = Convert.ToInt32(R.Substring(i + 1));

    i = beforeTheE.IndexOf('.');

    if (i < 0)
        i = beforeTheE.Length;
    else
        beforeTheE = beforeTheE.Replace(".", "");

    i += E;

    while (i < 1)
    {
        beforeTheE = "0" + beforeTheE;
        i++;
    }

    while (i > beforeTheE.Length)
    {
        beforeTheE += "0";
    }

    if (i == beforeTheE.Length)
        return beforeTheE;

    return String.Format("{0}.{1}", beforeTheE.Substring(0, i), beforeTheE.Substring(i));
}


texts: Uncompress archive, check contents, add missing files, recompress archive

texts:
The code looks for the specified .tgz file, if it's not present, it creates it. It looks for files ending in .txt in the cwd and adds them to a list. It decompresses the gzip, checks for the .txt files in the tar, adds the missing files to the tar and then recreates the compressed gzip with the new files in it. It then deletes the temporarily created tar file.

This is a self assigned script to learn the basics of working with compressed tarballs.

Please take a look and let me know if there are problems that can be accounted for or improvements that can be made. I'm only a few weeks into python, there is still a lot that I don't know.

#!usr/bin/python3

import os, gzip
import tarfile
import sys
import shutil
import send2trash

myFL = []
notThere = []
feil = '/home/pi/python/chap9OrganizingFiles/shutildir/comp.tgz'
outfeil = '/home/pi/python/chap9OrganizingFiles/shutildir/comp.tar'

if os.path.isfile(feil):
        print('File found, opening ' + os.path.relpath(feil))
else:
        print('File does NOT exist, creating ' + os.path.relpath(feil))
        with tarfile.open(feil, 'w:gz'): print('File Created')

with tarfile.open(feil, 'r:gz') as tar:
        myDirList = os.chdir('/home/pi/python/chap9OrganizingFiles/shutildir/')
        print('Current directory is: ' + os.getcwd() + '\n\n')
        for dirList in os.listdir(os.getcwd()):
                myFL.append(dirList)
        for listItem in myFL:
                if listItem in tar.getnames():
                        print("There: " + listItem)
                else:
                        if listItem.endswith('.txt'):
                                notThere.append(listItem)

print('\n\n')
for li in notThere: print('Text file not in tarball: ' + li)

with gzip.open(feil, 'rb') as unzip, open(outfeil, 'wb') as out:# open the gzip file
        out.write(unzip.read()) # read the gzip file into the output file

def addToTar(ntlist):
        with tarfile.open(outfeil, 'a') as tar:
                for ntLI in ntlist:
                        tar.add(ntLI)
                        print('Item added: ' + ntLI)

addToTar(notThere)

with open(outfeil, 'rb') as uf, gzip.open('/home/pi/python/chap9OrganizingFiles/shutildir/comp.tgz', 'wb') as of:
        shutil.copyfileobj(uf, of)

send2trash.send2trash(outfeil)
print('\nAll done and cleaned up.')


texts:
I'm working on socket programming in C. I have no problem with usage the threads. This all works fine but I'm new in this area. I wrote this code in client.c but is there any misused code or something may cause problems in the future?
My client sends a message to the server and client can receive it. There are 2 major operations: recv and send.
CLIENT
#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h> // for inet_addr
#include <string.h>
#include <zconf.h>
#include <stdlib.h>
#include <pthread.h>

void *sendMessage(void *sock_desc) {
    //Send some data
    while (1) {
        char message[2000];
        printf("%s","> ");
        scanf("%[^\n]%*c", message);
        fflush(stdin);

        if (send(*((int *) sock_desc), message, strlen(message) + 1, 0) < 0) {
            puts("Send failed");
        }
    }
}

void *receiveMessage(void *sock_desc) {
    while (1) {
        char server_reply[2000];
        if (recv(*((int *) sock_desc), server_reply, 2000, 0) < 0) {
            puts("recv failed");

        }
        //Receive a reply from the server
        printf("\033[32;1m %s \033[0m\n", server_reply);
    }
}

int main(int argc, char *argv[]) {
    int                sock;
    struct sockaddr_in server;
    //char               message[2000], server_reply[2000];

    //Create socket
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        printf("Could not create socket");
    }

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family      = AF_INET;
    server.sin_port        = htons(8888);

    //Connect to remote server
    if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) {
        perror("Connect failed. Error");
        return 1;
    }

    puts("Connected to server\n");
    int *new_sock;
    new_sock = malloc(1);
    *new_sock = sock;
    //keep communicating with server

    pthread_t send_thread, receive_thread;
    pthread_create(&send_thread, NULL, sendMessage, (void *) new_sock);
    pthread_create(&receive_thread, NULL, receiveMessage, (void *) new_sock);

    pthread_join(receive_thread, NULL);
    pthread_join(send_thread, NULL);

    close(sock);
    return 0;
}


texts:
I am preparing for an interview, and here's a popular problem on the dynamic programming. And I want to see if there's any feedback or code review for my solution at dynamic programming question.

#  Problem: Coin Sum
#
#  Given an array of coins and a target total, return how many
#  unique ways there are to use the coins to make up that total.
#
#  Input:  coins {Integer Array}, total {Integer}
#  Output: {Integer}
#
#
#  Example:
#  Input:  [1,2,3], 4
#  Output: 4
#
#  1+1+1+1
#  1+3
#  1+1+2
#  2+2
#
#
#  Input:  [2,5,3,6], 10
#  Output: 5
#
#          2+3+5
#          5+5
#          2+3+2+3
#          2+2+6
#          2+2+3+3
#

#  Note: You have an unlimited number of each coin type. All coins in the
#        coin array will be unique
#        Order does not matter. Ex: One penny and one nickel to create six
#        cents is equivalent to one nickel and one penny
#
#

def coin_sum(coins, total):
    # tabulation way
    arr = [1] + [0] * total
    for coin in coins:
        for i in range(coin, total + 1):
            arr[i] += arr[i - coin]
    return 0 if total == 0 else arr[total]

# Time Complexity: O(N*M), let the number of coins be m.
# We iterate from arr[coin] -> arr[n], or ~ n operations on each coin, hence n*m.
# Auxiliary Space Complexity: O(N)

It passes all of the following 5 tests for my Coin sum tests:

def expect(count, name, test):
    if (count == None or not isinstance(count, list) or len(count) != 2):
        count = [0, 0]
    else:
        count[1] += 1

    result = 'false'
    errMsg = None
    try:
        if test():
            result = ' true'
            count[0] += 1
    except Exception as err:
        errMsg = str(err)

    print('  ' + (str(count[1]) + ')   ') + result + ' : ' + name)
    if errMsg != None:
        print('       ' + errMsg + '\n')

def lists_equal(lst1, lst2):
    if len(lst1) != len(lst2):
        return False
    for i in range(0, len(lst1)):
        if lst1[i] != lst2[i]:
            return False
    return True

print("\nCoin Sum Tests")
test_count = [0, 0]

def test():
    example = coin_sum([1, 2, 3], 4)
    return example == 4

expect(test_count, 'should work for first example case', test)

def test():
    example = coin_sum([2, 5, 3, 6], 10)
    return example == 5

expect(test_count, 'should work for second example case', test)

def test():
    example = coin_sum([2], 10)
    return example == 1

expect(test_count, 'should work for a single coin', test)

def test():
    example = coin_sum([7, 15], 20)
    return example == 0

expect(test_count, 'should work when there is no solution', test)

def test():
    example = coin_sum(
        [78, 10, 4, 22, 44, 31, 60, 62, 95, 37, 28, 11, 17, 67, 33, 3, 65, 9, 26, 52, 25, 69, 41, 57, 93, 70, 96, 5,
         97, 48, 50, 27, 6, 77, 1, 55, 45, 14, 72, 87, 8, 71, 15, 59], 100)
    return example == 3850949

expect(test_count, 'should work for variety of coins and large total', test)

print(('\nPASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1])))


texts:
I've made a dropdown menu using angularJS, it works fine but I feel that I'm not following the DRY principle. Is there a way to combine this switch statement into something more efficient with less code? Instead of having 3 "cases" can I just use an OR operator inside of a data-ng-switch-when or something like that? This code will get bigger because it's quite a big project so code efficiency is key.

{{item}}

{{subitem}}

{{subitem}}

{{subitem}}

Here's my controller containing the menu items:

onlinePlatform.controller('onlinePlatformCtrl', function ($scope) {

    $scope.mainMenu = ['Startsida', 'Nyheter', 'Meddelanden', 'Mina sidor', 'Forum', 'Kalender', 'Verktyg', 'Hjälp'],
    $scope.subMenu = {
        messages: ['Inkorg', 'Skickat', 'Borttaget'],
        myPages: ['Mina kurser', 'Mitt schema', 'Klasslista', 'Anteckningar'],
        tools: ['Ladda ner Dreamspark produkter']
    }

});


texts:
I need to select the <table> before the table where the link I clicked. I can't use IDs, because I don't want to edit my jQuery every time I add a new table.

but this looks kinda bloated for me:

$(this).closest("table").prevAll("table").first().css( "background", "yellow" );

take a look here: http://jsfiddle.net/syddmxfn/13/


texts:
To start with Common Lisp I am doing Project Euler using this language. Usually I manage to solve problems but I am quite sure that my code is not as efficient as it could be in Common Lisp. That is why I need a review from experienced lispers.

This is my code for problem 35. Please offer any improvements.

(defun prime-p (n)
  (cond
    ((= n 1) nil)
    ((= n 2) t)
    ((evenp n) nil)
    (t (loop for i from 3 to (isqrt n) by 2
      never (zerop (mod n i))))))

(defun list->num (lst)
  (loop for i in lst
       for p = (- (length lst) 1) then (- p 1)
       sum (* i (expt 10 p))))

(defun num->list (n)
  (loop for c across (write-to-string n)
       collect (parse-integer (string c))))

(defun rotate (lst)
  (append (last lst) (butlast lst)))

(defun number-rotations (n)
  (let* ((digits (num->list n))
         (digits-count (length digits)))
    (loop repeat digits-count
       for rotated = digits then (rotate rotated)
       collect (list->num rotated))))

(defun problem-35 (limit)
  (let ((hash-primes (make-hash-table)))
    (loop for n from 1 to limit
       if (prime-p n)
       do (setf (gethash n hash-primes) t))
    (loop for p being the hash-keys in hash-primes
       if (loop for n in (number-rotations p)
         always (gethash n hash-primes))
       collect p)))


texts: Efficient ways of looking for start-key and processing data

texts:
This question is a follow up from my previous question.

I am working with some wireless communication in Arduino.

979797 is the address of the transmitter. I have written the following code to check the address first before processing the data. My main concern is speed of computation.

void printBuffer(const uint8_t *serialBuffer)
{
  //print contents of buffer
  for (int i = 0; i<100; i++)
    Serial.println(serialBuffer[i]); //remove the print in binary option to decode
}

void processBytes(const uint8_t value)
{
  static uint8_t serialBuffer[bufferSize]; //buffer to hold values
  static unsigned int startPosition=0;

  if(startPosition < bufferSize)
  {
    serialBuffer[startPosition] = value;
    startPosition++;
  }

  else
  {
    printBuffer(serialBuffer);
    startPosition = 0;
  }

}//end of processBytes
void loop() {

  //check if data is available in serial buffer
  while(RX.available())
  {
    //check for start key
    address(RX.read())
    //process data
    for(int i = 0; i< 68; i++)
        processBytes(RX.read());
  }
}
void address(const uint8_t value)
{
  int counter = 0;
  int newVal = value;
  while(value == 97 && counter < 3)
  {
    counter++;
    newVal = RX.read();
  }
}

The data packet just has the following components: start key (979797) and 68 bytes of data(payload). There is no termination key. Also, the transmitter transmits one byte at a time. Thus, each value received is less than 256. Hence why I am saving the data into a uint8_t[] array.

Example of possible data:

97 97 97 (68 bytes of random positive integers all less than 256) 97 97 97

Other than the address() method, most of it was borrowed from Gammon. Here is the reference page for the arduino commands I am using. Are there ways I can optimize this computation?


texts:
Let's say that i have a database which contain cheese. I love cheese.
Depending on the request my server is getting (c# WebApi), i have to filter user data accordingly.
Maybe the user wants to only get cheese up to a certain date, or from a certain date, or between to dates. Maybe he wants all french cheese, or american cheese.
My model works, but i dont like switchs, and i feel like there is a better way.

The model is as follow :

namespace myAPI.Models
{
    public enum CheeseFilter
    {
        Country,
        DateFrom,
        DateStart,
        DateBetween,
    };

    public class FilterQuery
    {
        public CheeseFilter? filter { get; set; }
        public DateTime? DateStart{ get; set; }
        public DateTime? DateEnd{ get; set; }
        public String Country{ get; set; }

    }
}

This model is what's get filled [FromPost]
Now, i'm creating a tuple which will hold the StoredProcedure name (Basically, a select with where, order by, etc), its parameters, and the choosen filter, like so :

       private Tuple<CheeseFilter, String, List<SqlParameter>> LoadedCheeseWithOptions;

And where i actually fill it :

public bool CheeseFilterTuple()
        {
            bool flag = false;
            List<SqlParameter> options = new List<SqlParameter>();
            String SPName = "ERROR";
            DateTime tmp = new DateTime(); // ForChecking GoodFormating of datetimes
            DateTime tmp2 = new DateTime();
            switch (GetMode().Value)
            {
                case CheeseFilter.DateFrom:
                    flag = !String.IsNullOrWhiteSpace(dateStart) && DateTime.TryParseExact(dateStart, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);;
                    options.Add( new SqlParameter() { Name =  "@DateStart", Value = tmp.ToString("yyyyMMdd")});
                    SPName = "Cheese_FromDate";
                    break;
                case CheeseFilter.DateStart:
                    flag = !String.IsNullOrWhiteSpace(dateEnd) && DateTime.TryParseExact(dateEnd, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);
                    options.Add(new SqlParameter() { Name = "@DateEnd", Value = tmp.ToString("yyyyMMdd") });
                    SPName = "Cheese_To_Date";
                    break;
                case CheeseFilter.BetweenDates:
                    flag = !String.IsNullOrWhiteSpace(dateStart) && DateTime.TryParse(dateStart, out tmp) && !String.IsNullOrWhiteSpace(dateEnd) && DateTime.TryParse(dateEnd, out tmp2);
                    options.Add( new SqlParameter() { Name = "@DateStart",Value =  tmp.ToString("yyyyMMdd")}); //Converting for sqlServer
                    options.Add( new SqlParameter() { Name = "@DateEnd", Value = tmp2.ToString("yyyyMMdd")});
                    SPName = "Cheese_Between_Date";
                    break;

            }
            LoadedCheeseWithOptions = new Tuple<CheeseFilter, string, List<SqlParameter>>(GetMode().Value, SPName, options);
            return flag;
        }

GetMode() is just transforming the CheeseFilter? into a CheeseFilter.

The main issue is that, with this last bit of code here, i feel like with every new filter that I might get asked to create will mean adding another block of code to the pile, which I think is a poor man's solution.

So I'm asking you for some guidelines, or even better ways that'd you handle better this optional filter loading.


texts:
This works but feels like alot of code for what it accomplishes. I feel like I'm maybe missing something obvious.

// When current month is same as target month, then return the current day of the month.
// Else return the number of days in the target month.
static int DefaultDaysToSynch()
{
    var now = DateTime.Now;
    int result = now.Day;
    int month = Properties.Settings.Default.StatsMonth;
    int year = Properties.Settings.Default.StatsYear;
    if (!((year == now.Year) && (month == now.Month)))
    {
        result = DateTime.DaysInMonth(year, month);
    }
    return result;
}


texts: Vue.js code to update selection on screen

texts:
I have the following code snippet:

    WHU
    20 Oct
    BHA

    CHE
    21 Oct
    WAT

and the following VueJS method:

methods: {
            changeTeam(selection) {
                this.team = selection;
            }
         }

So as you can see, I'm calling this function and passing in the value in the table cell (i.e.  tag) to change a selection. This works for me, but is there a way I can capture the contents of the table cell, by means of some other method? Something a little more reusable or would this just be introducing extra overhead?

The table itself is the result of a dynamically generated page, so I'm not overly bothered about the apparent duplication.


texts: Efficient implementation of a Dynamic Programming challenge

texts:
I wrote the following code for a Dynamic Programming problem but the online judge gives me a 'Time Limit Exceeded' error.  How can I optimize this code to make it more efficient, especially the part of initializing the DP array to 0.0 (I am using memset() right now)?

Problem:

There are N values in an array. Two players take turn by turn to play the game.
Player1, with 50% probability can pick the left most value or the right most value.
3.If there is only one value left in the array, the player, having no more choice, will just pick up that value.
Question is to calculate the expected sum of values that First player can obtain.
\$T <= 500\$ and \$N <= 2000\$

#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cstring>
using namespace std;
#define max  2000
int main(){
    int T;
    double **dp = new double*[max];
    for(int i=0; i<max; ++i)
            dp[i] = new double[max];
    cin >> T;
    while(T--){
            int N;
            cin >> N;
            int V[N];
            for(int i=0; i<N; ++i)
                    cin >> V[i] ;
            for(int i=0; i<N; ++i)
                    memset(dp[i], 0.0, sizeof(dp[0][0])*N);
            for(int i=0; i<N; ++i)
                    dp[i][i] = V[i];
            for(int j=1; j<N; ++j)
                    for(int i=j-1; i>=0; --i){
                            dp[j][i] = 0.5 * ( dp[i][i] + dp[j][j] + dp[j-1][i+1] );
                            if( (i+2)<N )
                                    dp[j][i] += (0.250 * dp[j][i+2]);
                            if( (j-2)>=0 )
                                    dp[j][i] += (0.250 * dp[j-2][i]);
                    }
            cout << setprecision (5) << dp[N-1][0] << endl;
    }
    for(int i=0; i<max; ++i)
            delete[] dp[i];
    delete dp;
    return 0;
}


texts:
I'm new to MVC and i'm having some difficulty on understanding the proper usage of ViewModels and Controllers.

I have this example where i will list several different informations in my HomeController as CTAs, Banners, News, Courses... and i came up with this ViewModel structure after some research :

public class CoursesViewModel
{
    private readonly Entities _db = new Entities();
    public List<Courses> Courses { get; private set; }

    public Courses ViewModel() { Initialize( "", "", 0 ); }

    public CursosViewModel( string where, string order, int take ) { Initialize( where, order, take ); }

    private void Initialize( string where, string order, int take )
    {
        IQueryable<Curso> query = _db.Curso;

        if( !string.IsNullOrEmpty( where ) )
            query = query.Where( @where );

        if( !string.IsNullOrEmpty( order ) )
            query = query.OrderBy( @order );

        if( take > 0 )
            query = query.Take( @take );

        Courses = query.ToList();
    }
}

public class BaseViewModel
{
    private readonly Entities _db = new Entities();

    public Page Page { get; private set; }
    public List<State> States { get; private set; }
    public List<HtmlBlock> Blocks { get; private set; }

    public Page GetPage( int pageId )
    {
        return Pagina = _db.Page.FirstOrDefault( x => x.ID == pageId ) ?? new Page();
    }

    public void SetBlocks( Page page )
    {
        Page = page;
    }

    public void SetBlocks( List<HtmlBlock> blocks )
    {
        Blocks = blocks.OrderBy( x => x.Ordem ).ToList();
    }

    public void SetStates( List<State> states )
    {
        States = states;
    }
}

And this is my Controller:

public class HomeController : Controller
{
    private readonly Entities _Db = new Entities();

    [MinifyHtml]
    public ActionResult Index()
    {
        var HtmlParser = new HtmlParser();
        var Redirect   = HelperMethods.GetRouteRedirect( HttpContext );
        var BaseVM     = new BaseViewModel();

        var page = BaseVM.GetPage( Redirect.pageId );

        if( page == null ) return new TransferResult( "/not-found" );

        //My ViewModel calls happen inside the HtmlParser.ParseBlocks,
        //there i will get the right ViewModel to each View and instantiate it
        BaseVM.SetBlocks( HtmlParser.ParseBlocks( page.html, ControllerContext ) );
        BaseVM.SetStates( ViewBag.states );

        return View( BaseVM );
    }
}

Is this the correct "usage" for the ViewModel and Controller ? Should i use my Entities (_db) inside a closure ( using ) ? Why ?

Another thing, i have some common information that exists on every page, how can i work with this on ViewModels without repeating the properties on each ViewModel. I created a BaseViewModel, should i extend it on every ViewModel  or should i implement it as a property ?


texts:
Friends A, B, C, D go for a trip.
They spend on various expenses.
Cost of the expense is shared.

Example :

A spends 100 for breakfast for A, B, C and D
D spends 500 for cab for B and C
B spends 300 for lunch for A, B and C

Write a program to calculate how much each should get or each should give to one another. App should be scalable that number of friends can change

For the above problem I have written the below code.  I need help to know whether I have written quality code utilising an optimal OOP design.

public class SpendDetect
{

    Map<String, PayDetails> outputMap = new HashMap<String, PayDetails>();

    public void getPayDetails(String payer, int amount, List<String> beneficiary) {

        List<String> consolidatedBenificiary = beneficiary;
        int dividableCount = consolidatedBenificiary.size();
        int amountToBePaid = 0;

        /**
         * Check if the payer is also a beneficiary
         */

        boolean IfPayerIsBenificiary = checkIfPayerIsBenificiary(payer,
                beneficiary);

        /**
         * If the payer is beneficiary remove the payer from the list of
         * beneficiaries
         */

        if (IfPayerIsBenificiary) {

            consolidatedBenificiary.remove(payer);
        }

        /**
         * Calculate the amount to be payed back by the benificiary
         */

        amountToBePaid = amount / dividableCount;

        /**
         * List the details to be paid by the beneficiary to the payer
         */
        for (String benificiaryIndividual : beneficiary) {
            System.out.println(benificiaryIndividual + " should be paying "
                    + amountToBePaid + " to " + payer);
        }
    }

    /**
     * Method to check if the payer is a benificiary
     *
     * @param payer
     * @param beneficiary
     * @return
     */
    public boolean checkIfPayerIsBenificiary(String payer,
            List<String> beneficiary) {
        boolean IfPayerIsBenificiary = false;

        if (beneficiary.contains(payer)) {
            return true;
        }

        return IfPayerIsBenificiary;

    }

    /**
     * Set whether the amount is payable
     *
     * @param isPayable
     * @param amount
     * @param payDetails
     * @return
     */

    public PayDetails setPayableOrToBePayed(boolean isPayable, int amount,
            PayDetails payDetails) {
        if (isPayable) {
            payDetails.Payable = payDetails.Payable + amount;
        } else {
            payDetails.toBePayed = payDetails.toBePayed + amount;
        }

        return payDetails;
    }

    public static void main(String[] args) {
        SpendDetect spd = new SpendDetect();
        List<String> benificiaryList = new ArrayList<String>();
        benificiaryList.add("A");
        benificiaryList.add("B");
        benificiaryList.add("C");
        benificiaryList.add("D");

        spd.getPayDetails("A", 100, benificiaryList);
        benificiaryList.clear();

        benificiaryList.add("B");
        benificiaryList.add("C");
        spd.getPayDetails("D", 500, benificiaryList);
        benificiaryList.clear();

        benificiaryList.add("A");
        benificiaryList.add("B");
        benificiaryList.add("C");
        spd.getPayDetails("B", 300, benificiaryList);

    }
}


texts:
Is there a better way to rewrite this part in python. It doesnot have to be shorter as long as its much better. thanks in advance

count = 1
while count < 10:
    _, pho = webcam.read()
    gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    images = face_cascade.detectMultiScale(gr, 1.3, 4)
    for (x,y,w,h) in faces:
            cv2.rectangle(pho,(x,y),(x+w,y+h),(0,255,0),2)
            fa = gray[y:y + h, x:x + w]
            e_size = cv2.resize(fa, (100, 100))
            cv2.imwrite('%s/%s.JPEG' % (folder,count), e_size)
    count += 1
    cv2.imshow('OpenCV', pho)
    key = cv2.waitKey(20)


texts:
As it is going to be used as part of some automation and not just at the command line I was wondering if it could be improved at all.

Improve would mean any of:

handle sad cases better
handle error better
report errors better
better able to work on multiple linux OS including OSX

Improve would NOT mean:

shorter code
short variable names
Linux shell version specific tricks or shortcuts
allowing for rvm not being present (checked elsewhere)

function make_sure_rvm_rubies_installed() {

rvm list > $TMP/local_ruby_versions.txt
local_ruby_versions=(1.8.7 1.9.3)

for version in "${local_ruby_versions[@]}"
do
  cat $TMP/local_ruby_versions.txt | grep -q $version
  version_search_result=$?
  if [ $version_search_result = 0 ]
  then
    echo "Required RVM Ruby version $version confirmed as present on this machine"
  else
    echo "*** EXITING SMOKE TEST *** - not all required ruby versions are present in RVM"
    echo "Please install RVM ruby version: $version and then re-run this program"
    exit
  fi
done
if [ $? = 0 ]
  then echo "All required Ruby Versions confirmed as present locally"
fi
}

make_sure_rvm_rubies_installed


texts: Constructing queries with SQLAlchemy based on search parameters

texts:
I have an app where the user can search for items in my database by entering a set of information, then the server receives it and for each option it queries the database, and stores the result in a list. I have around 10 different options and each option have from two to three possible values, so it's taking around 200 lines alone.

I use SQLAlchemy to handle the database from my Python backend. The way this works is that all options are sent as a dict via HTTP to the server, on the backend I use around a dozen of conditional statement to run the right query for each option.

I will only show how it works for 3 options, because all of them share almost the same logic:

if "type" in query and query["type"] is not None:
    if query["type"] == "blog":
        s = table.select(table.c.wordpress >= "2" )
        temp_list = self.run(s)
        full_list.append(temp_list)
    if query["type"] == "ecommerce":
        s = table.select(and_(table.c.ecommerce >= "3", table.c.ssl == "true"))
        temp_list = self.run(s)
        full_list.append(temp_list)
    if query["type"] == "other":
        s = table.select().all()
        temp_list = self.run(s)
        full_list.append(temp_list)
if "storage" in query and query["storage"] is not None:
    if query["storage"] == "10":
        s = table.select(or_(table.c.storage >= "10",table.c.storage == "0") )
        temp_list = self.run(s)
        full_list.append(temp_list)
    if query["storage"] == "100":
        s = table.select(or_(table.c.storage >= "100", table.c.storage == "0"))
        temp_list = self.run(s)
        full_list.append(temp_list)
    if query["storage"] == "0":
        s = table.select(table.c.storage == "0")
        temp_list = self.run(s)
        full_list.append(temp_list)
if "bandwidth" in query and query["bandwidth"] is not None:
    if query["bandwidth"] == "10":
        s = table.select(or_(table.c.bandwidth >= "10",table.c.bandwidth == "0") )
        temp_list = self.run(s)
        full_list.append(temp_list)
    if query["bandwidth"] == "100":
        s = table.select(or_(table.c.bandwidth >= "100", table.c.bandwidth == "0"))
        temp_list = self.run(s)
        full_list.append(temp_list)
    if query["bandwidth"] == "0":
        s = table.select(table.c.bandwidth == "0")
        temp_list = self.run(s)
        full_list.append(temp_list)

Type, storage and bandwidth are options, for example type has 3 possible values: blog, ecommerce or other, and for each possible value I'm running an SQL statement to get the DB results that meet that query. run is a function that executes the SQL query(s) and returns a list of rows.

This is working very well and very fast (MY databases don't have more than 50 rows). However, there are multiple option with multiple values, and I'm using an if statement for each option and each value, making this part of the app around 200 lines of code. I would like to find a shorter way to achieve this.

Notes:

Users can only select one value for each option
I can't use the AND and OR operators in one query, because there are values that need a whole logic. For example, the value "0" on storage means unlimited so it would be actually bigger than 100 and 10 so I can't use just one SQL query for that logic.


texts: Go Web API for Sending Emails via Contact Form

texts:
I've been playing around with Go and finally found a use case for a little web service I could build.
It takes JSON data via an HTTP POST request and sends me an email via Mailgun's API (it's used for a contact form on my website).
I'm new to Go and would love some feedback on what I could do better, anything I missed and where I could do better following the "Go way" of doing things. :)
main.go
package main

import (
    "fmt"
    "log"
    "net/http"
    "os"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

var mailgunDomain string = os.Getenv("MAILGUN_DOMAIN")
var mailgunAPIKey string = os.Getenv("MAILGUN_API_KEY")
var allowedOrigin string = os.Getenv("ALLOWED_ORIGIN")
var port string = os.Getenv("PORT")

func main() {
    if port == "" {
        panic("Missing environment variable PORT")
    }
    if mailgunDomain == "" {
        panic("Missing environment variable MAILGUN_DOMAIN")
    }
    if mailgunAPIKey == "" {
        panic("Missing environment variable MAILGUN_API_KEY")
    }
    if allowedOrigin == "" {
        panic("Missing environment variable ALLOWED_ORIGIN")
    }

    r := mux.NewRouter()

    r.Use(handlers.CORS(
        handlers.AllowedHeaders([]string{"Content-Type"}),
        handlers.AllowedOrigins([]string{allowedOrigin}),
    ))

    r.HandleFunc("/", homeHandler).Methods("GET")
    r.HandleFunc("/contact", HandleContact(mailgunDomain, mailgunAPIKey)).Methods("POST", "OPTIONS")

    log.Fatal(http.ListenAndServe(":"+port, r))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    fmt.Fprintln(w, "API for maxschmitt.me")
}

contact.go
package main

import (
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "os"
    "time"

    "github.com/mailgun/mailgun-go/v4"
)

var mailgunSender string = "email@sender.com"
var mailgunReceiver string = "email@receiver.com"

// HandleContact sends emails to me via the contact form
func HandleContact(mailgunDomain string, mailgunAPIKey string) http.HandlerFunc {
    type body struct {
        Name    string `json:"name"`
        Email   string `json:"email"`
        Message string `json:"message"`
    }

    mg := mailgun.NewMailgun(mailgunDomain, mailgunAPIKey)
    mg.SetAPIBase(mailgun.APIBaseEU)

    return func(w http.ResponseWriter, r *http.Request) {
        var b body

        err := json.NewDecoder(r.Body).Decode(&b)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }

        message := "From: " + b.Name + "<" + b.Email + ">\n\n"
        message += b.Message

        fmt.Fprintln(os.Stdout, "## New message!")
        fmt.Fprintln(os.Stdout, message+"\n")

        mgMsg := mg.NewMessage(mailgunSender, "New contact form submission", message, mailgunReceiver)
        mgMsg.SetReplyTo(b.Email)

        // Create a 10s timeout for sending the message
        ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
        defer cancel()

        resp, id, err := mg.Send(ctx, mgMsg)
        if err != nil {
            fmt.Println("Error sending contact form submission:")
            fmt.Println(err)
            http.Error(w, "Something went wrong", http.StatusInternalServerError)
            return
        }

        fmt.Fprintln(os.Stdout, "Mailgun response:", resp)
        fmt.Fprintln(os.Stdout, "Mailgun ID:", id)

        json.NewEncoder(w).Encode(b)
    }
}

I appreciate any feedback! Thanks!


texts: Force Stop by Error in httpClient.execute(httpPost);

texts:
It work's at Smartphone(Android 2.3.3) but Tablet(Android 4.0) => Force Close!!

 public String getXmlFromUrl(String url) {
        String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost); // HERE FORCE CLOSE, why???
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

Any suggestion with example?


texts:
I am playing with learning PowerShell classes, and I have a validation situation that kind of lends itself to Enums, as shown in the first example.
With Enum

Enum pxPathType {
  FileSystem_Folder = 0
  FileSystem_File   = 1
  Registry_Key      = 2
  Registry_Property = 3
}

class PxConstant {
    # Static Properties
    static [string] $RegExPathWithWildcard = '\\\*\.\*$|\\\*|\\.\.\*$|\*\.(\?[a-zA-Z0-9\?]{2}|[a-zA-Z0-9\?]\?[a-zA-Z0-9\?]|[a-zA-Z0-9\?]{2}\?)$|\\[^\\]*\.(\?[a-zA-Z0-9\?]{2}|[a-zA-Z0-9\?]\?[a-zA-Z0-9\?]|[a-zA-Z0-9\?]{2}\?)$|\\[^\\]*\.\*$'
}

class PxPath {
    # Properties
    [string]$Type = $null

    # Constructors
    PxPath ([string]$path) {
        $this.Type = [PxPath]::PathType($path)
    }
    PxPath ([string]$path, [string]$pathType) {
        #$pathTypeEnum = try {
        $this.Type = try {
            [pxPathType] $pathType
        } catch {
            Throw "Not a valid path type: $pathType"
        }
    }

    static [String] PathType ([String]$path) {
        [string]$pathType = $null
        if ($path -match [PxConstant]::RegExPathWithWildcard) {
            $pathWithoutWildcard = $path -replace [regex]::escape($matches[0]), ''
            Write-Host $pathWithoutWildcard
        }
        return $pathType
    }
}

$pathType = 'FileSystem_Folders'
$path = try {
    [PxPath]::New("C:\", $pathType)
} catch {
    Write-Host "$($_.Exception.Message)"
}
$path = try {
    [PxPath]::New("\\Server\Folder\*")
} catch {
    Write-Host "$($_.Exception.Message)"
}

The issue I have is that the Enum is only EVER used in the PxPath class, and I feel like that means I should have the Enum in the class, so it's self contained. However, PS5 doesn't allow an Enum in a class. The workaround I have come up with is to instead use an array as a hidden Property of the class instead, as in this second example.

With Array in Class

class PxConstant {
    # Static Properties
    static [string] $RegExPathWithWildcard = '\\\*\.\*$|\\\*|\\.\.\*$|\*\.(\?[a-zA-Z0-9\?]{2}|[a-zA-Z0-9\?]\?[a-zA-Z0-9\?]|[a-zA-Z0-9\?]{2}\?)$|\\[^\\]*\.(\?[a-zA-Z0-9\?]{2}|[a-zA-Z0-9\?]\?[a-zA-Z0-9\?]|[a-zA-Z0-9\?]{2}\?)$|\\[^\\]*\.\*$'
}

class PxPath {
    # Properties
    hidden [string[]]$validPathTypes = @('FileSystem_Folder', 'FileSystem_File', 'Registry_Key', 'Registry_Property')
    [string]$Type = $null

    # Constructors
    PxPath ([string]$path) {
        $this.Type = [PxPath]::PathType($path)
    }
    PxPath ([string]$path, [string]$pathType) {
        if ($this.validPathTypes -contains $pathType) {
            $this.Type = $pathType
        } else {
            Throw "Not a valid path type: $pathType"
        }
    }

    static [String] PathType ([String]$path) {
        [string]$pathType = $null
        if ($path -match [PxConstant]::RegExPathWithWildcard) {
            $pathWithoutWildcard = $path -replace [regex]::escape($matches[0]), ''
            Write-Host $pathWithoutWildcard
        }
        return $pathType
    }
}

$pathType = 'FileSystem_Folders'
$path = try {
    [PxPath]::New("C:\", $pathType)
} catch {
    Write-Host "$($_.Exception.Message)"
}
$path = try {
    [PxPath]::New("\\Server\Folder\*")
} catch {
    Write-Host "$($_.Exception.Message)"
}

I'm wondering if there is a performance or functional argument for one over the other? Or perhaps a strong Best Practice argument in favor? Or is this coders choice really?


texts: I could use a review of my sudoku validation

texts:
I'm looking for alternative ways to do it and in general parts that don't look write on this code.

using System.Collections.Generic;

namespace Algorithms
{
    public class SudokuPuzzleValidator
    {
        readonly int[,] _board;

        public SudokuPuzzleValidator()
        {
            _board = new int[9,9];
        }

        public SudokuPuzzleValidator(int[,] board)
        {
            _board = board;
        }

        public bool Validate()
        {
            const int integersInGame = 9;
            var rowSet = new HashSet<int>[integersInGame];
            InitializeSet(integersInGame, rowSet);
            var columnSet = new HashSet<int>[integersInGame];
            InitializeSet(integersInGame, columnSet);
            var subGridSet = new HashSet<int>[integersInGame];
            InitializeSet(integersInGame, subGridSet);

            for (var row = 0; row < integersInGame; row++)
            {
                for (var column = 0; column < integersInGame; column++)
                {
                    var cval = _board[row, column];
                    if (rowSet[row].Contains(cval))
                    {
                        return false;
                    }
                    rowSet[row].Add(cval);
                    if (columnSet[column].Contains(cval))
                    {
                        return false;
                    }
                    columnSet[column].Add(cval);
                    var subGridNumber = FigureOutSubGrid(row, column);
                    if (subGridSet[subGridNumber].Contains(cval))
                    {
                        return false;
                    }
                    subGridSet[subGridNumber].Add(cval);
                }
            }
            return true;
        }

        private static void InitializeSet(int integersInGame, HashSet<int>[] rowSet)
        {
            for (var i = 0; i < integersInGame; i++)
            {
                rowSet[i] = new HashSet<int>();
            }
        }

        private static int FigureOutSubGrid(int row, int column)
        {
            return column/3 + row/3*3;
        }
    }
}

Link to my post:
http://alfredoalvarez.com/blog/?p=372


texts: How easy is it to crack this encryption algorithm?

texts:
When I was about 13 or 14 years old, I was a little interested in cryptography (which is, after all, an interesting field). I learnt quite a lot since that time (it has been about 8 years since then), but I'm still very far away from considering myself an expert in cryptography.

Whatever, when I was at that age, I wrote this little Perl script which I just found on an old HD. (Saved as MyEncrypt.pm)

package MyEncrypt;

use strict;
use warnings;

my @_ALPHABET = ('a' .. 'z', 'A' .. 'Z', 0 .. 10, ' ');
my $_i = 0;
my %_ALPHABET = map { $_i++; $_ => $_i } @_ALPHABET;
$_i = 0;
my %_ALPHABET_REVERSE = map { $_i++; $_i => $_ } @_ALPHABET;

sub new {
    bless +{}, shift
}

sub set_password {
    my $self = shift;
    my $password = shift;
    $self->{hashed_password} = _hash_password($password);
    return $self;
}

sub encrypt {
    my $self = shift;
    my $input = shift;

    my $hashed_password = $self->{hashed_password};
    die "No password set.\n" unless $hashed_password;

    my @split = split(//, $input);

    my $output = shift;
    for (0 .. $#split) {
        my $new_number .= ($_ALPHABET{$split[$_]} + ($hashed_password ** ($_ + 1))) % $#_ALPHABET;
        $output .= $_ALPHABET_REVERSE{$new_number};
    }
    return $output;
}

sub _hash_password {
    my $password = shift;
    my $hash = 1;
    my $i = 1;
    for (split(//, $password)) {
        my $power = length($password) / (2 ** $i);
        $power = 1 if $power < 1;
        $hash *= int($_ALPHABET{$_} ** $power);
        $i++;
    }

    if(is_multiple_of_two($hash)) {
        $hash += 1;
    }

    while (length($hash) != 10) {
        no warnings;
        $hash *= $hash | join('', map { $_ALPHABET{$_} } split(//, $password));
        $hash =~ s/\.//g;
        $hash = substr($hash, 0, 10);
    }
    return $hash;
}

sub is_multiple_of_two {
    my $n = shift;
    my $log = log($n) / log(2);
    if($log == int($log)) {
        return 1;
    } else {
        return 0;
    }
}

1;

(It probably has the worst hashing-algorithm ever. I know).

This is my "test-program" for it:

use strict;
use warnings;
use MyEncrypt;

my $enc = MyEncrypt->new();
$enc->set_password('abc');
die $enc->encrypt("hello world");

My idea was this:
We give it a password and it somehow generates a "hash" of it (here in a way that, I admit, I don't quite understand anymore. For some reason, it should be 10 digits long and these are generated by, until the password is 10 digits long, multiplying the password with the OR'd characters of the alphabet (where a = 1, ... A = 27, ...) and then cutting it to 10 characters or less, until this leads to a "hash"), which is then later used for this letter-by-letter-substitution:

x = (number of the actual letter + password_hash to the power of (position of this character + 1)) modulo the size of the alphabet

and then x is used to look for the letter numbered x, which will be added to the output-string. When gone through all the text, the output will have a completely different form of what it had as input. And when one letter changes in the password, the whole string is different.

E.g.:

string: "hello world", pass: "abc" => 9bkpXY1H0oR
string: "hello world", pass: "abcd" => HS4gVkuWX4U
string: "hello world", pass: "abcda" => DhAqIeHn9cr

and so on.

Of course, the code is terrible, the hashing-algorithm is probably the worst one ever and the idea is not really new, but I came up with it myself and at that time I was quite proud of myself for this. But how secure would this have been? How much time would one need to decrypt this and how would this be done? As I've said, I developed in many fields, but for some reason after that script I did not care so much about cryptography anymore and my knowledge there is quite limited.


texts:
Continuing with my series of cipher programs, I hastily wrote a null cipher program, and I was wondering how it could be improved:

#include <iostream>
#include <vector>
#include <sstream>
#include <iterator>
#include <algorithm>

std::string getString();
std::vector<std::string> tokenize(const std::string & str);
std::vector<int> getPattern();

int main(){
    std::string input;
    std::vector<std::string> words;
    std::vector<int> pattern;
    do{
        if(words.size() != pattern.size()){
            std::cout << "\nError: Number of words must be equal to number of integers in pattern.";
        }
        input = getString();
        words = tokenize(input);
        pattern = getPattern();
    } while(words.size() != pattern.size());

    for(int i = 0; i < words.size(); ++i){
        if(words[i].length() > pattern[i]){
            std::string str = words[i];
            std::cout << str[pattern[i]];
        }
    }

    std::cout << '\n';
    return 0;
}

std::string getString(){
    std::cout << "Seperate words with spaces.\nInput string: ";
    std::string input;
    std::getline(std::cin, input);
    return input;
}

std::vector<std::string> tokenize(const std::string & str){
    std::stringstream ss(str);
    std::istream_iterator<std::string> begin(ss);
    std::istream_iterator<std::string> end;
    std::vector<std::string> words(begin, end);
    return words;
}

std::vector<int> getPattern(){
    std::string pattern;
    std::vector<int> intTokenizedPattern;
    bool validPattern;
    do{
        std::cout << "Seperate positive integers with spaces: ";
        std::getline(std::cin, pattern);
        std::vector<std::string> tokenizedPattern = tokenize(pattern);
        try{
            std::transform(tokenizedPattern.begin(), tokenizedPattern.end(),
                std::back_inserter(intTokenizedPattern),
                [](const std::string & str){ return (std::stoi(str) > 0 ? std::stoi(str) - 1 : throw "Input less than one");});
            validPattern = true;
        } catch(...){
            tokenizedPattern.clear();
            intTokenizedPattern.clear();
            validPattern = false;
        }
    } while(!validPattern);

    return intTokenizedPattern;
}

Here is an example input/output:

Seperate words with spaces.
Input string: Susan says Gail lies. Matt lets Susan feel jovial. Elated angry?
Seperate positive integers with spaces: 1 2 3 1 2 3 1 2 3 1 2
SailatSevEn

In the output above, it is deciphered to say "sail at seven" (null ciphers are not used in the modern age of cryptography).

In my program, I verify that the number of elements in the words and pattern vectors is equal. I also verify that the elements in the pattern vector are all actual integers (which is done in the try-catch loop).

I found it interesting that at this time this is the only null cipher program on Code Review, so it could also prove helpful to future viewers.

How can this code be improved?


texts: Given sum and product, find the two variables

texts:
Basically, find x and y given the product = xy and sum = x + y. I would like review on optimization, clean code, and complexity.  It looks like O(1), but the while loop makes me wonder if it's something different.

/**
 *  x will always be less than or equal to y.
 */
final class Variables {
    private final int x;
    private final int y;

    Variables(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override public String toString()  {
        return " x = " + x + " y = " + y;
    }
}

/**
 * @author SERVICE-NOW\ameya.patil
 */
public final class SimultaneousEquations {

    private SimultaneousEquations () {}

    /**
     * Provided we dont have positive product and -ve sum,
     * return value would be the smallest posive integer of the variable.
     *
     * @param product : product of x and y
     * @param sum     : sum of x and y
     * @return        : smallest positive integer of x and y.
     */
    private static int getX(int product, int sum) {
        assert product != 0;
        assert product < 0 || (product > 0 && sum > 0);

        int x = 1;
        while (x*x != (sum * x  - product)) {
            x++;
        }
        return x;
    }

    /**
     * Given a product and a sum, return two variables.
     *
     * @param sum       : sum of two variables
     * @param product   : product of two variables
     */
    public static Variables getVariables(int product, int sum) {
        if (product == 0) {
            if (sum < 0) {
                return new Variables(sum, 0);
            } else {
                return new Variables(0, sum);
            }
        }

        if (product < 0) {
            int x = getX(product, sum);
            return new Variables(product/x, x);
        }

        if (sum < 0) {
            int x = -getX(product, -sum);
            return new Variables(product/x, x);
        }

        int x = getX(product, sum);
        return new Variables(x, product/x);
    }

    public static void main(String[] args) {
        // 0 10
        Variables v1 = SimultaneousEquations.getVariables(0, 10);
        boolean result1 = v1.getX() == 0 && v1.getY() == 10;
        System.out.println(result1);

        // 2 5
        Variables v2 = SimultaneousEquations.getVariables(10, 7);
        boolean result2 = v2.getX() == 2 && v2.getY() == 5;
        System.out.println(result2);

        // -2 5
        Variables v3 = SimultaneousEquations.getVariables(-10, 3);
        boolean result3 = v3.getX() == -2 && v3.getY() == 5;
        System.out.println(result3);

        // 2 -5
        Variables v4 = SimultaneousEquations.getVariables(-10, -3);
        boolean result4 = v4.getX() == -5 && v4.getY() == 2;
        System.out.println(result4);

        // -2 -5
        Variables v5 = SimultaneousEquations.getVariables(10, -7);
        boolean result5 = v5.getX() == -5 && v5.getY() == -2;
        System.out.println(result5);
    }
}


texts:
I have the follow code to change between different CSS theme files, I would like some reviews on it because I am sure it can be improved to be safer.

 <head>
    <?php
    $theme = $_GET['theme'];
    $choice = preg_replace('/[^A-Za-z0-9\-]/', '', $theme);
    if (empty($choice)){
echo '<link rel"stylesheet" type="text/css" href="css/default.css" />';}
    elseif (file_exists("./css/" . $choice . ".css"))
{echo '<link rel"stylesheet" type="text/css" href="css/'.$theme.'.css" />';}
    else {echo '<link rel"stylesheet" type="text/css" href="css/default.css" />';}
    exit();
    ?>
    <!-- other elements in head -->
    </head>

The functions are:

If GET string empty set CSS default file
If GET non existing CSS file set CSS default file
If GET existing CSS file them we use the echo GET.css file


texts:
I've written an implementation of the back-propagation algorithm in Clojure (here). This is my first attempt at Clojure where the code totals more than ten lines and so it is not very idiomatic; specifically in one of my functions I have this:

; example neural-network: {:inputs [{:weights [1] :delta -0.2 :activation 1}] :outputs [{:activation 0.645}]}
(defn train-layer
  [neural-network layer-index next-layer-index rate]
  (let [layer (get neural-network layer-index)
        next-layer (get neural-network next-layer-index)]
    (loop [neuron 0
           net neural-network]
      (if (< neuron (count layer))
        (recur (inc neuron) (loop [next-neuron 0
                                   net-1 net]
           (if (< next-neuron (count next-layer))
             (let [change (* (get-in next-layer [next-neuron :delta]) (get-in layer [neuron :activation]))
                   weight (+ (get-in layer [neuron :weights next-neuron]) (* rate change))]
               (recur (inc next-neuron) (assoc-in net-1 [layer-index neuron :weights next-neuron] weight)))
             net-1)))
        net))))

Where I need to change a neural network inside a nested for loop; making it an argument to each loop seems like a bad idea. It is also really rather dense (and therefore probably quite difficult to understand, so apologies). How should this be implemented to make it easier to read and more idiomatic?


texts: Fail-safe remote API operations for managing customers and billing

texts:
I'm working with two remote APIs: one which manages customers and the other (a Paypal API interface) which manages billing. To delete an account, I must delete the records from both.

function deleteAccount($account_id) {
    try {
        $api1->deleteAccount( $account_id );
    } catch (Exception $e) {
        Logger::log(...);
        return false;
    }

    try {
        $api2->cancelBilling( $account_id );
    } catch (Exception $e) {
        Logger::log(...);
        return false;
    }
}

Suppose that the first operation (with api1) succeeds but the second operation (with api2) fails. This could happen, for example, if the api2 server was down - a factor which is out of my control.

I would then have deleted the account in api1, but would still be billing the user, which would lead to a corruption in my data (and some unhappy users!).

I have one idea on how to maximise the possibility of success, by doing various checks for errors:

function deleteAccount($account_id) {
    //Check that servers are up
    if(!$api1->canConnectToServer() || !$api2->canConnectToServer()) {
        return false;
    }
    if (!$api1->isAccountIDValid($account_id ) || !$api2->isAccountIDValid($account_id ) ) {
        return false;
    }

    try {
        $api1->deleteAccount( $account_id );
    } catch (Exception $e) {
        Logger::log(...);
        return false;
    }

    try {
        $api2->cancelBilling( $account_id );
    } catch (Exception $e) {
        Logger::log(...);
        return false;
    }
}

However, this seems a little flimsy and doesn't guarantee data integrity. Is there a better way to handle this? I'm also not sure whether I should return false or throw an exception.