texts:
I have to create some APIs for a online game and I decided to learn to use namespaces correctly.

I used the factory pattern, then the loadModule method checks if in the Modules folder there is a class named $module and then it return the object.
The folders are synchronized with the namespaces.

The main class Metin2.class.php:

<?php

namespace Metin2;
use mysqli;
use \Metin2\Utilities as Utilities;
require_once("config.php");
require_once(UTILITIES_PATH . "Autoloader.class.php");

class Metin2
{
    public $db;

    public function __construct(mysqli $database)
    {
        spl_autoload_register("Metin2\\Utilities\\Autoloader::loadModel");
        try {
            if(!$database) throw new Exceptions\Metin2Exception("The database instance     is not a valid instance");
            $this->db = new Utilities\Database($database);

        } catch (Exceptions\Metin2Exception $e) {
            echo $e->errorMessage();
        }

    }

    public function loadModule($module)
    {
        $m = "\\Metin2\\Modules\\" . $module;
        return new $m;
    }
}

Autoloader class:

<?php
namespace Metin2\Utilities;

class Autoloader {
    public static function loadModel($class){
        $class = str_replace("\\","/",$class);
        $class = explode("/",$class);
        if($class[0] == "Metin2")unset($class[0]);
        $class = implode("/",$class);
        $path = ROOT_PATH.$class.".class.php";
        if(file_exists($path)){
            require_once($path);
        }
    }
}

An example of a module:

<?php
namespace Metin2\Modules;

class Testdb {

    public $db;
    public function __construct(){
        $this->db = \Metin2\Utilities\Database::getInstance();
        print_r($this->db->getOne("account"));
    }
}

Everything works well, but I want to know if there are any things I did wrong or if there are things I can do better.


texts: Grab data from one sheet and insert/format it into another sheet

texts:
I have code that runs and does what I want it to do with the click of the command button, however when executing, it runs very slow.

The code grabs data from one sheet and inserts/formats it into another sheet in two separate tables that have been converted into range. I did this because I need to automatically update two different graphs with certain data.

I'm still new with VBA coding and any kind of direction or help to make the code run faster is appreciated or ways to remove unnecessary code since it is probably longer than it needs to be.

Public Sub Button1_Click() ' Update Button

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Dim lastRowPart As Long
Dim lastRowCW As Long
Dim lastRowQty As Long
Dim lastRowQtyLeft As Long
Dim lastRowDescrip As Long
Dim i, j, k As Integer
Dim IO As Worksheet: Set IO = Sheets("Inventory Overview")
Dim TD As Worksheet: Set TD = Sheets("Trend Data")

'1. Copies and formats data

lastRowPart = IO.Cells(Rows.count, "F").End(xlUp).Row
lastRowDescrip = IO.Cells(Rows.count, "G").End(xlUp).Row
lastRowQtyLeft = IO.Cells(Rows.count, "O").End(xlUp).Row
lastRowQty = IO.Cells(Rows.count, "I").End(xlUp).Row
lastRowCW = IO.Cells(Rows.count, "L").End(xlUp).Row

TD.Cells.UnMerge ' reset***

j = 2
k = 2
For i = 2 To lastRowCW
If IO.Cells(i, "L").Value = "Unknown" Then
    TD.Cells(j, "G").Value = IO.Cells(i, "L").Value
    TD.Cells(j, "H").Value = IO.Cells(i, "F").Value
    TD.Cells(j, "I").Value = IO.Cells(i, "I").Value
    TD.Cells(j, "J").Value = IO.Cells(i, "O").Value
    TD.Cells(j, "K").Value = IO.Cells(i, "G").Value
    j = j + 1
Else
    TD.Cells(k, "A").Value = IO.Cells(i, "L").Value
    TD.Cells(k, "B").Value = IO.Cells(i, "F").Value
    TD.Cells(k, "C").Value = IO.Cells(i, "I").Value
    TD.Cells(k, "D").Value = IO.Cells(i, "O").Value
    TD.Cells(k, "E").Value = IO.Cells(i, "G").Value
    k = k + 1
End If
Next

' Autofit
TD.range("B1:B" & lastRowPart).Columns.AutoFit
TD.range("E1:E" & lastRowDescrip).Columns.AutoFit
TD.range("H1:H" & lastRowPart).Columns.AutoFit
TD.range("K1:K" & lastRowDescrip).Columns.AutoFit

'2. Sort Cells
Dim LastRow As Long
LastRow = TD.Cells(Rows.count, 5).End(xlUp).Row

With TD.Sort  ' sorts data from A to Z
 .SetRange TD.range("A2:E" & LastRow)
 .Header = xlGuess
 .MatchCase = False
 .Orientation = xlTopToBottom
 .SortMethod = xlPinYin
 .Apply
End With

'3. Merge CW Cells
' rngMerge = range for parts reworked/left with known CW
' URngMerge = range for parts reported with unknown CW

Dim rngMerge As range, URngMerge As range, cell As range, lastRowMerge As   Long, ULastRowMerge As Long
lastRowMerge = TD.Cells(Rows.count, 1).End(xlUp).Row
ULastRowMerge = TD.Cells(Rows.count, 7).End(xlUp).Row
Set rngMerge = TD.range("A1:A" & lastRowMerge)
Set URngMerge = TD.range("G1:G" & ULastRowMerge)

MergeAgain:
For Each cell In rngMerge
    If cell.Value = cell.Offset(1, 0).Value And IsEmpty(cell) = False Then
        range(cell, cell.Offset(1, 0)).Merge
        GoTo MergeAgain
End If
Next

MergeAgain2:
For Each cell In URngMerge
If cell.Value = cell.Offset(1, 0).Value And IsEmpty(cell) = False Then
    range(cell, cell.Offset(1, 0)).Merge
    GoTo MergeAgain2
End If
Next

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub


texts: Integer Log2 implemented using binary search

texts:
I saw a simple method to calculate Log2(N), where N is the power of 2:

unsigned int Log2(unsigned int N)
{
    unsigned int n = 0;
    while (N >>= 1)
    {
        ++n;
    }
    return n;
}

It would be not likely very necessary, but I try to improve it in a simple way, the idea comes from binary search.

unsigned int Log2New(unsigned int N)
{
    unsigned int bits = sizeof(N) * 4;
    unsigned int n = 0;
    while (N > 1)
    {
        if (N >> bits)
        {
            N >>= bits;
            n += bits;
        }
        bits >>= 1;
    }
    return n;
}

I run the test in Visual Studio 2013, 32 bits release build and fully optimized.  When I look into generated disassembly, both methods are inlined, and there are nothing special in both function.  There is only one shr command as expected in

if (N >> bits) { N >>= bits; ... }

I test both of the method by sending 1 << n, n from 0 to 31 to them, and repeat for 1000000 times, and count the time separately.

The new method is about 1.66 times faster than the old one,

Then I make a further change, expand the while loop in the new method.  (There was a word for this 'expand', but I don't remember it exactly 8-| )
To make it clear, I make a new define, and the method become:

#define CountShift(bits)  if ((N)>>(bits)) { (N)>>=(bits); (n) += (bits); }
unsigned int Log2NewExpand(unsigned int N)
{
    unsigned int n = 0;
    CountShift(16);
    CountShift(8);
    CountShift(4);
    CountShift(2);
    CountShift(1);

    return n;
}

Looking into the disassembly again, as expected, it's fully serialized, only 5 test, je shr and add commands.

Timing again, the expanded method is again about 1.66 times faster then the new one, and about 2.8 times faster than the original method.

I think there must be some more space for improvement.  Any suggestion are welcome.


texts: How do I reduce lines of code in this piece of code? A number of lines are being repeated in updateProfileFlags and fetchProfileObj

texts:
This method initiates a new connection with the thrift client and returns a profile object

 private TResume fetchProfileObj(int userId) {
    try{
        TTransport transport = new TSocket("172.XX.X.XXX”, 9311);
        transport.open();
        TProtocol protocol = new  TBinaryProtocol(transport);
        Map<String, String> ids = new HashMap<String, String>();
        ids.put("requestId", "settingsService");
        TResumeService.Client resumeServiceClient = new TResumeService.Client(protocol);
        TResume profileObj = resumeServiceClient.getFullActiveProfileFromUserId(ids, 105, userId, "resman5_1");
        transport.close();
        return profileObj;
    } catch(Exception e) {
        e.printStackTrace();
        return null;
    }
}

This method updates the profile object recieved from the fetchProfile method

private void updateProfileFlags(TResume profile,int recruiterJobAlert) {
    try{
        TTransport transport = new TSocket("172.XX.X.XXX", 9321);
        transport.open();
        TProtocol protocol = new  TBinaryProtocol(transport);
        Map<String, String> ids = new HashMap<String, String>();
        ids.put("requestId", "settingsService");
        TUpdateResume.Client updateResumeClient = new TUpdateResume.Client(protocol);
        profile.getUser().setResdexVisibility(recruiterJobAlert>0?"a":"c");
        updateResumeClient.saveProfile(ids, 105, profile.getProfile(), "now", "resman5_1", null);
        transport.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

Now calling the above methods

public void myTestMethod(){
updateProfileFlags(fetchProfileObj(userId),settings.getRecruiterJobAlert());
}


texts:
I have a set of functions in my program for conveniently generating random number in various distributions. I'm interested in the questions listed below, though other comments are also welcome.

Am I using C++'s random tools correctly and clearly?
From watching rand() Considered Harmful and reading this answer, I learned that RNG calls are not thread-safe. I changed my code just by adding the specifier thread_local to the generator and distribution variables. Is this all that's needed to make the functions thread-safe? These are called within std::async procedures in my project.
Does it matter whether one std::mt19937_64 generator is used for all the functions or if each function has its own copy?

In Random.h

#ifndef RANDOM_H
#define RANDOM_H

#include <random>
#include <algorithm>

namespace Random
{
    // Random number with normal distribution and mean of zero
    double random_normal(double standard_deviation);

    // Random number with inclusive range
    double random_real(double min, double max);
    int random_integer(int min, int max);

    // Return true with probability 50%
    bool coin_flip();

    // Return true with given probability
    bool success_probability(double probability);

    namespace
    {
        thread_local std::mt19937_64 generator(std::random_device{}());
    }

    // Shuffles the order of the list
    template<class List>
    void shuffle(List& list)
    {
        std::shuffle(list.begin(), list.end(), generator);
    }
}
#endif // RANDOM_H

In Random.cpp

#include "Random.h"

#include <random>

int Random::random_integer(int min, int max)
{
    using uid = std::uniform_int_distribution<int>;
    thread_local static auto dist = uid{};
    return dist(generator, uid::param_type{min, max});
}

double Random::random_normal(double standard_deviation)
{
    using nd = std::normal_distribution<double>;
    thread_local static auto dist = nd{};
    return dist(generator, nd::param_type{0.0, standard_deviation});
}

double Random::random_real(double min, double max)
{
    using urd = std::uniform_real_distribution<double>;
    thread_local static auto dist = urd{};
    return dist(generator, urd::param_type{min, max});
}

bool Random::coin_flip()
{
    return success_probability(0.5);
}

bool Random::success_probability(double probability)
{
    return random_real(0.0, 1.0) < probability;
}

An example usage:

#include <iostream>
#include <future>

#include "Random.h"

double random_walk(int number_of_steps, double step_size)
{
    double position = 0;
    for(int i = 0; i < number_of_steps; ++i)
    {
        position += Random::random_normal(step_size);
    }
    return position;
}

int main()
{
    // Simulate 1,000,000-step continuous random walks
    const int number_of_walks = 100; // adjust to suit your computer
    const int number_of_steps = 1000000;
    const double step_size = 1.0;
    std::vector<std::future<double>> results;
    for(int i = 0; i < number_of_walks; ++i)
    {
        results.emplace_back(std::async(random_walk, number_of_steps, step_size));
    }

    for(auto& result : results)
    {
        std::cout << result.get() << std::endl;;
    }

    return 0;
}


texts: Password-Lock a Single Page with PHP - How did I do?

texts:
I just wrote some PHP to let a client lock off a their one-page site from the public using a password. No users and no database. Just checking the password the user enters and testing it against the chosen phrase. This should be simple (right?) but I havn't built this sort of thing before. Let me know what you think, and whether it could be done better. Thanks!

includes/session.php

class Session {

private $logged_in;

function __construct() {
    session_start();
    $this->check_login();
}

// Return whether they are logged in.
public function is_logged_in() {
    return $this->logged_in;
}

// When initialized, check to see if the user is logged in.
private function check_login() {
    if (isset($_SESSION['logged_in'])) {
        // If logged in, take this action
        $this->logged_in = true;
    } else {
        // If not logged in, take this action
        $this->logged_in = false;
    }
}

// Set the session. User will remain logged in.
public function login() {
    $_SESSION['logged_in'] = 1;
    $this->logged_in = true;
}

// Log out. Unset session and destroy it.
public function logout() {
    unset($_SESSION['logged_in']);
    $this->logged_in = false;
    session_destroy();
}

public function check_pass($pass) {
    $pass = @strip_tags($pass);
    $pass = @stripslashes($pass);

    if ($pass !== 'TheChosenPassword') return false;

    return true;
}
}

login.php:

require_once('includes/session.php');

// If already logged in just send them to index.php
if ($session->is_logged_in()) {
    header('Location: index.php');
    exit;
}

// Create the var in the global scope.
$msg = 'This page is private.<br> Please enter the password.';

// If the form was submitted ...
if (isset($_POST['submit'])) {

    // Make sure they entered a pass
    if (!$_POST['pass']) {
        $msg = "Please enter a password.";
    } else {

        // If they entered a pass, grab it and trim it.
        $pass = trim($_POST['pass']);

        // Now check the pass
        if ($session->check_pass($pass)) {
            $session->login();
            header('Location: index.php');
            exit;
        } else {
            $msg = "Sorry, that password is incorrect.";
        } // Endif checkpass
    } // endif isset(pass)

} // Endif isset(post)

?> <!-- The form is bellow -->

index.php

require_once('includes/session.php');
if (!$session->is_logged_in()) {
    header('Location: login.php');
    exit;
}

You can probably guess from the code that the form just has an <input> with a name of 'pass' and a submit button with a name of 'submit'. Also a <small> tag in which i echo $msg. So, any thoughts on how this could be improved? Did I make any glaring mistakes? Thanks for the help!


texts: Mouseover effects for social network icons

texts:
Hey so I have written some code out in jQuery, but it seems to violate DRY. I'm not too familiar with JavaScript or jQuery, so I was just asking for some advice on how to optimize this code:

$("#twitter").rotate({
  bind:
  {
    mouseover : function() {
    $(this).rotate({animateTo:360});

    $("#twitter").fadeTo(function() {
        $(this).load(function() { $(this).fadeTo(); });
        $(this).attr("src", "images/logos/Twitter-Color.png");
    });
  },
  mouseout : function() {
    $(this).rotate({animateTo:0})
    $("#twitter").fadeTo(function() {
        $(this).load(function() { $(this).fadeTo(); });
        $(this).attr("src", "images/logos/Twitter-White.png");
    });
  }
  }
});

$("#linkedin").rotate({
  bind:
  {
    mouseover : function() {
    $(this).rotate({animateTo:360});

    $("#linkedin").fadeTo(function() {
        $(this).load(function() { $(this).fadeTo(); });
        $(this).attr("src", "images/logos/Linkedin-Color.png");
    });
  },
  mouseout : function() {
    $(this).rotate({animateTo:0})
    $("#linkedin").fadeTo(function() {
        $(this).load(function() { $(this).fadeTo(); });
        $(this).attr("src", "images/logos/Linkedin-White.png");
    });
  }
  }
});
$("#facebook").rotate({
  bind:
  {
    mouseover : function() {
    $(this).rotate({animateTo:360});

    $("#facebook").fadeTo(function() {
        $(this).load(function() { $(this).fadeTo(); });
        $(this).attr("src", "images/logos/Facebook-Color.png");
    });
  },
  mouseout : function() {
    $(this).rotate({animateTo:0})
    $("#facebook").fadeTo(function() {
        $(this).load(function() { $(this).fadeTo(); });
        $(this).attr("src", "images/logos/Facebook-White.png");
    });
  }
  }
});


texts:
This code seems surprisingly fast at checking if a number is prime.

def is_prime(number: int) -> bool:
    """Checks if a number is prime or not"""
    # number must be integer
    if type(number) != int:
        raise TypeError("Non-integers cannot be tested for primality.")
    # negatives aren't prime, 0 and 1 aren't prime either
    if number <= 1:
        return False
    # 2 and 3 are prime
    elif number <= 3:
        return True
    # multiples of 2 and 3 aren't prime
    elif number % 2 == 0 or number % 3 == 0:
        return False
    # only need to check if divisible by potential prime numbers
    # all prime numbers are of form 6k +/- 1
    # only need to check up to square root of number
    for i in range(5, int(number**0.5) + 1, 6):
        if number % i == 0 or number % (i + 2) == 0:
            return False

    return True

However, is there any way to speed this prime testing up?


texts: Sharing a database connection with multiple modules

texts:
I am building what essentially could be viewed as a glorified database wrapper as a Python package, where I'm having several classes and functions spread out into different modules. My current problem is how to share the database connections with the different modules.

An example class in user.py:

class User(object):
    def __init__(self, user_name, db_con):
        self.user_name = user_name
        self._db_con = db_con

Which results in my __init__.py looking like this:

from .user import User as _User

def _connect_dbs():
    econ = _mdb.connect(host='db.com',
                        user='user', passwd=pass,
                        db='db', charset='utf8')
    return econ

_db = _connect_dbs()

def User(user_name):
    return _User(user_name, _db)

Is this a good solution, or could I implement it in another manner? While this avoids global variables, it does result in some code I would rather not have to write for quite a few functions.


texts: Pseudo-random number generator port from C

texts:
C code:

uint32_t pcg32_random_r(pcg32_random_t* rng)
{
  uint64_t oldstate = rng->state;
  rng->state = oldstate * 6364136223846793005ULL + rng->inc;
  uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u;
  uint32_t rot = oldstate >> 59u;
  return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}

Attempted Java port (slightly fixed from GitHub):

public int nextInt() {
  long oldState = state;
  state = oldState * MULTIPLIER + inc;
  int xorShifted = (int) (((oldState >>> 18) ^ oldState) >>> 27);
  int rot = (int) (oldState >>> 59);
  return Integer.rotateRight(xorShifted, rot);
}

Are there differences in behavior? * and + should give the same bitwise results for signed arithmetic in Java and unsigned in C++, >>> in Java is the same as >> in C... But am I missing something?


texts: Validating a date with C# and ASP.NET Core 3.1

texts:
I have a simple class to ensure the date entered into a form is a valid date. Where can I improve it, have I missed anything?
public class ValidDate : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var dateToParse = value.ToString();
        var parsedDate = new DateTime();

        if (DateTime.TryParseExact(dateToParse, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture,
            System.Globalization.DateTimeStyles.None, out parsedDate))
            return ValidationResult.Success;

        return new ValidationResult("Invalid date, please try again with a valid date in the format of DD/MM/YYYY.");
    }
}

Thanks,


texts: T-SQL simplify repeated query unions for each day of the week

texts:
I've created the T-SQL code below to get the next nearest datetime value during the next 7 days.

The ScheduleDetail table schema is:

CREATE TABLE [dbo].[ScheduleDetail]
(
[uid] [int] IDENTITY(1,1) NOT NULL,
[scheduleRef] [int] NOT NULL,
[startTime] [datetime] NOT NULL,
[stopTime] [datetime] NOT NULL,
[validSunday] [bit] NOT NULL,
[validMonday] [bit] NOT NULL,
[validTuesday] [bit] NOT NULL,
[validWednesday] [bit] NOT NULL,
[validThursday] [bit] NOT NULL,
[validFriday] [bit] NOT NULL,
[validSaturday] [bit] NOT NULL,
[validHoliday] [bit] NOT NULL
)

The MIN(CAST(CAST(...) AS nextScheduleDateTime is to get the date from that day of the week (after today) and add it to the schedule's startTime (as the startTime and stopTime fields are actually TIME types stored as DATETIME's. Don't ask me why...)

The only difference between each is the value @Sunday, @Sunday + 1, etc. and the column names: validSunday, validMonday, etc.

DECLARE @waypointId INT = 100;
DECLARE @Sunday INT = 1;

SELECT MIN(nextScheduleDateTime)
FROM
    SELECT MIN(CAST(CAST(DATEADD(dd, (6 - DATEPART(dw, GETDATE()) + @Sunday) % 7 + 1, GETDATE()) AS DATE) AS DATETIME) + CAST(ScheduleDetail.startTime AS TIME)) AS nextScheduleDateTime
    FROM WaypointEventLog INNER JOIN
         Schedule ON Schedule.scheduleRef = WaypointEventLog.ScheduleID INNER JOIN
         ScheduleDetail ON Schedule.scheduleRef = ScheduleDetail.scheduleRef
    WHERE WaypointID = @waypointId
    AND Completed = 0
    AND Schedule.scheduleType = 6
    AND (validSunday = 1 AND DATEPART(dw, GETDATE()) <> @Sunday)

    UNION

    SELECT MIN(CAST(CAST(DATEADD(dd, (6 - DATEPART(dw, GETDATE()) + @Sunday + 1) % 7 + 1, GETDATE()) AS DATE) AS DATETIME) + CAST(ScheduleDetail.startTime AS TIME)) AS nextScheduleDateTime
    FROM WaypointEventLog INNER JOIN
         Schedule ON Schedule.scheduleRef = WaypointEventLog.ScheduleID INNER JOIN
         ScheduleDetail ON Schedule.scheduleRef = ScheduleDetail.scheduleRef
    WHERE WaypointID = @waypointId
    AND Completed = 0
    AND Schedule.scheduleType = 6
    AND (validMonday = 1 AND DATEPART(dw, GETDATE()) <> @Sunday + 1)

    UNION

etc for each day of the week.....

Is there any way to simplify this, maybe convert these to a UDF somehow? Or Similar.

I could probably do something with EXEC and LEFT() the column name but that feels wrong.


texts: Check if two lists are permutations of the one another ( Improvement)

texts:
Task: . Complete the following function that determines if two lists contain the same elements, but not necessarily in the same order. The function would return true if the first list contains 5, 1, 0, 2 and the
second list contains 0, 5, 2, 1. The function would return false if one list contains elements the other
does not or if the number of elements differ. This function could be used to determine if one list is a
permutation of another list. The function does not affect the contents of either list.

My code:

def permutation(a,b):
    if len(a) != len(b):
        return False
    n = len(a)
    count = 0
    for i in range(n):
        for j in range(n):
            if b[j] == a[i]:
                count += 1
    return count == n

def main():
    lst_1 = [1,2,3,4]
    lst_2 = [2,4,3,1]
    lst_3 = [2,4,4,5,4,5]
    lst_4 = [2,3,4,4,4,4]
    print(permutation(lst_1,lst_2))
    print(permutation(lst_2,lst_3))
    print(permutation(lst_3,lst_4))
main()


texts:
There is an object which has few properties. I wrote a function for test cases which check if the properties are satisfied or not. The function should throw an exception if the property is not satisfied.

But, I think there are better ways to write those test cases. A subset of the property of the object is as follows:

  x['polygon'] is a list of >= 3 integer (x,y) pairs representing the
  corners of the polygon in clockwise or anticlockwise order.

Current function is as follows:

def validate_object(x):
    """This function validates an object x that is supposed to represent an object
    inside an image, and throws an exception on failure.
    Specifically it is checking that:
      x['polygon'] is a list of >= 3 integer (x,y) pairs representing the corners
                    of the polygon in clockwise or anticlockwise order.
    """
    if type(x) != dict:
        raise ValueError('dict type input required.')

    if 'polygon' not in x:
        raise ValueError('polygon object required.')

    if not isinstance(x['polygon'], (list,)):
        raise ValueError('list type polygon object required.')

    points_list = x['polygon']
    if len(points_list) < 3:
        raise ValueError('More than two points required.')

    for x, y in points_list:
        if type(x) != int or type(y) != int:
            raise ValueError('integer (x,y) pairs required.')

    return

It would be really helpful if someone could please suggest better ways of writing those test cases.


texts: Keep reading user keyboard input if available, while echoing back the latest available

texts:
On StackOverflow I have asked a question a few minutes ago, but then by trying a bit more, I found the answer myself, and I'm posting the resulting working code here for review.
What the code does, is waiting for, and repeatedly prompting the user to enter a character; when the user enters one, the program echoes it back and goes back to the previous mode, waiting for further input. The program assumes an initial implicit input of 'A'.
{-# language LambdaCase #-}

import Control.Concurrent
import Data.Maybe
import System.IO

main :: IO ()
main = do
  hSetBuffering stdin NoBuffering
  future_input <- newEmptyMVar
  work future_input 'l'

work :: MVar Char -> Char -> IO ()
work future_input latest_input = do
  forkIO $ putMVar future_input =<< getChar
  wait future_input latest_input
    where
      wait :: MVar Char -> Char -> IO ()
      wait future_input latest_input =
        tryTakeMVar future_input >>=
          \case Just input -> putStrLn ("new input " ++ return input)
                              >> work future_input input
                Nothing    -> putStrLn ("old input " ++ return latest_input)
                              >> threadDelay 100000
                              >> wait future_input latest_input

Some thoughts on about the code:

I've tried to use applicative/monadic style wherever I could, without compromising readability too much;
as regards the concurrentcy-handling part, basically the wait function, I preferred using the do sugar because I could hardly get something working this way.


texts:
Please review this code
I have written a function to find the successor of BST in c. It takes three arguments, i.e root pointer to the binary search tree, node value of which we have to find a successor and parent pointer (for first call it is also root pointer. It will return an integer that is the successor of the node value give.
/**
 * find Successor of BST, complex: o(h)
 * @param rootPtr root pointer of BST
 * @param parent_node parent node of the subtree (root node should be passed by default)
 * @param nodeValue node val to find successor
 * @return succsor
 */
int find_successor_h(BSTNode * rootPtr, int data, BSTNode * parent_node) {
  if (rootPtr == NULL) return data;
  int rt;

  if (data < rootPtr -> data)
    rt = find_successor_h(rootPtr -> left_child, data, rootPtr);
  else if (data > rootPtr -> data)
    rt = find_successor_h(rootPtr -> right_child, data, rootPtr);
  else {
    if (rootPtr -> right_child != NULL)
      return minBST(rootPtr -> right_child);
    else if (rootPtr != parent_node)
      return INT_MIN;
    else
      return data;
  }

  if (rt == INT_MIN)
    return INT_MAX;

  if (rt == INT_MAX)
    return parent_node -> data;
}


texts:
I have written this snippet to find r-permutations of n, i.e. if I have an array of n=3 {0,1,2}, then r=2 permutations will be {{0, 1}, {0, 2}, {1, 0}, {1, 2}, {2, 0}, {2, 1}}.
Can somebody review it and help me optimize / reduce its complexity (I don't want to use recursive function):

"_getAllPermutation": function(input, allPermutations, usedIndices, r) {
    var index = 0,
        usedIndex = null;

    for (; index < input.length; index++) {
        usedIndex = input.splice(index, 1)[0];
        r--;
        usedIndices.push(usedIndex);
        if (input.length === 0 || r === 0) {
            allPermutations.push(usedIndices.slice());
        }
        if (r > 0) {
            this._getAllPermutation(input, allPermutations, usedIndices, r);
        }
        input.splice(index, 0, usedIndex);
        r++;
        usedIndices.pop();
    }
}


texts: Returning containers from function - C++

texts:
I've been trying to implement a few interfaces for processing data. And most of the time I do new of container and return a smart pointer to this container. Something like this:

class GenericUtil
{
    private:
        // Some members here

    public:
        unique_ptr<vector<string>> BreakStringOnDelimiter( string& dataStr );
};

But recently I came across "The c++ Programming Language" book and observed that Stroustrup seems to be suggesting to return containers just like that. But some other cases, he also demonstrates use of smart pointers for the same. So I have been just wondering what would be most efficient and maintainable way (plus a style which doesn't come as surprise to other fellow devs) of doing this?

unique_ptr<vector<string>> BreakStringOnDelimiter( string& dataStr );

or

vector<string> BreakStringOnDelimiter( string& dataStr );

or

vector<string>* BreakStringOnDelimiter( string& dataStr );

or something else?

Please suggest which one and why?

Thanks in advance!


texts: Better way to work with clickable regions of window

texts:
The Goal
Basically, what I'm looking for is the ability to click a region below an image to trigger a click() event which will scroll the window to the following image.
The Question
Is there a better way to do this? I've achieved the result I want, but with a whole ton of <divs>? I know there are some plugins out there but I'd like to do it without including a large library.
The progress...
I've done this by placing several "invisible"
 elements around the image which are bound to click events. Later on I'll try to work through left, right, and top scrolling.
A live preview is available here.
Here is the code:
...

  // these are the "invisible divs"

$("document").ready(function() {

    $(".bottomclick").click(function() {
        console.log("Scroll jquery is working");
        $( this ).parent().addClass("activeproj");
        let $target = $(".activeproj").next(".main-proj");
        if ($target.length == 0 )
            $target = $(".main-proj:first");

        $([document.documentElement, document.body]).animate({
        scrollTop: $($target).offset().top
        }, 2000);

        $('.activeproj').removeClass('activeproj');
    });
});


texts: MySQL query: blog entry has comments or not

texts:
How expensive is this query?

Lets say for example if I don't have a field called total_comments in my blog table. All I want to know is the blog has comments or not.

SELECT EXISTS (SELECT true FROM comments WHERE blog_id = b.id) as has_comments FROM blogs b

How else could this be achieved?


texts: Avoiding using strings when using Spring.Net by incorporating instantiation in class

texts:
Totally new to MVP and Spring, and I have what seems to be typical MVP application that uses Spring, where the presenter is instantiated like:

IApplicationContext ctx = ContextRegistry.GetContext();
presenter = (clsPresenter)ctx.GetObject("clsPresenter");

I hate using strings to call code, really, I hate it.  So I'm thinking of putting something like

static private readonly string _clsName = typeof(ClsPresenter).Name.ToCamelCase();
public static ClsPresenter getNewPresenterFromSpring()
{
    IApplicationContext ctx = ContextRegistry.GetContext();
    return (ClsPresenter)ctx.GetObject(_clsName);
}

into all of the presenters.  So that instead of the the two lines above which use a string to find the presenter, it would be one line using the static method:

presenter = ClsPresenter.getNewPresenterFromSpring();

I know this violates the SRP, and it might look to be introducing some coupling between the Presenter classes and Spring, but it seems to me that it's not really coupled any more than it was before, it's just now type (and typo) safe, while living in a somewhat weird place.  If I stop using Spring, I simply replace this call with whatever else gets used instead.

Am I missing something that makes this a really bad idea?  Is there a better way of avoiding the usage of strings?  Should I just suck it and make sure I don't spell "clsPresenter" as "classPresenter"?


texts:
I'm currently on Ch 4 Lab 4 in Programming Arcade Games with Python and Pygame.

Any feedback on how I could improve the code would be awesome. I'm using Python IDLE 3.4.3.

import random

print("Welcome to Camel!")
print("""You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.""")
print()

#variables
milesTraveled = 0
thirst = 0
camelFatigue = 0
nativesTraveled = -20
canteen = 3
done = False

#start main loop
while not done:
    nativesBehind = milesTraveled - nativesTraveled
    fullSpeed = random.randrange(10, 21)
    moderateSpeed = random.randrange(5, 13)
    print("""
    A. Drink from your canteen.
    B. Ahead at moderate speed.
    C. Ahead full speed.
    D. Stop for the night.
    E. Status check
    Q. Quit.""")
    print()
    userInput = input("Your choice? ")
    if userInput.lower() == "q":
            done = True

#status
    elif userInput.lower() == "e":
        print("Miles traveled: ",milesTraveled)
        print("Drinks in canteen: ",canteen)
        print("Your camel has ",camelFatigue,"amount of fatigue.")
        print("The natives are ",nativesBehind,"miles behind you.")
#stop for night
    elif userInput.lower() == "d":
        camelFatigue *= 0
        print("Your camel feels refreshed and happy his fatigue is now ",camelFatigue)
        nativesTraveled += random.randrange(7, 15)
#move full speed
    elif userInput.lower() == "c":
        print("You traveled ",fullSpeed,"miles!")
        milesTraveled += fullSpeed
        thirst += 1
        camelFatigue += random.randrange(1, 4)
        nativesTraveled += random.randrange(7, 15)
        oasis = random.randrange(1, 21)

#move moderate speed
    elif userInput.lower() == "b":
        print("You traveled ",moderateSpeed,"miles!")
        milesTraveled += moderateSpeed
        thirst += 1
        camelFatigue += 1
        nativesTraveled += random.randrange(7, 15)
        oasis = random.randrange(1, 21)

        #drink canteen
    elif userInput.lower() == "a":
        if canteen == 0:
            print("You're out of water.")
        else:
            canteen -= 1
            thirst *= 0
            print("You have ",canteen,"drinks left and you are no longer thirsty.")

#not done check
    if oasis == 20:
        camelFatigue *= 0
        thirst *= 0
        canteen = 3
        print("You found an oasis! After taking a drink you filled your canteen and the camel is refreshed.")
    if nativesBehind <= 15:
        print("The natives are drawing near!")
    if milesTraveled >= 200 and not done:
        print("You made it across the desert, you win!")
        done = True
    if nativesTraveled >= milesTraveled:
        print("The natives caught and beheaded you.")
        print("You're dead!")
        done = True
    if thirst > 4 and thirst <= 6 and not done:
        print("You are thirsty")
    if thirst > 6:
        print("You died of dehydration!")
        done = True
    if camelFatigue > 5 and camelFatigue <= 8 and not done:
        print("Your camel is getting tired.")
    if camelFatigue > 8:
        print("Your camel is dead.")
        done = True


texts:
I'm still somewhat new to C, so pardon me for any silly mistakes I've made.

I'm trying to convert video frames into Minecraft map colors using JNI and FFmpeg's av (and swscale) libraries. The code works below but it's sluggish and I'm going to assume it's prone to the branch prediction problem.

The Minecraft map data is stored in ctx->data; it's a 16384 byte array that's fetched from a direct ByteBuffer via GetDirectBufferAddress.

convertRow is called from a thread pool (taken from here); the thread pool has 4 threads to use.

Current specs of the computer:

  8GB of RAM

  i5 650 @ 3.19GHz

// http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi
float fast_sqrt(const float x){
    union
    {
        int i;
        float x;
    } u;

    u.x = x;
    u.i = (1<<29) + (u.i >> 1) - (1<<22);
    return u.x;
}

// forgot where this was from; TODO: find source
double dist(unsigned char r, unsigned char g, unsigned char b, Color e2) {
    int rmean = (r + e2.r ) / 2;
    int rDiff = r - e2.r;
    int gDiff = g - e2.g;
    int bDiff = b - e2.b;
    return fast_sqrt((((512+rmean)*rDiff*rDiff)>>8) + 4*gDiff*gDiff + (((767-rmean)*bDiff*bDiff)>>8));
}

char matchColor(unsigned char r, unsigned char g, unsigned char b){
    int index = 0;
    double best = -1;
    double distance;
    for (int i = 4; i < ARR_LENGTH(mapColors); ++i) {
        distance = dist(r, g, b, mapColors[i]);
        if (distance < best || best == -1.0f) {
            best = distance;
            index = i;
        }
    }

    return (char)(index < 143 ? index : -144 + (index - 143));
}

static void convertRow(void* ptr){
    param* params = (param*)ptr;
    int p;
    unsigned char r, g, b;

    for (int y = 0; y < params->ctx->height; y++) {
        p = params->x * 3 + y * params->ctx->rgbFrame->linesize[0];
        r = params->ctx->rgbFrame->data[0][p];
        g = params->ctx->rgbFrame->data[0][p + 1];
        b = params->ctx->rgbFrame->data[0][p + 2];
        params->ctx->data[(params->x / 128) + (params->ctx->width / 128) * (y / 128)][((params->x % 128) + 128 * (y % 128))] = matchColor(r, g, b);
    }

    latch_countdown(params->ctx->latch);
}

JNIEXPORT jboolean JNICALL Java_ga_nurupeaches_vivianmap_natives_NativeVideo_n_1readFrame(JNIEnv* env, jobject jthis, jlong ptr){
    Context* ctx = (Context*)ptr;

    while((ctx->read = av_read_frame(ctx->formatCtx, &(ctx->packetIn))) >= 0){
        if(ctx->packetIn.stream_index == ctx->vtrackId){
            avcodec_decode_video2(ctx->codecCtx, ctx->rawFrame, &(ctx->finished), &(ctx->packetIn));
            if(ctx->finished){
                sws_scale(ctx->sws, (const uint8_t* const*)ctx->rawFrame->data,
                          ctx->rawFrame->linesize, 0, ctx->codecCtx->height,
                          ctx->rgbFrame->data, ctx->rgbFrame->linesize);

                break;
            }
        }
    }

    if(ctx->read < 0){
        // bad. don't do this.
        // stop doing this me.
        Java_ga_nurupeaches_vivianmap_natives_NativeVideo_n_1close(env, jthis, ptr);
    }

    // lock count mutex so that we don't have a race condition
    latch_lockCount(ctx->latch);
    for(int x=0; x < ctx->width; x++){
        param* params = malloc(sizeof(param));
        params->ctx = ctx;
        params->x = x;
        threadpool_add(ctx->pool, convertRow, params, 0);
    }
    // unlock mutex after all tasks have been submitted
    latch_unlockCount(ctx->latch);

    // wait for count to hit 0
    latch_wait(ctx->latch);
    // reset latch
    latch_reset(ctx->latch);
    return true;
}

Any suggestions (especially performance improvements) would be appreciated! I'm willing to edit more code into the question if you need it; I just didn't because I didn't want it to become a needle in a haystack problem.


texts: Write a function to extract a given number of randomly selected elements from a list

texts:
I'm going through the 99 Haskell problems and I have a few question about the solution I implemented for Problem 23.

It asks:

  Extract a given number of randomly selected elements from a list.

This is the code I came up with:

-- Extract a given number of randomly selected elements from a list.
import System.Random

randomFromList :: StdGen -> Int -> [a] -> ([a], StdGen)

randomFromList generator 0 _ = ([], generator)
randomFromList generator toDo xs =
  let (nextInt, generator') = next generator
      index = mod nextInt (length xs)
      (otherNumbers, generator'') = randomFromList generator' (toDo -1) xs
  in  ((xs !! index) : otherNumbers, generator'')

It works, but I'm not sure this is idiomatic Haskell nor that it is the best way to address this problem.

None of the solutions in the Haskell wiki uses the let approach so I was wondering if it is discouraged for some reason.


texts: Counting pairs of integers which have a predefined difference

texts:
I'm doing this HackerRank problem:

  Given \$N\$ integers, count the number of pairs of integers whose difference is \$K\$.

So far, I've ended up with this code:

def countPairs(ar, n, k):
    ar.sort()
    temp = list(ar)
    i = 0
    j = n - 1
    cnt = 0
    while i < n:
        while abs(ar[i] - temp[j]) > k and j > 0:
            j -= 1
        if abs(ar[i] - temp[j]) == k:
            cnt += 1
        i += 1
        j = n - 1
    return cnt

if __name__ =='__main__':
    N, K = map(int, raw_input().strip().split())
    A = map(int, raw_input().strip().split())
    print countPairs(A, N, K)

The problem is some test cases terminated due to timeout (took more than 10 seconds).

I tried calculating the time complexity. Sorting the list in the first step of countPairs takes \$O(n\log n)\$ and copying the list in the second step into temp takes \$O(n)\$.

This link says that the "two-pointer technique" has \$O(n)\$ complexity. So, the overall complexity is \$O(n \log n)\$. Does anyone know how to make it run faster?

To be honest, I think the "two-pointer technique" isn't \$O(n)\$, but \$O(n^2)\$ because of the two while loops, but I'm not sure.


texts:
I'm learning F#, and even though I'm able to do whatever I want, parts of my code looks really bad. I would love to get some suggestions on how to improve a couple of functions involving some conditional logic.

let stripLast (punct : char) (word : string) =
    if word.Length > 0 && word.LastIndexOf(punct) = word.Length - 1
    then word.Substring(0, word.Length - 1)
    else word

let countWord (dictionary : Dictionary<string, int>) word =
    if word = "" || (blacklisted word) then "" |> ignore
    elif dictionary.ContainsKey(word)  then dictionary.[word] <- dictionary.[word] + 1
    else dictionary.[word] <- 1

I'm guessing there are ways to make these much more elegant. For instance, the second function uses side-effects on a Dictionary and has return type unit, but I added a branch where I had to use ignore in (probably) a silly way. Please don't change the functionality, but show me a nicer way to write the code.


texts: What is the more effective way to get array of data out of xml for d3 chart?

texts:
I am writing a small application that would interactively allow user for xml file manipulation with d3 interactive charts.

My xml file has the following hierarchy :

<?xml version="1.0" encoding="UTF-8" ?>
<testcase>

  <measurement>
    <type>M8015</type>
    <interval>15</interval>
  </measurement>
  <measurement>
    <type>M8016</type>
    <interval>15</interval>
  </measurement>
  <measurement>
    <type>M8020</type>
    <interval>15</interval>
  </measurement>
   ...
</testcase>

What would be the most effective way to get the data out of xml into 2 arrays (one for x axis type, and one for y axis interval).

I have tried the following but don't know if that's a good approach.

$(function() {
  var $mydata = new Array(1);
  $.get("./testcase.xml", function(xml) {

      var $chart = d3.select("body").append("div")
          .attr("class", "chart")
          .attr("id", "chart");

      $(xml).find('measurement').each(function(){
        var $meas = $(this);
        var $type = $meas.find('type').text();
        var $interval = $meas.find('interval').text();

        $mydata.push({'type': $type, 'interval': $interval});
    });
});

Any suggestions if that's the correct way of handling this problem ?


texts: Find an unknown length using sohcahtoa (Trigonometry)

texts:
Here is a calculator for an unknown side in a right-angle. Is there a more efficient way of doing this?

import math
def trigonometry(angle, side_length, known, unknown):
    o, h, a = 'opposite', 'hypotenuse', 'adjacent'
    sohcahtoa = {o: {h: math.sin, a: math.tan},
                 h: {o: math.sin, a: math.cos},
                 a: {o: math.tan, h: math.cos}}
    function = sohcahtoa[known][unknown]
    return side_length / function(math.radians(angle)) if known == 'opposite' or (known == a and unknown == h)\
        else function(math.radians(angle) * side_length)

    print(trigonometry(30, 1, 'opposite', 'hypotenuse'))

I particularly dislike this line as it is basically brute force and very long.

return side_length / function(math.radians(angle)) if known == 'opposite' or (known == a and unknown == h)\
        else function(math.radians(angle) * side_length)

Test Calls

Here are two test calls to make sure the code works.

Call: trigonometry(30, 1, 'opposite', 'hypotenuse')
Expected Output: 2

Call: trigonometry(30, 2, 'hypotenuse', 'opposite')
Expected Output: 1


texts:
Please critique my TODO App in React w/ Redux:

// React Component
const TodoApp = ({todos, inputText, onInputChange, onAdd, onDelete}) => {
    const numbers = range(todos.length);
    const zipped  = zip(numbers, todos);

    return (

TODO!

{zipped.map( (z) =>

                        {z[1].text}
                        <button onClick={() => onDelete(z[0])}>delete</button>

                )}

                    <input type="text" value={inputText} onChange={onInputChange}/>
                    <button onClick={onAdd}>add</button>

    );
};

// Redux (State)
const ADD = 'ADD';
const UPDATE_INPUT_TEXT = 'UPDATE_INPUT_TEXT';
const DELETE='DELETE';

function todo(state = {todos: [], inputText: ""}, action) {
    switch(action.type) {
        case ADD:
            return {
              todos: state.todos.concat( {
                text: state.inputText
              }),
              inputText: ''
            };
        case UPDATE_INPUT_TEXT:
            return {
                todos: state.todos,
                inputText: action.newInputText
            };
        case DELETE:
            const filtered = state.todos.filter( (e, index) => index !== action.index);
            return {
                todos: filtered,
                inputText: ''
            };
        default:
            return state;
    }
}

const store = createStore(todo);

const renderTodo = () => {
    const st = store.getState();
    ReactDOM.render(
        <TodoApp todos={st.todos}
                 inputText={st.inputText}
                 onInputChange={event =>
                     store.dispatch({type: UPDATE_INPUT_TEXT, newInputText: event.target.value})
                 }
                 onAdd={() => store.dispatch({type: ADD})}
                 onDelete={(index) => store.dispatch({type: DELETE, index: index})}

        />,
        document.getElementById('root')
    )
};

store.subscribe(renderTodo);
renderTodo();


texts:
https://leetcode.com/problems/stone-game/

Alex and Lee play a game with piles of stones.  There are an even
number of piles arranged in a row, and each pile has a positive
integer number of stones piles[i].
The objective of the game is to end with the most stones.  The total
number of stones is odd, so there are no ties.
Alex and Lee take turns, with Alex starting first.  Each turn, a
player takes the entire pile of stones from either the beginning or
the end of the row.  This continues until there are no more piles
left, at which point the person with the most stones wins.
Assuming Alex and Lee play optimally, return True if and only if Alex
wins the game.
Example 1:
Input: piles = [5,3,4,5] Output: true Explanation:  Alex starts first,
and can only take the first 5 or the last 5. Say he takes the first 5,
so that the row becomes [3, 4, 5]. If Lee takes 3, then the board is
[4, 5], and Alex takes 5 to win with 10 points. If Lee takes the last
5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alex,
so we return true.
Constraints:
2 <= piles.length <= 500 piles.length is even. 1 <= piles[i] <= 500
sum(piles) is odd.

I am working on my recursion an dynamic programming skills. please review for performance
solution 1: recursion
public bool StoneGame(int[] piles)
{
    return Helper(piles, 0, piles.Length - 1, 0, 0, true);
}

private bool Helper(int[] piles, int start, int end, int sumAlex, int sumLee, bool isAlex)
{
    if (start >= end)
    {
        return sumAlex > sumLee;
    }
    if (isAlex)
    {
        return Helper(piles, start + 1, end, sumAlex + piles[start], sumLee, false)
               || Helper(piles, start, end - 1, sumAlex + piles[end], sumLee, false);
    }
    else
    {
        return Helper(piles, start + 1, end, sumAlex, sumLee + piles[start], true)
               || Helper(piles, start, end - 1, sumAlex, sumLee + piles[end], true);
    }
}

Solution 2: DP
public class Solution
{
    private int[,] dp;
    public bool StoneGame3(int[] piles)
    {
        dp = new int[piles.Length, piles.Length];
        for (int i = 0; i < piles.Length; i++)
        {
            for (int j = 0; j < piles.Length; j++)
            {
                dp[i, j] = -1;
            }
        }
        //begin or end of the row
        int s = 0;
        int e = piles.Length - 1;
        Helper(s, e, true, piles);
        return dp[0, piles.Length - 1] > 0;
    }

    private int Helper(int s, int e, bool isAlex, int[] piles)
    {
        if (s > e)
        {
            return 0;
        }

        if (s == e)
        {
            return piles[s];
        }

        if (dp[s, e] != -1)
        {
            return dp[s, e];
        }

        if (isAlex)
        {
            dp[s, e] = Math.Max(piles[s] + Helper(s + 1, e, !isAlex, piles), piles[e] + Helper(s, e - 1, !isAlex, piles));
        }
        else
        {
            //we remove what lee is picking and we will take the min so we will have the max stones for alex
            dp[s, e] = Math.Min(-piles[s] + Helper(s + 1, e, !isAlex, piles), -piles[e] + Helper(s, e - 1, !isAlex, piles));
        }
        return dp[s, e];
    }
}


texts:
A previous developer had an array of strings like so:

public static const PAGE_ONE:String     = 'PageOne';
public static const PAGE_TWO:String     = 'PageTwo';
public static const PAGE_THREE:String   = 'PageThree';
public static const PAGE_FOUR:String    = 'PageFour';
public static const PAGE_FIVE:String    = 'PageFive';
public static const PAGE_SIX:String     = 'PageSix';

When he wanted to open a new type of page he would write

switch ($page)
{
    case PAGE_ONE:
        // Do stuff
        break;

    ...

    case PAGE_SIX:
        // Do stuff
        break;
}

Which was all well and good, but I thought it could be condensed a little bit, so I created a little more functional approach.

In the constructor, this function is called setting up the table:

    private function setDefaultPages() : void {
        _pages[PAGE_ONE]          = function($xml:XMLList)  { return new PageOne( $xml ); }

        ...

        _pages[PAGE_SIX] = function($xml:XMLList)   { return new PageSix( $xml ); }
    }

Now, when the time comes to open a page, all I have to write is this:

_nextPage = _pages[$page](xml);

However, I am worried that I have hurt readability by doing this. Could anybody suggest a good middle-ground if it is so?


texts: Structuring objects for proper MVVM in Knockout

texts:
I'm working with knockout and am trying to stay true the MVVM structure and trying to make the objects have that dependency on each other.

Model, ViewModel, Service definitions:

var App = window.App || {};

(function(ns, $, ko) {
    ns.Models = {};
    ns.ViewModels = {};
    ns.Services = ns.Services || {};

    //Service def
    ns.Services.SearchService = function() {
        this.SearchByName = function(name, callback) {
            $.get("/api/SearchByName/" + name, function(d){
                callback(d);
            });
        };
    };

    //Model Def
    ns.Models.SearchResultModel = function(json) {
        var self = this;

        ko.mapping.fromJS(json, {}, self);
    };

    //ViewModel def
    ns.ViewModels.SearchResultsViewModel = function() {
        var self = this;

        self.dataService = new ns.Services.SearchService();
        self.SearchResults = ko.observableArray();

        self.GetSearchResultsByName = function(name){
            self.dataService.SearchByName(name, function(d) {
                $.each(d, function(i, e) { self.SearchResults.push(new ns.Models.SearchResultModel(e)); });
            });
        };
    };
}(App, jQuery, ko));

And I can currently use it like so:

var vm = new App.ViewModels.SearchResultsViewModel();

vm.GetSearchResultsByName("Doe");

ko.applyBindings(vm, document.getElementById("search-results-form"));

This is just my starting point and it seems like the ko.applyBindings(...) should be in the ViewModel somewhere.

With all that, am I going the right direction for this or am I completely off with it?


texts: Determining the value of a position on an array based on its nearest datapoint known value

texts:
I was wondering what would be the efficient way to determine the value of a position on an array based on its nearest datapoint known value in Python?

  Problem description:

  There are datapoints in an array which are 1000 units apart and their values are known (see the figure). However,
  there are datapoints which fall between the known datapoints and their
  values should be determined based on their nearest known datapoint.

  For instance, following the figure, the value of the datapoint at
  position 124200 should be set to 435 and the value of the datapoint at
  position 124850 should be set to 380.

At the moment, I am doing it like this:

# 'values' is an array which has the values for the known datapoints
# 'position' is an array that has the datapoints which their values should be determined
# 'step' keeps the number of units in between two datapoints with known values
# 'n' is a list which keeps the extracted values

for pos in positions:
    if pos % step <= 500:
        idx = (( pos - (pos % step)) / step) - 1
        n.append(values[idx])
    else:       #pos % step > 500:
        idx = (( pos + (step - (pos % step))) / step)  - 1
       n.append(values[idx])

I was also considering implementing the logic with addition and subtraction operations instead of modulo and division operations, but after some discussion with a friend, we came up with the conclusion that modern processors in doing divisions and multiplication are as fast as doing addition and subtraction, so I ruled that option out.


texts:
In C++11, I tend to have master objects that maintain sole ownership of a collection of some children objects.  Let's assume these children objects are non-copyable (for instance, boost::noncopyable).

Other code needs to access these children objects to do some temporary processing, but not keep references, or share ownership over these objects.

As such, my master objects tend to have some sort of a get_child() method.

As an example, let's say I have a Master object like this:

class Master {
private:
  std::vector<std::unique_ptr<Child>> children;
  ...
public:
  ??? get_child(int index);
};

When writing the get_child() method, I have 2 obvious options:

Return by pointer:

Child* get_child(int_index) {
  return children[index].get();
}

Return by reference:

Child& get_child(int index) {
  return *(children[index]);
}

I thought I didn't like either of these (for reasons I explain below), so I came up with the following:

borrowed_ptr<Child> get_child(int index) {
  return make_borrowed<Child>(children[index].get());
}

where borrowed_ptr is a trivial class wrapping a pointer with no smarts.  I provide its implementation at the end of this question.

To me, borrowed_ptr indicates that there exists a unique_ptr someplace, and this borrowed_ptr should be used for a short time, and not be recorded for any circumstance.

I don't like returning by raw pointer (1.) because I feel that Child* doesn't imply that there exists a unique_ptr<Child> someplace.  Namely, I already have a lot of raw pointers floating around (think handles received from libraries, or my code which is not using smart pointers).  I feel borrowed_ptr gives a little more information over a raw pointer.

I don't like returning by reference (2.) because of an additional reason.  I am worried that I will write

Child child = get_child();

and invoke a copy when I didn't intend to.

My question: Is borrowed_ptr silly? Does it raise red flags with experienced C++ developers?  Is it a faux pas?  Does it feel like a code smell?  Do you feel I should rather do 1., 2. or something else altogether?

Here is my implementation of borrowed_ptr:

template<typename T>
class borrowed_ptr {
private:
  T* ptr;
public:
  borrowed_ptr(const unique_ptr<T>& r) {
    ptr = r.get();
  }

  inline T* operator->() {
    return ptr;
  }
  inline const T* operator->() const {
    return ptr;
  }
  inline T& operator*() {
    return *ptr;
  }
  inline const T& operator*() const {
    return *ptr;
  }
};


texts:
I use Electron with NodeJS but this is mainly a javascript question. I got tired of build processes and being dependent of frameworks like Vue so I started my own.

Setup in index.html

A component example

module.exports = {
  html() {
    return /*html*/ `

      Some HTML ${component('someOtherComponent')}

    `;
  },
  created() {
    this.myCustomMethod();
  },
  init() {
    console.log("After HTML is placed on site");
  },
  myCustomMethod() {
    console.log("Custom method, before HTML is placed on site");
  }
};

Is it a good approach? Are there any pitfalls with it that you see?


texts: std::vector memory manipulation with serialization and deserialization

texts:
This is my code and I would like to get it code reviewed. It is functional and behaves as expected.

I pass some basic types to the Serialize() function and then deserialize the output to get back the original value.

size_t returnSize(const char* s)
{
       string string(s);
       return string.size();
};
template<typename T>
size_t returnSize(const T& t)
{
       return sizeof(t);
};

template<typename T>
string Serialize(const T& t)
{
    T* pt = new T(t);
    vector<char> CasttoChar;

    for (int i =0 ;i<returnSize(t);i++)
    {
        CasttoChar.push_back(reinterpret_cast<const char*>(pt)[i]);
    }
    delete pt;
    return  string( CasttoChar.begin(), CasttoChar.end() );

};

template<>
string Serialize<string>(const string& t)
{
    return Serialize(t.c_str());
};

template<typename T>
T DeSerialize(const string& cstr)
{
    const T* a = reinterpret_cast<const T*>(cstr.c_str());
    return *a;
}

template<>
string DeSerialize<string>(const string& cstr)
{
    return DeSerialize<char*>(cstr);
}

int _tmain(int argc, _TCHAR* argv[])
{
    int x = 97;
    string c = Serialize<int>(x);
    cout << DeSerialize<int>(c) << endl;

    char g = 'g';
    string c2 = Serialize<char>(g);
    cout << DeSerialize<char>(c2) << endl;

    string k = "blabla";
    string c3 = Serialize<const char*>(k.c_str());
    cout << DeSerialize<char*>(c3) << endl;

    string ka = "string";
    string c4 = Serialize<string>(ka);
    cout << (DeSerialize<string>(c4)).c_str();

    system("PAUSE");
    return EXIT_SUCCESS;
}


texts: Count arrays' of objects intersections based on several properties

texts:
I have two arrays as an input:

const set1 = [
  { id: 1 },
  { id: 2, name: 'd' },
  { id: 8, name: 'b' },
  { id: 7 },
];
const set2 = [
  { name: 'e' },
  { id: 1, name: 'a' },
  { name: 'b' },
  { id: 7 },
  { id: 16 },
];

What I need to do is to count how many objects in this two arrays are connected (share 1 or more property/value pairs).

So, what I am expecting to achieve, is 3.
More specifically, the list of connected objects will be (but it is not needed as an output):

{ id: 1, name: 'a' }
{ id: 7 }
{ id: 8, name: 'b' }

Here is my completely working code (and the link to it - https://jsbin.com/jexoxabere/1/edit?js,console)

const mergeObjects = (obj1, obj2) => {
  const result = {};
  for (let key in obj2) {
    if (obj1.hasOwnProperty(key)) {
      // If particular property has no value in obj2, assign it a value from obj1 to preserve connection between them
      result[key] = obj2[key] ? obj2[key] : obj1[key];
    }
  }
  return result;
}

const reduce = (arr) => (
  arr.reduce((acc, item) => {
    const { name, id } = item;
    if (id) {
      acc.id[id] = name || '';
    }
    if (name) {
      acc.name[name] = id || '';
    }
    return acc;
  }, {
    id: {},
    name: {},
  })
);

const set1Obj = reduce(set1);
const set2Obj = reduce(set2);

const mergedIDs = mergeObjects(set1Obj.id, set2Obj.id);
const mergedNames = mergeObjects(set1Obj.name, set2Obj.name);

for (let key in mergedIDs) {
  const value = mergedIDs[key];
  delete mergedNames[value];
}

console.log(Object.keys(mergedIDs).length +  Object.keys(mergedNames).length);

But I believe this code can be rewritten in a better way, meaning more performant algo, better readability (not meaning variables naming, but more readable flow itself) etc.


texts:
I am making an ArrayList that contains Map values. itemData is my ArrayList that contains itemselected, which is a map. Then, because I want to send this array to my PHP code, I am converting itemData into a JSONArray. Then parsing the array in my PHP script and inserting those individual values into a MySQL database.

private ArrayList<Map<String, String>> itemData = new ArrayList<>();
private Map<String, String> itemselected = new HashMap<>();
JSONArray itemSelectedJson = new JSONArray();

 private void selectedItems() {
        if(invEstSwitch.isChecked())
        {
            billType = textViewEstimate.getText().toString();
        }else{
            billType = textViewInvoice.getText().toString();
        }

        itemselected.put("custInfo",custSelected.toString());
        itemselected.put("invoiceNo", textViewInvNo.getText().toString());
        itemselected.put("barcode", barCode.getText().toString());
        itemselected.put("desc", itemDesc.getText().toString());
        itemselected.put("weight", weightLine.getText().toString());
        itemselected.put("rate", rateAmount.getText().toString());
        itemselected.put("makingAmt", makingAmount.getText().toString());
        itemselected.put("net_rate", netRate.getText().toString());
        itemselected.put("itemTotal", itemtotal.getText().toString());
        itemselected.put("vat", textViewVat.getText().toString());
        itemselected.put("sum_total", textViewSum.getText().toString());
        itemselected.put("bill_type", billType);
        itemselected.put("date", textViewCurrentDate.getText().toString());

        //Add the map to the Array
        itemData.add(index, itemselected);
        itemSelectedJson= new JSONArray(Arrays.asList(itemData));
        index++;
    }

The code is pretty straightforward, but I am interested in any possible improvement. I am sure there is a better way to do it.


texts: CSS3 transitions performance enhancement

texts:
I am building a website with heavy CSS3 transitions. The menu is hidden on the left and slides in on hover pushing the main content right. The menu contains transformed elements and has a semi transparent background.

I am concerned about the performance of the animations. When the animation is triggered several times (and also often on the first trigger) the frame rate goes under 30 FPS.

How can I enhance the performance of the animation and have a higher frame rate?

I tried making these animation with jQuery and it is worse.

I made a simple example that has the FPS issue here (hover the envelope icons on the left).

HTML:

body,html,ul,li {margin: 0; padding: 0;}
nav {
  width: 0; height: 100%;
  position: fixed;
  top: 0; left: 0;
  background-color: rgba(255, 145, 0, 0.8);
  -webkit-transition: width .5s ease-out;
  transition: width .5s ease-out;
}
nav:hover {
  width: 40%;
}
ul {
  list-style-type: none;
  position: absolute;
  width: 60%;
  left: 20%;
}
nav li {
  position: relative;
  margin: 0.5em 0;
  padding: 0.5em;
  min-width: 5em;
}
nav li:before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  background: teal;
  z-index: -1;
  opacity: 0;
  -webkit-transform: skewX(30deg);
  -ms-transform: skewX(30deg);
  transform: skewX(30deg);
  -webkit-transition: opacity .5s ease-out;
  transition: opacity .5s ease-out;
}
nav:hover li:before {
  opacity: 1;
}
nav li * {
  vertical-align: middle;
}
nav img {
  height: 2em;
}
nav a {
  opacity: 0;
  -webkit-transition: opacity .5s ease-out;
  transition: opacity .5s ease-out;
}
nav:hover a {
  opacity: 1;
}
/* MAIN */

section {
  width: 60%;
  margin-left: 20%;
  min-height: 100%;
  background: url(http://lorempixel.com/output/nature-q-g-640-480-9.jpg);
  -webkit-transition: margin-left .5s ease-out;
  transition: margin-left .5s ease-out;
}
nav:hover +section {
  margin-left: 30%;
}

Home

About

Clients

Contact

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus porta augue vitae bibendum vulputate. Nam sed pulvinar neque. Pellentesque justo neque, aliquet at risus sed, tristique mattis purus. In laoreet diam at porttitor tempor. Vestibulum ante
    ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras in lorem sit amet purus egestas aliquet. Cras dignissim venenatis facilisis. Suspendisse id dui consectetur, lobortis mauris nec, egestas augue. Sed dui sapien, dignissim
    in dui eget, pretium laoreet leo. Phasellus semper faucibus elit eu consequat. Maecenas aliquam nibh sit amet sapien blandit, non sagittis mi vestibulum.

  ... More content ...


texts: Rock, Paper, Scissors, Lizard and Spock - Relational Paradigm

texts:
I found a few question about the game and IMHO it's a relational problem and better addressed by set logic. Thus I created this solution in SQL to get away from ugly JavaScript, elegant java and practical C#

--drop table [Hand]
--drop table [Action]

create table [Hand]
(
     Id int primary key not null
    ,Name varchar(20) not null
)

create table [Action]
(
     WinsId int not null
    ,LosesId int not null
    ,ActionText varchar(100) not null
)
GO

alter table [Action] with nocheck add constraint fk_ActionhandWins foreign key(WinsId) references [Hand] (Id)
alter table [Action] with nocheck add constraint fk_ActionhandLoses foreign key(LosesId) references [Hand] (Id)
GO

insert into [Hand] (Id, Name)
values
 (1, 'Rock')
,(2, 'Paper')
,(3, 'Scissors')
,(4, 'Lizard')
,(5, 'Spock')

insert into [Action] (winsId, ActionText, LosesId)
values
  (1, 'Crushes', 3)
 ,(1, 'Crushes', 4)
 ,(2, 'Covers', 1)
 ,(2, 'Disproves', 5)
 ,(3, 'Cuts', 2)
 ,(3, 'Beheads', 4)
 ,(4, 'Eats', 2)
 ,(4, 'Poisons', 5)
 ,(5, 'Vaporizes', 1)
 ,(5, 'Distrois', 3)

 GO

 -- All possiblities
 select w.Name + ' ' + a.ActionText + ' ' + l.Name
 from [Action] a
 join [Hand] w on w.Id = a.WinsId
 join [Hand] l on l.Id = a.LosesId

GO
--drop function dbo.RockPaperScissorsLizardSpock
create function dbo.RockPaperScissorsLizardSpock(@Player1 int, @Player2 int)
returns @Result table(Result varchar(200), [Text] varchar(200))
as begin

    insert into @Result
             select 'Player 1 Wins!' as Result, w.Name + ' ' + a.ActionText + ' ' + l.Name as [Text]
             from [Action] a
             join [Hand] w on w.Id = a.WinsId
             join [Hand] l on l.Id = a.LosesId
             where w.Id = @Player1
             and l.Id = @Player2
             UNION
             select 'Player 2 Wins!' as Result, w.Name + ' ' + a.ActionText + ' ' + l.Name as [Text]
             from [Action] a
             join [Hand] w on w.Id = a.WinsId
             join [Hand] l on l.Id = a.LosesId
             where w.Id = @Player2
             and l.Id = @Player1

    if not exists(select * from @Result)
    insert into @Result values ('Tie!','')

    return

end;
GO
-- Testing cases
select * from dbo.RockPaperScissorsLizardSpock(1,2)
select * from dbo.RockPaperScissorsLizardSpock(2,1)
select * from dbo.RockPaperScissorsLizardSpock(1,1)
GO

Advantages of this approach are it doesn't require any implementation to add more "hands" just keep populating the two tables.

Are there any disadvantages of this approach compared to using OOP?


texts: Rövarspråket Language Encoder and Decoder

texts:
Used Python 3 for a solution to a Reddit /r/DailyProgrammer challenge.

When we Swedes are young, we are taught a SUPER-SECRET language that only kids know, so we can hide secrets from our confused parents. This language is known as "Rövarspråket" (which means "Robber's language", more or less), and is surprisingly easy to become fluent in, at least when you're a kid...
Rövarspråket is not very complicated: you take an ordinary word and replace the consonants with the consonant doubled and with an "o" in between. So the consonant "b" is replaced by "bob", "r" is replaced with "ror", "s" is replaced with "sos", and so on. Vowels are left intact. It's made for Swedish, but it works just as well in English.
Your task today is to write a program that can encode/decode a string of text into Rövarspråket.

Encoder:
import string

def main():
    word = input('Enter Phrase : ')
    final_word = rövarspråket(word)
    print(final_word)

def is_vowel(letter):
    VOWELS = ['A', 'E', 'I', 'O', 'U', 'Y', 'Å', 'Ä', 'Ö']
    if str.upper(letter) in VOWELS:
        return True
    else:
        return False

def rövarspråket(word):
    new_word = []
    for character in word:
        if character.isalpha() and not is_vowel(character):
            new_word.append(character + 'o' + str.lower(character))
        else:
            new_word.append(character)
    return ''.join(new_word)

if __name__ == '__main__':
    main()

Decoder program is identical to the Encoder except for a different central function of course:
def decode_rövarspråket(word):
    original_word = []
    i = 0
    while i <= (len(word) - 1):
        original_word.append(word[i])
        if word[i].isalpha() and not is_vowel(word[i]):
            i += 3
        else:
            i += 1
    return ''.join(original_word)

I'm newer to Python and one of my main concerns is writing code that is idiomatic and properly "Pythonic". Another is the loop in the decoder program. The algorithm I decided to go with revolves around iterating one character for vowels and three for consonants (to skip the o and repeated letter). Using a for-loop seemed like it would involve jumping through more hoops than just biting the bullet and using a while instead.


texts: SQL server efficiency, comparing date time of latest record and the one under it

texts:
I have a snippet of SQL that compares the last two records and gives the datediff in seconds. However, the way I have it is quite slow, taking up to 20 seconds to execute depending on how many controllerIDs I need to check. What would be a more efficient way of doing this?

 select
                T.controllerID,
                datediff(ss, T.Max_dtReading, T1.Max_dtReading) As ElaspedTime
            from
                (
                    select
                        controllerID,
                        max(dtReading) as Max_dtReading
                    from ReaderData
                    where CardID = 'FFFFFFF0' AND (controllerID in(2,13,28,30,37,40))
                    group by controllerID
                ) as T
                outer apply(
                    select max(T1.dtReading) as Max_dtReading
                    from ReaderData as T1
                    where
                        T1.CardID = 'FFFFFFF0' AND (controllerID in(2,13,28,30,37,40))
                        and T1.controllerID = T.controllerID
                        and T1.dtReading < T.Max_dtReading
                ) as T1


texts: Choice Decision Maker (Random string from ArrayList)

texts:
I'm learning about inheritance and polymorphism in my CS class and thought it'd be a good idea to find something I could apply myself to. I have a lot of ideas, and sometimes there's things I want to do and things I don't want to do. Why not leave the decision-making up to Java?

I'm looking for feedback to make my code better: whether it's something I could do with readability or inheritance, or even data structure wise. Or if there's bugs that'd be nice to know too :)

There are multiple classes extending MakeChoice, I just didn't put them here.

import java.util.*;

public class MakeChoice {

    // main
    public static void main(String[] args) {
        makeChoice makerShareChoice = new makeChoiceMakerShare();
        System.out.println(makerShareChoice);
    }

    public static int getChoiceForArrayList(int size) {
        int choice = generateRandomIntRange(0, size - 1);
        return choice;
    }

    public static int generateRandomIntRange(int min, int max) {
        int range = (max - min) + 1;
        int random = (int) (Math.random() * range + min);
        return random;
    }

}

import java.util.*;

public class MakeChoiceMakerShare extends makeChoice {
    private static ArrayList<String> choices = new ArrayList<String>();

    public makeChoiceMakerShare() {
        super();
        choices.add("acrylic LED");
        choices.add("MESA EduPi");
        choices.add("Collage of whiteboard wall");
        choices.add("sponge mitts");
        choices.add("hooks in closet");
        choices.add("10 x 10 LED Matrix");
        choices.add("What should I make? CoMotion addition to matrix");
        choices.add("What should I do this week? Screen");
        choices.add("Lasercraft belt + UW belt buckle + Wallet");
    }

    public String toString() {
        return "Your choice for this week in " + this.getClass() + " is: " + choices.get(getChoiceForArrayList(choices.size()));
    }
}


texts:
As part of my college class, I have to write a program that returns the "smallest" letter in the string. Input is assumed to be a non empty string. "Smallest" is defined as:

  The smallest decimal value of the character, pertaining to this chart.

The range of acceptable values is 0 <= x <= 127

I would like to get feedback on the algorithm of the code. Other suggestions are accepted and welcome, but the main algorithm is the main focus.

def smallest_letter(string: str) -> str:
    """
    Returns the smallest letter in the string

    Input is restricted to ASCII characters in range 0 <= character <= 127

    :param string: A string containing only ASCII letters

    :return: A string length one of the smallest letter
    """

    # Ensure all characters are within the acceptable range #
    for character in string:
        assert ord(character) <= 127

    smallest_letter = 1000
    for letter in string:
        if ord(letter) < smallest_letter:
            smallest_letter = ord(letter)
    return chr(smallest_letter)

if __name__ == "__main__":

    # Test Cases #

    assert smallest_letter("abydsufaksjdf") == "a"
    assert smallest_letter("bfsufsjfbeywafbiu") == "a"
    assert smallest_letter("ABYUVGDuibfsafuofiw") == "A"


texts: Search through server folders and display files that exist

texts:
I have a folder called uploads in this folder is a folder for the year the file was uploaded(2013,2014,2015 etc...), inside the year folder are usernames(rick, dan, edward etc...), inside the usernames folder are folders 1-12 for the month that the file was uploaded.

I want to search through the folders and if there is a file in the folder display the link, the problem I am having is figuring out how to do the check on all of the folders:

Here is my code so far:

<?php

        //array for years to check for
        $year = array('2013','2014','2015','2016','2017','2018','2019','2020');
        $month = array('1','2','3','4','5','6','7','8','9','10','11','12');

        //loop through years array and populate $existingYears[] array with years that exist on server
        foreach($year as $years){

            if(is_dir($yearPath = ABSPATH."/"."uploads/".$years."/".$username)){

                $existingYears[] = $years;

            }

        }

        //loop through existings years
        foreach($existingYears as $year){

            //title
            print "
".$year."
";

                //loop for months
                for ($i=1; $i<=12; $i++) {

                    if($i == 1){
                        $title = "January";
                    } elseif($i == 2){
                        $title = "February";
                    }elseif($i == 3){
                        $title = "March";
                    }elseif($i == 4){
                        $title = "April";
                    }elseif($i == 5){
                        $title = "May";
                    }elseif($i == 6){
                        $title = "June";
                    }elseif($i == 7){
                        $title = "July";
                    }elseif($i == 8){
                        $title = "August";
                    }elseif($i == 9){
                        $title = "September";
                    }elseif($i == 10){
                        $title = "October";
                    }elseif($i == 11){
                        $title = "November";
                    }elseif($i == 12){
                        $title = "December";
                    }

                    //path to months directories
                    $url=$userPath.'/'.$i;

                    $newUrl = $url.'/'.$files[2];

                    print $newUrl;

                    //check if directory exists
                    if(is_dir($url)){

                        //assign open state to $dir
                        $dir = opendir($url);

                        //add all files to $files[] array
                        while (($file = readdir($dir)) !== false){

                            $files[] = $file;

                        }
                        closedir($dir);

                        //display link to payslips
                        print "
";
                        print "
".$title."
";
                        print "Download";
                        print "
";

                    }

                }

        }

        ?>

Very messy I know, I am sure there is a better way to do this just not sure how.


texts:
As part of a solution I have the following class createCSV. It is working as expected but I'm very much aware of my lack of experience with c# and OO programming: are there any obvious potential problems or simple refactors?

(note: the use of a guid is a user requirement)

using System.Text;
using System.IO;
using System.Data;
using System;
using System.Collections.Generic;

namespace createCSV
{
  class Csv
  {

    private string guid;

    public Csv(string aGuid)
    {
      guid = aGuid;
    }

    public void CreateCSV(DataTable dt,string aDestPath, string aTitle)
    {

      string filePath = string.Concat(aDestPath, aTitle, @"-", this.guid, @".csv");
      string delimiter = ",";

      StringBuilder sb = new StringBuilder();
      List<string> CsvRow = new List<string>();

      //write headers
      foreach(DataColumn c in dt.Columns)
      {
        CsvRow.Add(c.ColumnName.ToString());
      }
      sb.AppendLine(string.Join(delimiter,CsvRow));

      //write data
      foreach(DataRow r in dt.Rows)
      {
        CsvRow.Clear();

        //go through each column adding to a list of strings
        foreach(DataColumn c in dt.Columns)
        {
          CsvRow.Add(r[c.ColumnName].ToString());
        }

        sb.AppendLine(string.Join(delimiter,CsvRow));
      }

      File.WriteAllText(filePath,sb.ToString());

      Console.WriteLine();
      Console.WriteLine(String.Concat(@"just completed: ",aTitle,@"-",this.guid,@".csv"));
    }

  }
}


texts: Class that represents starting points and endpoints of a game

texts:
I am creating my first HTML5 game using JavaScript and Phaser framework. I have a class (or more accurately a prototype) called MajorPoint that represents the starting point and the end point of the game. I initially put those two together, as they only differed from each other by the visible frame. Now as the game is more fleshed out though, the endpoint has got a few more rules that aren't needed by the starting point.

Should I now split this into two? I'm not sure what to do with it, because if I split this into two (StartPoint and EndPoint), those two prototypes would have a lot (relatively speaking) of identical code between each other. On the other hand, now there is almost as much code that is only needed by half of the objects.

The objects will not change their state during the game, so they stay as they are created the whole time they exist.

var MajorPoint = function(game, x, y, state, callback, callbackContext) {
  Phaser.Sprite.call(this, game, x, y, 'start-end', 0);
  this.state = state;
  this.anchor.setTo(0.5, 0.7);
  this.scale.setTo(0.5, 0.5);

  //If state is 'end' but end is not reachable, hides this object.
  //If state is 'end' and end is reachable, enables input for this object.
  if (state === 'end') {
    this.frame = 1;
    if (!game.data.isEndReachable()) {
      this.visible = false;
    } else {
      this.inputEnabled = true;
      if (callback !== undefined) {
        this.events.onInputDown.add(callback, callbackContext);
      }
    }
  }
};

MajorPoint.prototype = Object.create(Phaser.Sprite.prototype);
MajorPoint.prototype.constructor = MajorPoint;


texts: Binary Search recursive & iterative solution

texts:
I have implemented binary search solution by using recursion and iterative approach.
I there any way to improve it?
Tests
package test;

import main.algorithms.BinarySearchDemo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class BinarySearchTest {

    BinarySearchDemo binarySearchDemo;
    int[] array;

    @Before
    public void setUp(){
        binarySearchDemo = new BinarySearchDemo();
        array = new int[]{2, 3, 5, 6, 9, 11, 12, 15, 17, 21};
    }

    @Test
    public void testBinarySearchJavaAPI(){
        Assert.assertEquals(2, binarySearchDemo.binarySearchJavaAPI(5,array));
    }

    @Test
    public void testBinarySearchImpl(){
        Assert.assertEquals(2, binarySearchDemo.binarySearchImpl(5,array));
    }

}

Implementation
package main;

public class BinarySearch {

    private static boolean binarySearchRecursive(int[] array, int i) {

        return binarySearchRecursive(array,0,array.length-1,i);
    }

    private static boolean binarySearchRecursive(int[] array, int left, int right, int item) {

        if(left > right){
            return false;
        }
        int pivot =  (right - left) / 2 + left;

        if(item == array[pivot]){
            return true;
        }
        else if ( item < array[pivot] ){
            return binarySearchRecursive(array, left,pivot-1,item);
        }else {
            return binarySearchRecursive(array, pivot+1, right, item);
        }
    }

    private static boolean binarySearchIterative(int[] array, int item) {

        int left = 0;
        int right = array.length - 1 ;

        while (left < right) {
            int mid = (left + right)/2 + left;
            if (array[mid] == item) {
                return true;
            } else if(item < array[mid]) {
                right = mid-1;
            } else {
                left = mid + 1;
            }
        }
        return false;
    }

}


texts:
Here's my function that creates a bitmap file from an array of pixels. It can write a bitmap both with transparency and without transparency. Please review my code and give constructive criticism on how to increase the overall quality of it. :)

typedef unsigned char BYTE;

inline int bmpEncoder(const std::string &location,
    const unsigned __int32 &width, const unsigned __int32 &height,
    const std::vector<BYTE> &buffer,
    const bool &hasAlphaChannel = true) {

    std::ofstream fout(location, std::ios::out | std::ios::binary);

    if (fout.fail()) {
        return 0;
    }

    //Padding
    const unsigned __int8 padding = hasAlphaChannel ? 0 : (4 - (width * 3) % 4) % 4;

    //Bitmap file header.
    const char signature[2] = { 'B', 'M' };
    const unsigned __int32 fileSize = buffer.size() * sizeof(BYTE) + padding * (height - 1) + 14 + 124;
    const unsigned __int32 offset = 14 + 124;

    //Bitmap information header file
    const unsigned __int32 DIBSize = 124;
    const __int32 bitmapWidth = width;
    const __int32 bitmapHeight = height;
    const unsigned __int16 numPlanes = 1;
    const unsigned __int16 bitsPerPixel = (hasAlphaChannel) ? 32 : 24;
    const unsigned __int32 compressionMethod = (hasAlphaChannel) ? 3 : 0; //BI_RGB = 0, BI_BITFIELDS = 3
    const unsigned __int32 bitmapSize = buffer.size() * sizeof(BYTE);
    const __int32 horizontalResolution = 2834;
    const __int32 verticalResolution = 2834;
    const unsigned __int32 numColors = 0;
    const unsigned __int32 impColorCount = 0;
    const unsigned __int32 redBitmask = (hasAlphaChannel) ? 0x0000FF00 : 0; //ARGB32 pixel format
    const unsigned __int32 greenBitmask = (hasAlphaChannel) ? 0x00FF0000 : 0;
    const unsigned __int32 blueBitmask = (hasAlphaChannel) ? 0xFF000000 : 0;
    const unsigned __int32 alphaBitmask = (hasAlphaChannel) ? 0x000000FF : 0;

    //Writing the file header and information header to the file
    std::vector<BYTE> header(offset, 0);
    header[0] = signature[0];
    header[1] = signature[1];

#define HEADERS(i, variableName)    header[i] = variableName; header[i+1] = variableName >> 8; header[i+2] = variableName >> 16; header[i+3] = variableName >> 24;

    HEADERS(2, fileSize);
    HEADERS(6, 0);
    HEADERS(10, offset);
    HEADERS(14, DIBSize);
    HEADERS(18, bitmapWidth);
    HEADERS(22, bitmapHeight);

    header[26] = (BYTE)numPlanes;
    header[27] = (BYTE)(numPlanes >> 8);
    header[28] = (BYTE)bitsPerPixel;
    header[29] = (BYTE)(bitsPerPixel >> 8);

    HEADERS(30, compressionMethod);
    HEADERS(34, bitmapSize);
    HEADERS(38, horizontalResolution);
    HEADERS(42, verticalResolution);
    HEADERS(46, numColors);
    HEADERS(50, impColorCount);
    HEADERS(54, redBitmask);
    HEADERS(58, greenBitmask);
    HEADERS(62, blueBitmask);
    HEADERS(66, alphaBitmask);

#undef HEADERS

    fout.write((char *)header.data(), sizeof(BYTE) * header.size());

    //Writing the pixel array
    const unsigned __int32 bWidth = bitsPerPixel / 8 * width;

    for (int i = height - 1; i >= 0; i--) {
        std::vector<BYTE> row(buffer.begin() + i * bWidth, buffer.begin() + i * bWidth + bWidth);
        fout.write((char *)row.data(), row.size() * sizeof(BYTE));
        fout.seekp(padding * sizeof(BYTE), std::ios::cur);
    }

    fout.close();
    return 1;
}


texts:
I'm just starting to learn CoffeeScript and am trying to work through simple examples, this one being Prim's algorithm. I'd like feedback on everything but especially on making this script take advantage of the features of CoffeeScript most effectively.

nodes_dir = {
0 : [1],
1 : [0, 2, 3, 5],
2 : [1, 4],
3 : [1, 4, 5],
4 : [2, 3],
5: [1, 3]
}

edges_dir = {
0: {1:6}
1: {2:1, 3: 2, 5:0, 0:6},
2: {1:1, 4:4},
3: {1:2, 4:5, 5:3},
4:{2:4, 3:5},
5:{3:3, 1:0},
}

MAX_WEIGHT = 10000
NUM_NODES = 6
EDGE_WEIGHTS = [99, 2, 2, 1, 1, 5, 10]

get_min_key_value = (obj) ->
    if Object.keys(obj).length < 1
        return [-1, -1]
    min_k = MAX_WEIGHT
    min_v = MAX_WEIGHT
    for k, v of obj
        if v < min_v
          min_v = v
          min_k = k
    delete obj[min_k]
    [min_k, min_v]

# Prims algorithm as implemented in Skiena p 195
prim = (nodes_dir, edges_dir) ->
   # record-keeping arrays
   intree = []
   distance = []
   link = []
   parent = []

   # set default values for record-keeping arrays
   for i in [1..NUM_NODES]
       intree.push -1
       distance.push MAX_WEIGHT
       link.push -1
       parent.push -1

   links = []
   link_add = -1
   current_node = 0

   while intree[current_node] < 0
      # add new node and new edge to record of edges/nodes
      intree[current_node] = 1
      links.push link[current_node] if link[current_node] > 0

      # update any distances to tree that have become shorter with addition of new node
      p = edges_dir[current_node]
      for k,v of p
          weight = EDGE_WEIGHTS[v]
          if distance[k] > weight and intree[k] < 0
              distance[k] = weight
              link[k] = v
              parent[k] = current_node

      # determine which node is now closest to tree and add it
      dist = MAX_WEIGHT
      for i in [0..NUM_NODES-1]
          if intree[i] < 0 and dist > distance[i]
              dist = distance[i]
              current_node = i
              link_add = link[i]

   links

f = prim(nodes_dir, edges_dir)
alert f


texts:
I'm working with an API which gives me 19-digit ID numbers, formatted in blocks of four except for the last 3 digits. While I tried a for loop, I thought it would be most efficient to simply use a StringBuilder and substrings as the length of the ID will never change (documentation is omitted for privacy reasons):

public String getFormattedId() {
    return new StringBuilder()
            .append(id.substring(0, 4))
            .append(" ")
            .append(id.substring(4, 8))
            .append(" ")
            .append(id.substring(8, 12))
            .append(" ")
            .append(id.substring(12, 16))
            .append(" ")
            .append(id.substring(16, 19))
            .toString();
}

This transforms IDs like 1234567890000000123 into the more readable 1234 5678 9000 0000 123, which is also the format used throughout the documentation and website.

I should mention I come from a C# background, and I've heard Java's string + operator is just syntactic sugar for the StringBuilder method like I'm using here.


texts:
I am trying to Bruteforce a PCP that is supposed to be up to the length 300.

I wrote a little Python program that is doing just that but it could take forever until my program finds the right PCP.

import sys

x1 = "aba"
x2 = "a"
x3 = "bab"
y1 = "a"
y2 = "ab"
y3 = "abaa"

def ternary(n):
    if n == 0:
        return ''
    else:
        e = n//3
        q = n%3
        return ternary(e) + str(q)

x = 1;

while True:
    ter = ternary(x)
    ter = ("%01d" % (float(ter),))
    #print("ter = " + str(ter))
    wordx = ""
    wordy = ""
    for i in range(0, len(str(ter))):
        if(str(ter)[i] == '0'):
            wordx = wordx + x1
        if(str(ter)[i] == '1'):
            wordx = wordx + x2
        if(str(ter)[i] == '2'):
            wordx = wordx + x3
    for j in range(0, len(str(ter))):
        if(str(ter)[j] == '0'):
            wordy = wordy + y1
        if(str(ter)[j] == '1'):
            wordy = wordy + y2
        if(str(ter)[j] == '2'):
            wordy = wordy + y3

    print(ter)

    if wordx == wordy:
        print("Wordx = " + wordx + " and wordy = " + wordy + " and the decimal number is = " + str(x) + " and the ternary number is = " + str(ter))
        sys.exit("Yes!")
    x+=1

Useful Information about PCP's: https://en.wikipedia.org/wiki/Post_correspondence_problem


texts: Project Euler #14 in Clojure (finding long Collatz sequence chain)

texts:
I'm working on a Clojure implementation for Project Euler #14, which asks for the initial element, under 106, that produces the longest collatz-sequence chain.  I'm trying to make use of every optimization I know of, including transients and loop/recur. My code is based on a Lua implementation I wrote which runs in a fraction of a second. My strategy is to record all previously calculated Collatz lengths in a structure, so that I never calculate the same length more than once.

The structure I use is based on a Lua table, with a fixed-length array portion (a transient vector) and a growing dictionary portion (a transient map). Since the table will store lengths (of Collatz chains), I've called it an "ltable". The code to define the structure and its basic operations is:

(def upto 1000000)

(defn ltable-new []
  (transient {:under (transient (into [] (conj (repeat (- upto 2) nil) 1 1)))
              :over (transient {})}))

(defn ltable-contains [b n]
  (let [coll (if (< n upto)
               (b :under)
               (b :over))]
    (coll n)))

(defn ltable-insert! [b n val]
  (let [coll (if (< n upto)
               :under
               :over)]
    (assoc! b coll (assoc! (b coll) n val))))

ltable-new creates a new ltable with the vector initialized with nil values up to the desired length. ltable-contains and ltable-insert! both ensure that any value I provide will be checked for in the correct part of the ltable.

I also need to define a function to get the next Collatz value. It's simply:

(defn nxt-collatz [n] (if (even? n) (quot n 2) (inc (* 3 n))))

To build the ltable for a given value, I use the following code:

(defn ltable-mass-insert! [orig-table orig-lis counter]
  (loop [ltable orig-table lis orig-lis c counter]
    (if (empty? lis)
      ltable
      (let [cur (first lis)
            others (rest lis)]
        (recur (ltable-insert! ltable cur c) others (inc c))))))

(defn iterative-ltable-build! [init-value ltable]
  (loop [cur init-value acc '()]
    (let [nxt (nxt-collatz cur)]
      (if-let [colz-count (ltable-contains ltable nxt)]
        (ltable-mass-insert! (ltable-insert! ltable cur (inc colz-count)) acc (+ colz-count 2))
        (recur nxt (conj acc cur))))))

iterative-ltable-build! takes an initial value and an ltable, and populates the ltable at init-value with the Collatz chain length of that value. It also populates any necessary values that come from calculating the initial value. For example, (iterative-ltable-build! 3 (ltable-new)) will populate the entries for 2, 3, 4, 5, 8, 10, and 16.

To do this iteratively, instead of recursively, I build up a list of uncalculated values. When I encounter a known chain length, I stop iterating and instead insert the chain length (incremented for each member of the list) into each location in the list. This is what ltable-mass-insert! does.

To populate all the values, and to return only the ones below my limit (upto), I use this code:

(defn build-length-ltable []
  (loop [cur 2
         ltable (ltable-new)]
    (if (>= cur upto)
      (persistent! (ltable :under))
      (recur (inc cur) (iterative-ltable-build! cur ltable)))))

This calls iterative-ltable-build! with successive values from 2 to upto, using the same transient ltable throughout. When it's done, I return only the values under upto as a persisted vector.

Finally, to get the value with the longest chain length:

(defn e014 []
  (let [lt (build-length-ltable)
        to-consider (map (fn [a b] [a b]) (range) lt)]
    (first (reduce #(if (< (second %1) (second %2)) %2 %1) to-consider))))

I map the index position to each value, so that a vector of [1 2 8 3 6] becomes [[1 1] [2 2] [3 8] [4 3] [5 6]]. I reduce the collection to the element with the largest length, and return the first value.

When I run it, I usually get a result of 1.5 to 2 seconds.

euler.e014> (time (do (e014) "HIDE THE ANSWER"))
"Elapsed time: 1572.566466 msecs"
"HIDE THE ANSWER"

In Lua, I get a run time below half of a second. How can I improve the run time of this function?


texts: Python web crawler counting words in all pages in a domain

texts:
Here is a simple web crawler I wrote in Python 3 that counts the words in each page in a domain, displays word count per page, and sums them up.

Tested on a multitude of web pages, works correctly so far.

What do you think of my code?

import requests
from urllib.request import urlopen
from bs4 import BeautifulSoup

base_url = "https://independencerpgs.com/"
html = urlopen(base_url)
bsObj = BeautifulSoup(html.read(), features="html.parser");

urls=[]
for link in bsObj.find_all('a'):
    if link.get('href') not in urls:
        urls.append(link.get('href'))
    else:
        pass
print(urls)

words=0
for url in urls:
    if url not in ["NULL", "_blank", "None", None, "NoneType"]:
        if url[0] == "/":
            url=url[1:]
        if base_url in url:
            if base_url == url:
                pass
            if base_url != url and "https://"in url:
                url=url[len(base_url)-1:]
        if "http://" in url:
            specific_url=url
        elif "https://" in url:
            specific_url = url
        else:
            specific_url = base_url + url
        r = requests.get(specific_url)
        soup = BeautifulSoup(r.text, features="html.parser")
        for script in soup(["script", "style"]):
            script.extract()
        text = soup.get_text()
        lines = (line.strip() for line in text.splitlines())
        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
        text = '\n'.join(chunk for chunk in chunks if chunk)
        text_list = text.split()
        print(f"{specific_url}: {len(text_list)} words")
        words += len(text_list)
    else:
        pass
print(f"Total: {words} words")