texts:
I have been looking for an algorithm for splitting a file into smaller pieces, which satisfy the following requirements:

The first line in the original file is a header, this header must be carried over to the resulting files
The ability to specify the approximate size to split off, for example, I want to split a file to blocks of about 200,000 characters in size.
File must be splitted at line boundaries

More info:

This is part of my web service: the user uploads a CSV file, the web service will see this CSV is a chunk of data--it does not know of any file, just the contents.
The web service then breaks the chunk of data up into several smaller pieces, each will the header (first line of the chunk). It then schedules a task for each piece of data. I don't want to process the whole chunk of data since it might take a few minutes to process all of it. I want to process them in smaller size. This is why I need to split my data.
The final code will not deal with open file for reading nor writing. I only do that to test out the code.
The task to process smaller pieces of data will deal with CSV via csv.DictReader. It does not make sense to use the csv module to break up the original chunk of data into pieces. I have done some timing and my algorithm achieves better performance as opposed to reading/writing line-by-line just to break data into pieces.

Here is an example:

If my original file is:

Header
line1
line2
line3
line4

If I want my approximate block size of 8 characters, then the above will be splitted as followed:

File1:

Header
line1
line2

File2:

Header
line3
line4

In the example above, if I start counting from the beginning of line1 (yes, I want to exclude the header from the counting), then the first file should be:

Header
line1
li

But, since I want the splitting done at line boundary, I included the rest of line2 in File1.

Here is what I have so far. I am looking to turn this code segment into a procedure, but more importantly, I want the code to speed up a bit. Currently, it takes about 1 second to finish. In the final solution, In addition, I am going to do the following:

Change the procedure to return a generator, which returns blocks of data. I don't really need to write them into files. I think I know how to do this, but any comment or suggestion is welcome.
Since my data is in Unicode (Vietnamese text), I have to deal with .encode(), .decode(). Any hint to speed this up would be great.

with open('data.csv') as f:
    buf = f.read().decode('utf-8')

header, chunk = buf.split('\n', 1)

block_size = 200000
block_start = 0
counter = 0
while True:
    counter += 1
    filename = 'part_%03d.txt' % counter
    block_end = chunk.find('\n', block_start + block_size)
    print filename, block_start, block_end

    with open(filename, 'w') as f:
        f.write(header + '\n')
        if block_end == -1:
            f.write(chunk[block_start:].encode('utf-8'))
        else:
            f.write(chunk[block_start:block_end].encode('utf-8'))
        f.write('\n')

    block_start = block_end + 1
    if block_end == -1: break


texts:
I'm drowning in Swift optionals and error handling syntax. I'm just converting a text file into an array of Strings. One would think that this could be a simple two or three liner but by the time I got it to work, I ended up with the following mess:

enum ImportError: ErrorType {
    case FileNotFound
    case CouldntGetArray
}

private func getLineArrayFromFile(fileName: String) throws -> Array<String> {

    let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)
    if path == nil {
        throw ImportError.FileNotFound
    }

    var lineArray: Array<String>?
    do {

        let content = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
        lineArray = content.componentsSeparatedByString("\n")

    }catch{
        throw ImportError.CouldntGetArray
    }

    return lineArray!
}

I actually don't really care about the using ErrorType enum, but I wanted to play around with the new Swift Error Handling syntax.

I thought I understood optionals before, but they were giving me a headache when combined with the do-try-catch statement. I also didn't know if I should return an Array or an Optional Array.

What are the best practices for a situation like this?

Error handling
Treatment of optionals
Code brevity/readability


texts:
I'm trying to create passwords using the following snippet to match a custom password policy. I've added three gtr statements, at the end of the string, to guarantee my password policy is met.

foo=$(gtr -dc 'a-zA-Z0-9' < /dev/urandom | head -c 96;
gtr -dc 'A-Z' < /dev/urandom | head -c 1;
gtr -dc 'a-z' < /dev/urandom | head -c 1;
gtr -dc '0-9' < /dev/urandom | head -c 1);
echo $foo

Could this code be simplified?


texts:
I've written a circular buffer with multithreaded write and single read ability:

public class RingBuffer<E> extends AbstractList<E> implements RandomAccess {

    class Pointer {
        int p = 0;

        public int getPointer(){
            return this.p;
        }

        public void increasePointer(int p) {
            this.p = p;
        }
    }

    private final int n;
    private final List<E> rb;

    private int size = 0;
    private Pointer ptr_w = new Pointer();
    private Pointer ptr_r = new Pointer();

    public RingBuffer(int n) {
        this.n = n + 1;
        this.rb = new ArrayList<E>(Collections.nCopies(this.n, (E) null));
    }

    public int size() {
        return this.size;
    }

    private int wrap(int i) {
        int m = i % this.n;
        return (m < 0) ? m += this.n : m;
    }

    @Override
    public E get(int i) {
        return (this.size == 0) ? null : this.rb.get(i);
    }

    @Override
    public E remove(int i) {
        E e = this.get(this.ptr_r.getPointer());
        if(e != null) {
            this.rb.set(this.ptr_r.getPointer(), null);
            setPointer(false, this.ptr_r);
        }
        System.out.println("Read: " + this.ptr_r.getPointer() + " " + size());
        return e;
    }

    @Override
    public synchronized boolean add(E e) {
        if (size() == this.n - 1)
            throw new IllegalStateException("Cannot add element. Ringbuffer is filled.");
        this.rb.set(this.ptr_w.getPointer(), e);
        setPointer(true, this.ptr_w);
        System.out.println("Write: " + this.ptr_w.getPointer() + " " + size());
        return true;
    }

    private synchronized void setPointer(boolean a, Pointer ptr) {
        this.size = (a) ? this.size + 1 : this.size - 1;
        ptr.increasePointer(wrap(ptr.getPointer() + 1));
    }
}

I would like to know what I could improve and what you think about the code. I'm new to multithreading and would love to get some feedback.


texts: Error-handling #ifdefs for AFNetworking requests

texts:
I am using AFNetworking 1.4.3 to send and receive network messages in iOS. My application works slightly differently in DEBUG and RELEASE mode, so I need to use #ifdef clauses. How can I simplify the following fragments without making these macros:

#ifdef DEBUG
        if (failure) failure([NSError fromDict:responseObject]);
#else
        if (failure) failure([NSError networkError]);
#endif

#ifdef DEBUG
        if (failure) failure(error);
#else
        if (failure) failure([NSError networkError]);
#endif

Whole code:

@implementation ELHTTPClient

- (instancetype)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self) {
        __weak ELHTTPClient *weakSelf = self;
        [self setParameterEncoding:AFJSONParameterEncoding];
        [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
        [self setDefaultHeader:@"Accept" value:@"application/json"];
        [self setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            [weakSelf.delegate httpClient:weakSelf connectionStateChanged:status];
        }];
    }
    return self;
}

- (void)myPostPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(NSDictionary *))success failure:(ELErrorBlock)failure {
    [self postPath:path parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isResponseValid]) {
            if (success) success(responseObject);
        }
        else {
#ifdef DEBUG
            if (failure) failure([NSError fromDict:responseObject]);
#else
            if (failure) failure([NSError networkError]);
#endif
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [self.delegate httpClient:self networkError:error];
//        NSLog(@"Network error. Operation: %@, \n Error: %@", operation, error);
#ifdef DEBUG
        if (failure) failure(error);
#else
        if (failure) failure([NSError networkError]);
#endif
    }];
}

- (void)myGetPath:(NSString *)path parameters:(NSDictionary *)parameters
          success:(void (^)(NSDictionary *dict))success
          failure:(ELErrorBlock)failure {
    [self getPath:path parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isResponseValid]) {
            if (success) success(responseObject);
        }
        else {
#ifdef DEBUG
            if (failure) failure([NSError fromDict:responseObject]);
#else
            if (failure) failure([NSError networkError]);
#endif
//            NSError *error = [self.serializer errorFromDictionary:responseObject];
//            [self.delegate httpClient:self requestFailedError:error];
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
#ifdef DEBUG
        if (failure) failure(error);
#else
        if (failure) failure([NSError networkError]);
#endif
    }];
}

@end

My implementation of NSError category:

@implementation NSError (My)

+ (NSError *)networkError {
    NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] init];
    [userInfo setValue:@"Some problems with connection to network. Please try again later." forKey:NSLocalizedDescriptionKey];//FIXME: add localized string.
    return [NSError errorWithDomain:@"Connection error" code:1024 userInfo:userInfo];
}

+ (NSError *)fromDict:(NSDictionary *)dict {
    NSString *errorDesc = dict[@"description"];
    errorDesc = errorDesc ? : [NSString stringWithFormat:@"Dictionary: \n%@", dict];
    NSMutableDictionary* details = [NSMutableDictionary dictionary];
    details[NSLocalizedDescriptionKey] = errorDesc;
    NSNumber *errorCodeNum = dict[@"errorCode"];
    return [NSError errorWithDomain:@"world" code:[errorCodeNum intValue] userInfo:details];
}
@end


texts: Schema.org structure for a news aggregator individual post

texts:
I'm building a news aggregator website. This is my current schema structure for a single news article. There can be more than one article per page. I'm trying to have every possible piece of data structured. Am I missing something? How can this structure be schema.org-optimized for a news article post?

    <meta itemprop="inLanguage" content="es-419" />
    <meta itemprop="dateModified" content="2015-03-02T19:03Z" />
    <meta itemprop="keywords" content="correa, obama, whitehouse" />
    <meta itemprop="commentCount" content="41" />
    <meta itemprop="description" content="Excerpt of the news text goes here..." />
    <meta itemprop="isBasedOnUrl" content="http://eluniverso.com/2015/03/01/noticia3.html" />

        Headline goes here

    <time datetime="2015-03-02T17:43Z" itemprop="datePublished">Mar 2</time>

Complete article goes here. Two or three lines perhaps. Maybe more.

    politics
    67

        <meta itemprop="bestRating" content="5">
        <meta itemprop="worstRating" content="1">
        4.1/5 based on 249 votes

        <meta itemprop="logo" content="/logos/eluniverso.png" />

            El Universo

Related News 1

Related News 2

Related News 3


texts:
What do you think of this way to generate a random number from the total rows in a table? I would like to create a page that random.php precisely generates a random ID and shows it.

require 'includes/config.php';

$pdo->query('SELECT id FROM xxxx');
$pdo->resultset();
$total = $pdo->rowCount();

//echo random id
$id = rand(1, $total);

$pdo->query('SELECT * FROM xxxxx WHERE id = :id AND status = :status');
$pdo->bind(':id', $id);
$pdo->bind(':status', 1);
$rand = $pdo->single();

echo $rand['id'];


texts:
My code is for a 10-faced dice-rolling game. There are 2 players who start off with 50 points, then they both roll a dice and get a random score between 1-10. The player with the highest roll gets the difference between the rolls deducted from their score (50 points), but the loser gets the difference between the rolls added to their score. To win the game you must reach the score 0, or below.

#Imported to help flow, and random to simulate dice rolls

print("Welcome to the dice rolling game.")
#Printed to make it more friendly to the user :)
time.sleep(1)

playernames=[]
#Add player's names to a list
playernames.append(input("\nWhat is player 1's name?"))#.append is used to add multiple names to list
playernames.append(input("\nWhat is player 2's name?"))
time.sleep(1)
#Prints players names from the list

print("\nPlayer 1:",playernames[0])
print("Player 2:",playernames[1])
input("\nPress enter to begin: ")

dicelist=[0,0]

dicelist[0]=random.randint(1,10)
dicelist[1]=random.randint(1,10)

for i in range(0,2):
    print(playernames[i],"rolls a",dicelist[i])
diceDifference=abs(dicelist[0]-dicelist[1])

score0=20
score1=20
while True:
    if dicelist[0]>dicelist[1]:
            print("\nPlayer 1 wins")
            time.sleep(1)
            print("\nPlayer 2 loses",diceDifference,"points")
            print("Player 2 gains",diceDifference,"points")

            print("player 1:",score0-diceDifference)
            print("player 2:",score1+diceDifference)
score0==0
exit

elif dicelist[1]>dicelist[2]:
print("\nPlayer 2 wins")
time.sleep(1)
print("\nPlayer 2 loses",diceDifference,"points")
print("\nPlayer 1 gains",diceDifference,"points")
print("player 1:",score0+diceDifference)
print("player 2:",score1-diceDifference)
score1==0
exit

else:
print("It's a draw")
time.sleep(1)
print("No change in score")

print("The score is: ","\nPlayer 1:",score0,"\nPlayer 2:",score1)
time.sleep(1)


texts:
Previous question: BaseRepository for EF6

I've update my code.  Is it correct now?  I've changed IEnumerable to IQueryable.

public interface IRepository<T> : IDisposable
{
    T Get(Expression<Func<T, bool>> predicate);
    IQueryable<T> GetWhere(Expression<Func<T, bool>> predicate = null);
    void Add(T entity);
    void Delete(T entity);
    void DeleteWhere(Expression<Func<T, bool>> predicate);
    void Update(T entity);
    void Save();
}

public class BaseRepository<T> : IRepository<T> where T : class
{
    private readonly DbContext _dbContext;

    public BaseRepository(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public T Get(Expression<Func<T, bool>> predicate)
    {
        return GetWhere(predicate).FirstOrDefault();
    }

    public IQueryable<T> GetWhere(Expression<Func<T, bool>> predicate = null)
    {
        IQueryable<T> result = _dbContext.Set<T>();
        return (predicate == null) ? result : Queryable.Where<T>(result, predicate);
    }

    public void Add(T entity)
    {
        _dbContext.Entry(entity).State = EntityState.Added;
    }

    public void Delete(T entity)
    {
        _dbContext.Entry(entity).State = EntityState.Deleted;
    }

    public void DeleteWhere(Expression<Func<T, bool>> predicate)
    {
        IQueryable<T> entities = GetWhere(predicate);
        foreach (T entity in entities)
            Delete(entity);
    }

    public void Update(T entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;
    }

    public void Save()
    {
        _dbContext.SaveChanges();
    }

    public async void SaveAsync()
    {
        await _dbContext.SaveChangesAsync();
    }

    public void Dispose()
    {
        if (_dbContext != null)
            _dbContext.Dispose();
    }
}


texts: A function that replicates DLookup, and can use parameterized queries

texts:
This function was built to replace DLookup so that i could pass in parameterized queries for a speed increase. I also wanted a simple way to get more than one value if needed. For example, if i want 4 or 5 fields out of a particular record or maybe 4 or 5 records with only one field, I could get that with this function.

EDIT: the whole filter string portion of the fuction is legacy functionality from when i initially built this function and had to leave in untill all of the places that use this piece of code have been updated.

Public Function Qlookup(ByVal argQuery As String, Optional ByRef argParameters As Variant = Null, Optional ByVal argIsFilterString As Boolean = False) As Variant
    'Parameters -
    'argQuery: the query definition name
    'argParameters: the list of parameters (can come in an array or not) that should be in the order and starting at 0
    'argIsFilterString: Allows you to use a 'Where' Clause instead of a parameter list
    'that the parameters in your query are.
    'Output -
    'Will output a single item, 1d array or 2d array depending on the query you feed it.
    'This comment line is here to fix the formatting messing up.
    If Not BasicInclude.DebugMode Then On Error GoTo Error_Handler
    Dim rs As DAO.Recordset
    Dim qry As QueryDef
    Dim u As Long
    Dim out() As Variant
    Dim i As Long
    Dim j As Long
    Qlookup = Null
    Set qry = dbLocal.QueryDefs(argQuery)
    If argIsFilterString Then
        Set rs = qry.OpenRecordset(dbOpenSnapshot)
        rs.filter = argParameters
        Set rs = rs.OpenRecordset(dbOpenSnapshot)
    Else
        If IsArray(argParameters) Then
            u = UBound(argParameters)
            If u = (qry.Parameters.count - 1) Then
                For i = 0 To u
                    qry.Parameters(i).value = argParameters(i)
                Next i
            Else
                Err.Raise vbObjectError, "Qlookup", "Number of Parameters in query(" & qry.Parameters.count & ") do not match the number of parameters passed in(" & u + 1 & ")"
            End If
        Else
            If Not (IsNull(argParameters)) And qry.Parameters.count = 1 Then
                qry.Parameters(0).value = argParameters
            ElseIf qry.Parameters.count = 0 And Not (IsNull(argParameters)) Then
                Err.Raise vbObjectError + 1, "Qlookup", "Number of Parameters in query(" & qry.Parameters.count & ") do not match the number of parameters passed in(1)"
            ElseIf qry.Parameters.count = 0 And (IsNull(argParameters)) Then
            End If
        End If
        Set rs = qry.OpenRecordset(dbOpenSnapshot)
    End If
    If rs.RecordCount Then
        rs.MoveFirst
        rs.MoveLast
        rs.MoveFirst
        If rs.RecordCount > 1 Then
            If rs.Fields.count > 1 Then
                ReDim out(rs.RecordCount - 1, rs.Fields.count - 1)
                For i = 0 To rs.RecordCount - 1
                    For j = 0 To rs.Fields.count - 1
                        out(i, j) = rs.Fields(j).value
                    Next
                    rs.MoveNext
                Next
            Else
                ReDim out(rs.RecordCount - 1)
                For i = 0 To rs.RecordCount - 1
                    out(i) = rs.Fields(0).value
                    rs.MoveNext
                Next
            End If
            Qlookup = out
        Else
            If rs.Fields.count > 1 Then
                ReDim out(rs.RecordCount - 1, rs.Fields.count - 1)
                For i = 0 To rs.RecordCount - 1
                    For j = 0 To rs.Fields.count - 1
                        out(i, j) = rs.Fields(j).value
                    Next
                    rs.MoveNext
                Next
                Qlookup = out
            Else
                Qlookup = rs.Fields(0).value
            End If
        End If
    End If
Error_Exit:
    Set rs = Nothing
    Set qry = Nothing
    Exit Function
Error_Handler:
    StandardErrorBox "Qlookup", Err, Errors
    Qlookup = Null
    Resume Error_Exit
End Function


texts: PHP form validation for name, email, and Twitter handle

texts:
Given the following input values from a form, create a method or
  methods to validate the input based on their requirements. Throw an
  exception if any data is invalid.

  1.1 name: is required
  1.2 must be first name AND last name

  2.1 email is required
  2.2 is a valid email address

  3.1 twitter is optional
  3.2 is a Twitter handle

  The input data will be in the following format:

$input = [
    'name' => '...',
    'email' => '...',
    'twitter' => '...'
];

This is the code snippet I worked on. How can I improve my code?  I am not allowed to include or use any other files.

<!DOCTYPE html>

    <title>PHP Form Validation</title>

<?php

$name = '';
$email = '';
$twitter = '';
$nameError ="";
$emailError ="";
$twitterError ="";

class dataException extends Exception
{
      public function errorMessage()
      {
        $message = $this->getMessage();
        return $message;
      }
}

try
{
    if(isset($_POST['submit']))
    {
        if (empty($_POST["name"]) && empty($_POST["email"]))
        {
            throw new dataException('Name and Email are required');
        }
        if (empty($_POST["name"]))
        {
            throw new dataException('Name is required');
        }
        else
        {
            $name = test_input($_POST["name"]);
            // check name only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z ]*$/",$name))
            {
                throw new dataException('Only letters and white space allowed');
            }
            else
            {
                if(str_word_count($name)!=2)
                {
                     throw new dataException('FirstName and LastName is required');
                }
            }
        }
        if (empty($_POST["email"]))
        {
            throw new dataException('Email is required');
        }
        else
        {
            $email = test_input($_POST["email"]);
            // check if e-mail address syntax is valid or not
            if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
            {
                throw new dataException('Email is invalid');
            }
        }
        //checked vs internet.
        $twitter = test_input($_POST['twitter']);
        if (!isset($_POST['twitter']) || $_POST['twitter'] === '')
        {
            $twitter = '';
        }
        else
        {
            if (!preg_match('/^(\@)?[A-Za-z0-9_]+$/', $twitter))
            {
                throw new dataException('Invalid twitter handle');
            }
        }
    }
}
catch (dataException $e)
{
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
//php code ends here
?>

<form action="" method="post">
Name (FirstName and LastName):
<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>">
* <?php echo $nameError;?>

E-mail:
<input type="text" name="email" value="<?php echo htmlspecialchars($email);?>">
* <?php echo $emailError;?>

Twitter:
<input type="text" name="twitter" value="<?php echo htmlspecialchars($twitter);?>">
 <?php echo $twitterError;?>

<input type="submit" name="submit" type="submit" value="Submit">
</form>


texts: Removing punctuation and lowercasing a string

texts:
I am very fresh to python. As part of an assignment, I've written the following code to remove punctuation from a string and convert it to lowercase.

import string

words = "Dave, Laura, Maddy, Dave, Laura, Maddy, Dave, Laura, Dave";
translation = str.maketrans("","", string.punctuation);
new = words.translate(translation);
lower = new.lower();

However, this seems crude to me and I feel like I can accomplish my task with fewer function calls/less code. Does anyone have any suggestions as to how I could do this?


texts: Validate fields in Python dictionary using dictionary of lambdas

texts:
I would love some feedback on this.  I use it to validate web-form objects before persisting them in the dangerously-lazy MongoDb.  I have a class and many validators for each of my collections.  Is there a better way to write or go about this?

class ValidationError(Exception):
    pass

class User(object):

    @staticmethod
    def validate(data):

        def _id(val):
            if not isinstance(val, ObjectId):
                raise ValidationError('not ObjectId')
            else:
                return val

        map_keys = dict(
            _id=lambda x: _id(x)
        )

        def count(val):
            try:
                return int(val)
            except TypeError:
                raise ValidationError('%s not integer' % val)

        new_data = {}

        for key in data:
            try:
                new_data[key] = map_keys[key](data[key])
            except KeyError:
                raise ValidationError('Key not in User: "%s"' % key)
            except ValidationError, error:
                print key, error
                raise
        return new_data


texts:
I have a CRM system that has Notes, Payments, DairyEvents and anything else that needs to be bolt on over time.

I created an ITimeline interface that has a datetime and message method and implemented them on those models.

This is the simplest form of code I have started with:

public static List<Interfaces.ITimeline> GetAll(long personID)
{
    List<Interfaces.ITimeline> timelineEvents = new List<Interfaces.ITimeline>();

    timelineEvents.AddRange(Controllers.FollowUp.GetAll(personID));
    //add more to the list as the system grows

    return timelineEvents;
}

That is fine, as long as one of the controllers doesn't throw and error, then the whole Interface collapses. I had something similar happen on a another project, production environment, where a single provider went haywire due a bug on their system, amongst several other providers that were being interfaced with and worked fine. It wouldn't be so bad if it didn't crash all 600+ sites, just because of that mistake somebody else made.

I don't want to do try catches around every single addrange - I think that is just cluttering. Also, with integration like that, you build things to work, but exceptions happens here and there.

What is a proper way of taking data from various sources, controllers or integration, adding them to a collection of items for the interface? That way, if something fails in the middle, it won't bring down the entire page, or even worse, the whole framework.


texts: Lambda .Where() expression to return selected/flagged objects

texts:
In our software we enable certain features based on the existence of a flag.  The Flags class is a static class used to determine the existence of such a flag.

I came across one piece of logic that I wrote that I feel could benefit from refactoring.  The boolean logic works, but I think it's difficult to understand or read because it relies very heavily on short-circuiting.

The basic logic is:

Get all menu items.
Return a subset of those menu items by using the following rule:

Some menu items are tied to a specific flag that is expected to be hard-coded in some way.  The menu item name may not match the associated flag.
Any other menu items should be displayed.

Any help would be much appreciated.

private IEnumerable<MenuItemDefinition> GetMenuItems()
{
     return GetAllMenuItems().Where(mi =>
          (mi.MethodName != "NewWidget" || Flags.HasFlag("Feature1")) &&
          (mi.MethodName != "NewDongle" || Flags.HasFlag("Feature2")));
}


texts: Binary Min Heap data structure implementation

texts:
After reading about heap I tried to implement the heap. Below is my code along with test. Any feedback with respect to correctness, performance is welcome.

import java.util.Arrays;

public class BinaryHeap2 {
    private int[] heap;
    private int size;
    private int capacity;

    public BinaryHeap2(){
        capacity = 100;
        size = 0;
        heap = new int[capacity];
    }

    public BinaryHeap2(int capacity){
        this.capacity = capacity;
        size = 0;
        heap = new int[this.capacity];
    }

    public void offer(int i){

        if(size>=capacity){
            capacity = capacity*2;
            int[] tmp = new int[capacity];
            System.arraycopy(heap, 0, tmp, 0, heap.length);
            heap = tmp;
        }

        heap[size++] = i;

        heapifyUp(size-1);

    }

    private void heapifyUp(int position){
        int parent = (position-1)/2;
        while(heap[parent]>heap[position]){
            swap(parent,position);
            position = parent;
            parent = (position-1)/2;
        }
    }

    private void swap(int i, int j){
        int t = heap[i];
        heap[i] = heap[j];
        heap[j] = t;
    }

    public int peek(){
        return heap[0];
    }

    public int poll(){
        int min = heap[0];
        heap[0] = heap[size-1];
        size--;
        if(size>1)
            heapifyDown(0);
        return min;
    }

    public int getSize(){
        return size;
    }

    private void heapifyDown(int i) {
        int leftChild = 2*i+1;
        int rightChild = 2*i+2;
        int childToSwap = heap[leftChild]<heap[rightChild]?leftChild:rightChild;
        while(heap[i]> heap[childToSwap]){
            swap(i,childToSwap);
            i = childToSwap;
            leftChild = 2*i+1;
            rightChild = 2*i+2;
            if(rightChild>=size||leftChild>=size)break;
            childToSwap = heap[leftChild]<heap[rightChild]?leftChild:rightChild;
        }

    }

    public void display(){
        System.out.println(Arrays.toString(heap));
    }

}

Below is the Unit test

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;

public class BinaryHeap2Test {

    BinaryHeap2 heap;
    @Before
    public void setUp(){
        heap = new BinaryHeap2(3);
    }

    @Test
    public void test() {
        heap.offer(7);
        heap.offer(6);
        heap.offer(3);
        heap.offer(2);
        heap.offer(1);
        heap.offer(5);
        heap.offer(4);
        heap.offer(3);
        heap.offer(2);
        heap.display();
        assertEquals(1, heap.peek());
        assertEquals(heap.poll(), 1);
        assertEquals(heap.poll(), 2);
        assertEquals(heap.poll(), 2);
        assertEquals(heap.poll(), 3);
        assertEquals(heap.poll(), 3);
        assertEquals(heap.poll(), 4);
        heap.offer(1);
        heap.display();
        assertEquals(heap.poll(), 1);
        assertEquals(heap.poll(), 5);
        assertEquals(heap.poll(), 6);
        assertEquals(heap.poll(), 7);
        heap.display();

    }

    @Test
    public void test2(){
        heap.offer(300);
        heap.offer(200);
        heap.offer(100);

        assertEquals(100, heap.poll());
        heap.display();
        assertEquals(200, heap.poll());
        heap.display();
        assertEquals(300, heap.poll());
        heap.display();
        heap.offer(2);
        assertEquals(2, heap.peek());
        heap.offer(100);
        heap.offer(1);
        heap.offer(5);
        assertEquals(1, heap.poll());
        assertEquals(2, heap.poll());
        assertEquals(5, heap.poll());
        assertEquals(100, heap.poll());
    }

}


texts: Simple calculation program in assembly MASM

texts:
I am a beginner in assembly. This program calculates:

(Z+Z)+(X-Y)

DATA_SEG    SEGMENT
      X     DW 2
      Y     DW 3
      Z     DW 5
      RES1  DW ?
      RES2      DW ?
 DATA_SEG        ENDS
 CODE_SEG        SEGMENT

           ASSUME CS:CODE_SEG, DS:DATA_SEG

;**********************************************
 MAIN    PROC    FAR          ;MAIN PROGRAM STARTS HERE.

        MOV     AX,DATA_SEG
            MOV     DS,AX      ;INITIALIZING THE DS REGISTER.

            ; ***FIRST WE CALCULATE (Z+Z) AND SAVE IN RES1****
            MOV     AX,Z     ;
            add     AX,Z     ;  AX = Z+Z
            MOV     RES1,AX  ;  HOLD TEMPORARILY THE RESULT OF (Z-Z) IN RES1

        ; ***SECOND WE CALCULATE  (Y-X) AND SAVE IN RES2***
        MOV     AX,Y     ;  NOW STORE VAR Y IN AX REGISTER
        SUB     AX,X     ;  PERFORM  AX = Y-X
            MOV     RES2,AX  ;  HOLD TEMPORARILY THE RESULT OF (Y-X) IN RES2

            ; ***NOW ADD BOTH RES1 + RES2***

            MOV     AX,RES1  ; STORE  RESULT OF (Z+Z) IN AX REGISTER
            ADD     AX,RES2  ;  ADD RES1 + RES2

        ;****NOW FOR PRINTING WE MOVE THE VALUE IN DX REGISTER****

        MOV     DX,AX    ; tO PRINT WE FIRST MOVE DATA IN DX REGISTER
        ADD     DX,30H ;CONVERT TO ACSII CODE
            MOV     AH,2
            INT     21H
        MOV     AH,04CH
            INT     21H
MAIN    ENDP
CODE_SEG        ENDS
END     MAIN


texts:
Reworked based on the previous answer and on aesthetics and usability. It now sets the input focus, so you're always typing. When you run out of room for hours after tabbing through the inputs, you can hit space for more, or tab+space and you're done.

It trims numerical output to 6 digits for the rate and 3 digits for dollars (so the user can round for themselves for greater certainty).

Further improvements to make?

    <title>Tip Calculator</title>

Tip Calculator

 $ <input id=dividend type=text size=5 maxlength=5>

Hours:

        <input type=button value="add row" onclick="add_row()">

        <input type=button value="calculate" onclick="calculate()">

    &nbsp;

Github.io


texts:
Write a program that lets a user play "Rock,
  Paper, Scissors" against the computer. The program should ask the user
  to choose one of the three choices, and then the computer randomly
  picks one (without knowing what the user has chosen). For this
  problem, the user should be asked to enter an integer: 0 for rock, 1
  for paper, or 2 for scissors. Rock beats scissors, scissors beats
  paper, paper beats rock. The program should say who wins, and then
  keep playing until someone (the user or the computer) has won 10
  rounds. The computer needs to keep track of the current score and
  should also display it before each round.

import java.util.Scanner;
public class rock_paper
{

public static void main(String args[])
{
    int count_win=0;
    int user_choice;
    String choice=" ";
    int num_comp_wins=0;
    int num_user_wins=0;
    while(num_comp_wins!=10||num_user_wins!=10)
    {
    /* Read user input and determine choice */

    System.out.println("\n Let us play Rock Paper Scissors \n");
    System.out.println("\n Enter your choice 0 for rock, 1 for paper, or 2 for scissors \n");
    Scanner keyboard = new Scanner(System.in);
    user_choice=keyboard.nextInt();
    System.out.println("\n Your choice was \n"+user_choice);
    if(user_choice==0)
    {
        choice="rock";
    }
    else if(user_choice==1)
    {
        choice="paper";
    }
    else if(user_choice==2)
    {
        choice="scissor";
    }
    else
    {
        System.out.println("Incorrect choice");
        choice=null;
    }
    System.out.println(choice);

    /* Randomly generate computer input */

    Random rand = new Random();
    int computer_choice = rand.nextInt(3) + 1;
    String choice1="";
    if(computer_choice==0)
    {
        choice1="rock";
    }
    else if(computer_choice==1)
    {
    choice1="paper";
    }
    else if(computer_choice==2)
    {
    choice1="scissor";
    }
    else
    {
        System.out.println("Incorrect choice");
        choice1=null;
    }
    System.out.println(choice1);
   /* Compare user and computer response*/
    if (choice.equalsIgnoreCase("rock")) {
    if (choice1.equalsIgnoreCase("scissor"))
    {
        System.out.println("\nThe user wins!");
        num_user_wins++;
    }
    else if (choice1.equalsIgnoreCase("paper"))
    {
        System.out.println("\nThe computer wins!");
        num_comp_wins++;
    }
    else
        System.out.println("Tie");
}
else if (choice.equalsIgnoreCase("paper"))
{
    if (choice1.equalsIgnoreCase("scissor"))
    {
        System.out.println("\nThe computer wins!");
        num_comp_wins++;
    }
    else if (choice1.equalsIgnoreCase("rock"))
    {
        System.out.println("\nThe user wins!");
        num_user_wins++;
    }
    else
         System.out.println("Tie");
}
else if (choice.equalsIgnoreCase("scissor"))
{
    if (choice1.equalsIgnoreCase("rock"))
    {
        System.out.println("\nThe computer wins!");
        num_comp_wins++;
    }
    else if (choice1.equalsIgnoreCase("paper"))
    {
        System.out.println("\nThe user wins!");
        num_user_wins++;
    }
    else
         System.out.println("Tie");
}

}

}
}


texts: Stack based non-recursive Fibonacci - Go implementation

texts:
The following function computes a the last element in a Fibonacci sequence in Go language.

package main

import (
    "fmt"
)

type Element struct {
    Next  *Element
    Value interface{}
}
type Stack struct {
    Top   *Element
    Count int
}

func (stack *Stack) Push(value interface{}) {
    el := Element{
        Value: value,
        Next:  stack.Top,
    }
    stack.Top = &el
    stack.Count++
}
func (stack *Stack) Peek() (value interface{}) {
    if stack.Top != nil {
        value = stack.Top.Value
    }
    return
}
func (stack *Stack) Pop() (value interface{}) {
    if stack.Top != nil {
        value = stack.Top.Value
        stack.Top = stack.Top.Next
        stack.Count--
    }
    return
}
func (stack *Stack) Size() int {
    return stack.Count
}

func Fibonacci(n int) int {
    if n == 0 {
        return 0
    }
    if n == 1 {
        return 1
    }

    //for n >= 2 the initial stack has the 0 and 1 values
    stack := Stack{}
    stack.Push(0)
    stack.Push(1)

    // loop from n to 2
    for n > 1 {
        //pop two top elements from stack
        term1 := stack.Pop().(int)
        term2 := stack.Pop().(int)

        //push back the first popped element, this will become term2 on the next iteration
        stack.Push(term1)

        //push the sum of the two elements, this will be the Top element on the next iteration
        stack.Push(term1 + term2)

        //move to the next iteration
        n--

    }

    //the top element in stack represents the last element in the Fibonacci sequence for a given n position
    return stack.Pop().(int)
}
func FibonacciTest() {
    fmt.Println("F0 -> 0", 0 == Fibonacci(0))
    fmt.Println("F1 -> 1", 1 == Fibonacci(1))
    fmt.Println("F2 -> 1", 1 == Fibonacci(2))
    fmt.Println("F3 -> 2", 2 == Fibonacci(3))
    fmt.Println("F4 -> 3", 3 == Fibonacci(4))
    fmt.Println("F5 -> 5", 5 == Fibonacci(5))
    fmt.Println("F6 -> 8", 8 == Fibonacci(6))
    fmt.Println("F7 -> 13", 13 == Fibonacci(7))
    fmt.Println("F8 -> 21", 21 == Fibonacci(8))
    fmt.Println("F9 -> 34", 34 == Fibonacci(9))
    fmt.Println("F20 -> 6765", 6765== Fibonacci(20))
}
func main() {
    FibonacciTest()

}

I'm new to Go language. I'm interested if this code can be improved or what I can add to be more like a Go style. I'm not very sure about the .(int) "conversion" and any explanation will be appreciated.

https://play.golang.org/p/q57CvDaqRV


texts: Loose coupling, accessing class properties

texts:
I'm trying to get a better understanding of decoupling methods. Right now, I have this method:

private bool ContainsLegalFirstName(DataRow row, string legalFirstNameColumn)
{
    return row.Table.Columns.Contains(legalFirstNameColumn)
        && !String.IsNullOrEmpty(row[legalFirstNameColumn].ToString());
}

I was thinking about changing the DataRow to an IDataRecord and adding an IListSource parameter and passing in the DataTable, but then the problem is I can't access the columns of the DataTable from the IListSource. Any suggestions or is what I have good enough?


texts:
I need to parallelise a for loop that does quite a lot of processing over thousands of items. I came up with this basic loop that seems to work quite effectively on a small test.

template<class T, class C>
void parallel_for_each(std::vector<T>* ts, C callable, uint poolsize = (std::thread::hardware_concurrency()+1)*2) {

    atomic<size_t> index(0);
    std::vector<thread> threads;

    for (uint i = 0; i < poolsize; i++) {
        threads.emplace_back([&]() {
            while(index < ts->size()) {
                callable(ts->at(index++));
            }
        });
    }
    for (auto&& thread : threads) {
        thread.join();
    }
}

//use like:
std::vector<int> is= { 4,5, 6,7,8,3,2,25,44,34,562,356,235,66,3,45,66};
parallel_for_each(&is, print);

Is there any serious problem I've overlooked, or anything else I can improve?


texts: SICP Exercise 1.3: Sum of squares of two largest numbers out of three

texts:
The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following:

  Exercise 1.3.  Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

My answer is this:

    var sumSquareLargest = function (x, y, z) {
        var numbers = [x, y, z];
        numbers.sort();
        return numbers[1] * numbers[1] + numbers[2] * numbers[2];
    };

Am I doing unnecessary work here? How could I improve this answer, even if only stylistically-speaking?


texts:
Would like to have a code review so I can improve my knowledge and expertise in VBA more specifically with Dictionaries as this is the first time I used one.

For context I have duplicate data and need to consolidate creating a unique list. To achieve this I used a Dictionary concatenating 2 fields to make a unique key. Also I have a function that uses Dictionaries to get a unique key so I can find the number of occurrence for each order number and add a suffix at the end if more than 999 rows used for the same order.

Option Explicit
Sub UniqueListWithSumQty()

Dim wsSource As Worksheet
Dim ws As Worksheet
Dim sh As Worksheet
Dim strCell As String
Dim i As Long, j As Long
Dim LRow As Long
Dim dict As Object

Set ws = ActiveSheet
Set dict = CreateObject("Scripting.Dictionary")

With ws
    LRow = FindLastRow(ActiveSheet, 3, 21)
    .Range("C17:U" & LRow).Sort key1:=.Range("C17:C" & LRow), order1:=xlAscending, Header:=xlNo
    wsSource = .Range("C17:U" & LRow).value
End With
With dict
    For i = 1 To UBound(wsSource, 1)
        strCell = Join(Array(wsSource(i, 1), wsSource(i, 3)), "|")
        If Not .Exists(strCell) Then
            .item(strCell) = .Count + 1
            For j = 1 To UBound(wsSource, 2)
                wsSource(.Count, j) = wsSource(i, j)
            Next j
        Else
            wsSource(.item(strCell), 4) = wsSource(.item(strCell), 4) + wsSource(i, 4)
        End If
    Next i
    i = .Count
End With

Set sh = ActiveSheet
sh.Range("C17:U" & LRow).Clear

With sh.Range("C17")
    .Resize(i, UBound(wsSource, 2)) = wsSource
End With
Call CheckOccurance(Range("C17:C" & LRow), LRow, sh)
End Sub

Private Function CheckOccurance(rng As Range, LRow As Long, ws As Worksheet)
    Dim maxOrdNoRow As Double
    Dim timesOccured As Double
    Dim occur As Double
    Dim uniqueList As Object
    Dim i As Long
    Dim data As Variant
    Dim x As Long
    Dim key As Variant
    Dim lastUsedRow As Long

    Set uniqueList = CreateObject("Scripting.Dictionary")
    data = rng.value

    For i = 1 To UBound(data, 1)
         uniqueList(data(i, 1)) = Empty
    Next i

    For Each key In uniqueList
        maxOrdNoRow = Application.WorksheetFunction.CountIf(Range("C17:C" & LRow), "=" & key)
        timesOccured = maxOrdNoRow / 999

        lastUsedRow = ws.Range("C:C").Find(what:=key, after:=ws.Range("C16")).Row
        If timesOccured > 1 Then
            For x = 1 To WorksheetFunction.RoundUp(timesOccured, 0)
                If timesOccured > x Then
                    occur = timesOccured - (timesOccured - x)
                Else
                    occur = timesOccured
                End If
                ws.Range(Cells(lastUsedRow, 3), Cells((occur * 999) + 16, 3)).value = key & "-" & x
                lastUsedRow = (occur * 999) + 17
            Next x
        Else
            'do nothing
        End If
    Next key
End Function


texts: Updating NamedTuple members based on a function and previous value

texts:
I'm using a NamedTuple to represent the state of my game while it's running. The user can alter these settings using key presses, so in my PyGame key handler, I'm writing things like:

if key_code == 273:  # Up arrow
    return game_settings._replace(fps=game_settings.fps + 5)

Each key press transforms the settings state by using the old value and _replace.

I decided to try and emulate Clojure's update function as an exercise, and because it may actually make more code more readable. It takes a function and a key, and updates the value at that key using the function. Example usage:

>>> sett = GameSettings(fps=30, is_running=True)

>>> sett.update(lambda x: not x, "is_running")
GameSettings(fps=30, is_running=False)

>>> sett.update2(lambda x: not x, is_running=None)
GameSettings(fps=30, is_running=False)

I created two different versions that each behave similarly but are slightly different. Version one accepts a string key. Version two accepts kwargs with a dummy value. I'm not super happy with either though. Having to pass a String to Version one fells messy any error prone. If I typo the String, I'll get an AttributeError at runtime. Version two accepting a dummy value also feels off and is also error prone; although I do think it reads nicer without the quotes. The code for each is also quite ugly and dense.

The methods don't actually need to accept more than one key (I'll probably never pass more than one at a time), but I figured it barely changes the algorithm and it mirrors _replace, so I decided why not.

I'd appreciate any thoughts here on how to set this up better or make the code cleaner.

from __future__ import annotations
from typing import NamedTuple, Callable, TypeVar
from functools import reduce

T = TypeVar("T")

class GameSettings(NamedTuple):
    fps: int
    is_running: bool = True

    def update(self, f: Callable[[T], T], *keys) -> GameSettings:
        return reduce(lambda acc, k: acc._replace(**{k: f(getattr(acc, k))}), keys, self)

    def update2(self, f: Callable[[T], T], **kwargs) -> GameSettings:
        return self._replace(**{k: f(getattr(self, k)) for k, _ in kwargs.items()})


texts: Fast prototype code to hook up a webcam to the Azure Emotion API

texts:
Last week I had a 5 hours school project deadline based on the Azure Emotion API. Right now I am trying to rewrite the same code in a more clean/elegant way. I am quite new to coding so I will need all the help I can get. I am not really looking for a shorter way to write the same code, but I am looking for a clean/understandable way.

(function () {
  let tempEmotion = ''
  let lastEmotion = ''

  function ShowCam () {
    Webcam.set({
      width: 480,
      height: 360,
      image_format: 'jpeg',
      jpeg_quality: 100
    })
    Webcam.attach('#myCamera')
  }

  function TakeSnapshot () {
    Webcam.snap(function (dataUri) {
      document.getElementById('results').innerHTML = '<img id="base64image" src="' + dataUri + '"/>'
    })
    SaveSnapshot()
  }

  function SaveSnapshot () {
    let file = document.getElementById('base64image').src.substring(23).replace(' ', '+')
    let img = Base64Binary.decodeArrayBuffer(file)
    let ajax = new XMLHttpRequest()

    ajax.addEventListener('load', function (event) {
      UploadComplete(event)
    }, false)
    ajax.open('POST', 'https://api.projectoxford.ai/emotion/v1.0/recognize', 'image/jpg')
    ajax.setRequestHeader('Content-Type', 'application/octet-stream')
    ajax.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml')
    ajax.setRequestHeader('Ocp-Apim-Subscription-Key', 'EXTREMELY_HIDDEN_KEY')
    ajax.send(img)
  }

  function UploadComplete (event) {
    let xmlDoc = event.target.responseXML
    let result = xmlDoc.getElementsByTagName('scores')
    GiveUserFeedback(result)
  }

  function GiveUserFeedback (result) {
    let emotionArray = []
    let tempValue = 0
    let htmlBody = $('body')
    if (result[0]) {
      for (let i = 0; i < result[0].childNodes.length; i++) {
        emotionArray.push(Math.floor((Number(result[0].childNodes[i].textContent) * 100) + 1))
        if (Number(result[0].childNodes[i].textContent).toFixed(2) > tempValue) {
          tempValue = Number(result[0].childNodes[i].textContent).toFixed(2)
          tempEmotion = String(result[0].childNodes[i].nodeName)
          tempEmotion = tempEmotion.substr(0, 1).toUpperCase() + tempEmotion.substr(1)
        }
      }
      for (let i = 0; i < emotionArray.length; i++) {
        $('ul li:nth-child(' + (i + 1) + ') span').css('height', emotionArray[i])
      }
      switch (tempEmotion) {
        case 'Angry':
          htmlBody.css('background-color', '#F44336')
          htmlBody.css('color', '#FFFFFF')
          $('span').css('background-color', '#FFFFFF')
          break
        case 'Contempt':
          htmlBody.css('background-color', '#9C27B0')
          htmlBody.css('color', '#FFFFFF')
          $('span').css('background-color', '#FFFFFF')
          break
        case 'Disgust':
          htmlBody.css('background-color', '#673AB7')
          htmlBody.css('color', '#FFFFFF')
          $('span').css('background-color', '#FFFFFF')
          break
        case 'Fear':
          htmlBody.css('background-color', '#FF9800')
          break
        case 'Happiness':
          htmlBody.css('background-color', '#4CAF50')
          break
        case 'Neutral':
          htmlBody.css('background-color', '#FFFFFF')
          break
        case 'Sadness':
          htmlBody.css('background-color', '#03A9F4')
          break
        case 'Surprise':
          htmlBody.css('background-color', '#FFEB3B')
      }
      lastEmotion = tempEmotion
    }
  }

  window.onload = ShowCam
  window.setInterval(function () {
    TakeSnapshot()
  }, 3000)
})()


texts:
PHP realpath($path); is insufficient for some cases since it returns false on paths that dont exist on a file system.

I need a function that extends realpath($path); to return even path that does not exist yet. Such function would be used for keeping a user within his filesystem directory and/or restricting modifications to some directories and files.

function DesiredRealPath($path_string) {
    $desired_path = explode("/", str_replace("\\", "/", $path_string)); // convert back slashes to front slashes and create array of desired directories
    $real_path = explode("/", str_replace("\\", "/", realpath("."))); // convert back slashes to front slashes and create array of actual directories
    if(mb_substr($path_string, 0, 1) == "/" || mb_substr($path_string, 0, 1) == "\\") { // if path string begins with a slash, slice all actual directories except for root
        $real_path = array_slice($real_path, 0, 1); // "/" points to root directory
    }
    foreach ($desired_path as $desired_element) {
        switch ($desired_element) {
            case "":
                break;
            case ".":
                break;
            case "..": // remove last element of actual directories if array has at least 2 directories left
                if(count($real_path) >= 2) {
                    array_pop($real_path);
                }
                break;
            default: // push desired directory into actual directories
                array_push($real_path, $desired_element);
                break;
        }
    }
    return implode("/", $real_path); // put array of actual directories into a string
}

So far I have tested on both Windows and Linux, this function has determined precise directory even non-existant ones.

My question is, whether this function has any flaws or security vulnerabilities?


texts: Formatting a datetime string in the YYYYMMDD format

texts:
I'm working with some strange APIs that requires the dates to be sent in the YYYYMMDD format.

I was thinking of doing something like this:

string date = string.Concat(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

Is there a better practice?


texts:
I'm very new to Swift and programming in general. I'm creating a quiz application and am trying to create a function that will save the number of times a user has completed a quiz.

It appears to work through testing but I was wondering if there was a more elegant way to write this function:

func plusTestsTaken() {
    var testsTakenSave = NSUserDefaults.standardUserDefaults()

    if testsTakenSave.integerForKey("testsTaken") >= 1 {
        var testsTakenCount = testsTakenSave.valueForKey("testsTaken") as! Int
        testsTakenCount++
        testsTakenSave.setValue(testsTakenCount, forKey: "testsTaken")
        testsTakenSave.synchronize()
        println("Test again \(testsTakenCount)")
    } else {
        var testsTakenCount = 1
        testsTakenSave.setValue(testsTakenCount, forKey: "testsTaken")
        testsTakenSave.synchronize()
        println("Test number \(testsTakenCount)")
    }
}


texts: A JavaScript class, which finalises the HTML of each page of my NodeJS (Express) website

texts:
Background

A request (req in the code) is made to my server, and a response (res) returned. By the time the response has filtered through to the code below, most of the heavy lifting - looking up entries in a database, etc - has already been done. This code just puts some final tweaks on all responses before it's pushed out to the user's browser.

What This Code Does

More specifically, the code achieves three things:

A time stamp is added to the footer of the page.
The crude kind of apostrophes are transmuted into the prettier, curlier kind. (This is more important in some fonts than in others.)
-- and --- are transmuted into en and em dashes respectively.

Entry Point

This code is fired only when code in another file calls finaliser.protoRender(req, res, view, properties);. So the protoRender method is the only entry point; it's also the only exit.

The Code

/*
This code contains a class which handles any final, universal touches to the
page before it's passed to the browser.
*/

// The class in question.
class Finaliser
{
  constructor()
  {

  }

  // Ronseal.
  static fixApostrophes(input)
  {
    while(input.indexOf("``") >= 0)
    {
      input = input.replace("``", "&ldquo;");
    }
    while(input.indexOf("''") >= 0)
    {
      input = input.replace("''", "&rdquo;");
    }
    while(input.indexOf("`") >= 0)
    {
      input = input.replace("`", "&lsquo;");
    }
    while(input.indexOf("'") >= 0)
    {
      input = input.replace("'", "&rsquo;");
    }
    return input;
  }

  // Ronseal.
  static fixDashes(input)
  {
    while(input.indexOf("---") >= 0)
    {
      input = input.replace("---", "&mdash;");
    }
    while(input.indexOf("--") >= 0)
    {
      input = input.replace("--", "&ndash;");
    }
    return input;
  }

  // Render, and deliver the page to the browser.
  protoRender(req, res, view, properties)
  {
    var date = new Date();

    properties.footstamp = date.toISOString();
    res.render(view, properties, function(err, html){
      if(html === undefined)
      {
        res.render(view, properties);
      }
      else
      {
        html = Finaliser.fixApostrophes(html);
        html = Finaliser.fixDashes(html);
        res.send(html);
      }
    });
  }
}

// Exports.
module.exports = Finaliser;


texts: Simple singly linked list implementation in C

texts:
I have implemented a LinkedList with the ability to add, get elements from a particular position and ability to show all the elements in the array in to the console (main purpose to implement this was to ensure that all the elements are being populated in the LinkedList correctly).

I would highly appreciate comments based on:

The efficiency of my code
Conceptual misinterpretations of a linked list, if any
Violations of best practices
Better way of achieving this

This is the code I have written:

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

struct Element {
    int value;
    struct Element *nextElement;
};

struct LinkedList {
    struct Element *firstElement;
};

void add(struct LinkedList *list, int value) {
    if(list->firstElement == NULL) {
        struct Element *newElement;
        newElement = malloc(sizeof(struct Element));

        newElement->value = value;
        newElement->nextElement = NULL;

        list->firstElement = newElement;
    } else {
        struct Element *lastElement;

        lastElement = list->firstElement;

        while(lastElement->nextElement != NULL) {
            lastElement = lastElement->nextElement;
        }

        struct Element *newElement;
        newElement = malloc(sizeof(struct Element));

        newElement->value = value;
        newElement->nextElement = NULL;

        lastElement->nextElement = newElement;
    }
}

int getElement(struct LinkedList *list, int index) {
    int iteratedIndex = 0;
    int returnValue = 0;

    struct Element *temporaryElement = list->firstElement;

    while(temporaryElement != NULL) {
        if(iteratedIndex == index) {
            returnValue = temporaryElement->value;
            return returnValue;
        }

        iteratedIndex = iteratedIndex + 1;
        temporaryElement = temporaryElement->nextElement;
    }

    return 0;
}

void showAllElements(struct LinkedList *list) {
    struct Element *lastElement = list->firstElement;

    while(lastElement != NULL) {
        printf("%d\n", lastElement->value);
        lastElement = lastElement->nextElement;
    }
}

int main()
{
    struct LinkedList list = {NULL};
    add(&list, 5);
    add(&list, 10);
    add(&list, 15);
    showAllElements(&list);

    int value = getElement(&list, 0);

    printf("%d\n", value);

    return 0;
}

Here's the output I got:

5
10
15
5

Which is correct, first three listing all the elements in the LinkedList and last one fetching the element in the 0th index.


texts:
Implemented the quick sort algorithm in python, It was just for learning it, now I want to port it to C.

Thoughts on the quality of my python implementation?

from random import randint, shuffle

def swap(array, a, b):
    array[a], array[b] = array[b], array[a]

def quick_sort(array, start=0, end=None):
    if end is None:
        end = len(array) - 1

    if end - start >= 1:
        pivot = array[end]
        a = start
        b = end - 1
        while not a > b:
            if not array[a] > pivot:
                a += 1
                continue
            else:
                if array[b] < pivot:
                    swap(array, a, b)
                    a += 1
                b -= 1
        swap(array, a, end)
        quick_sort(array, start, a - 1)
        quick_sort(array, a + 1, end)

arr = [randint(0, 30) for _ in range(20)]
print(arr)
quick_sort(arr)
print(arr)


texts: Securely implementing AES/RSA hybrid crypto with PyCryptodome

texts:
I wondering if anyone could give me feedback on whether or not this is a secure way to implement AES/RSA hybrid encryption and signatures in python 3 with the PyCryptodome module.

All of the encoding and to/from hex format is just there because that's the format I intend to transfer it in.

"""Hybrid AES/RSA encryption, integrity, and repudiation proof of concept.
    Requires the PyCryptodome module but is imported as Crypto"""

from hashlib import sha512
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes

def generate_keys():
    """ Generates the rsa key pair and returns them.
        In actual usage private key is exported to .pem secured with a passphrase"""
    while True:
        privatekey = RSA.generate(2048)
        publickey = privatekey.publickey()

        return privatekey, publickey

def encrypt_msg(msg_body, publickey, privatekey):
    """Generates the session key, then creates the nonce and cipher.
       encrypts the message body with AES 256.
       encrypts the session key with RSA 2048
       returns the cipher text, tag, nonce, and the encrypted session key in hex format
       Hashes clear text message and creates signature"""
    session_key = get_random_bytes(32)

    aes_cipher = AES.new(session_key, AES.MODE_EAX)
    nonce = aes_cipher.nonce
    aes_cipher_text, tag = aes_cipher.encrypt_and_digest(msg_body)

    rsa_cipher = PKCS1_OAEP.new(publickey)
    enc_session_key = rsa_cipher.encrypt(session_key)

    msg_hash = int.from_bytes(sha512(msg_body).digest(), byteorder='big')
    signature = pow(msg_hash, privatekey.d, privatekey.n)

    return aes_cipher_text.hex(), tag.hex(), nonce.hex(), enc_session_key.hex(), signature

def decrypt_msg(aes_cipher_text, tag, nonce, enc_session_key, privatekey, publickey, signature):
    """encrypted session key is encoded and returned from hex
       Uses private key to decrypt the session key
       nonce is encoded and returned from hex
       cipher is created with supplied key, and nonce
       cipher text is decrypted
       tag is encoded and returned from hex
       message is checked for authenticity
       clear text is returned and authenticity status is returned
       hashes clear text and compares to signature
       """

    decrypt = PKCS1_OAEP.new(privatekey)
    session_key = decrypt.decrypt(enc_session_key.encode().fromhex(enc_session_key))

    aes_cipher = AES.new(session_key, AES.MODE_EAX, nonce=nonce.encode().fromhex(nonce))
    clear_text = aes_cipher.decrypt(aes_cipher_text.encode().fromhex(aes_cipher_text))

    try:
        aes_cipher.verify(tag.encode().fromhex(tag))
        authentic = True

    except ValueError:
        authentic = False

    msg_hash = int.from_bytes(sha512(clear_text).digest(), byteorder='big')
    hashfromsignature = pow(signature, publickey.e, publickey.n)
    if msg_hash == hashfromsignature:
        valid = True

    else:
        valid = False

    return clear_text, authentic, valid

TEST_MSG = b'this is a short test message.'

# Generates and assigns public and private keys
# Person A's key pair
PRIVATE_KEY, PUBLIC_KEY = generate_keys()
# Person B's key pair
PRIVATE_KEY_1, PUBLIC_KEY_1 = generate_keys()

# Encrypts the message, and creates the tag, nonce and encrypted session key
# Note same key pair is used only for testing purposes in implementation
# both sides will have own key pairs
msg_aes_cipher_text, msg_tag, msg_nonce, encrypted_session_key, signature = encrypt_msg(TEST_MSG, PUBLIC_KEY_1, PRIVATE_KEY)

# Decrypts the message with the supplied data and check for authenticity
msg_clear_text, authentic_status, valid = decrypt_msg(msg_aes_cipher_text, msg_tag, msg_nonce, encrypted_session_key, PRIVATE_KEY_1, PUBLIC_KEY, signature)
if valid:
    print('Valid signature.')
else:
    print('Invalid signature!')
if msg_tag:
    print('Valid tag.')
else:
    print('Invalid tag.')
print(msg_clear_text)
```


texts: Securely deleting files, while attempting to protect the user against obviously dangerous inputs

texts:
As far as I can tell, no gem currently exists to wrap shred, the *nix utility to securely delete files.  I created a small class to do this, the key methods are:

def self.run cmd
  stdout,stderr,status = Open3.capture3 cmd
  raise "Failed executing #{cmd}: stdout: #{stdout}, stderr: #{stderr}, status #{status}" unless status.nil? || status == 0
  stdout
end

def self.validate_path path, required_regex=nil
  raise if required_regex && !required_regex.is_a?(Regexp)
  File.expand_path(path).tap do |path|
    raise if path == '/'
    raise if required_regex && !path.match(required_regex)
  end
end

def self.dir! path, opts={}
  return unless Dir.exist?(path)
  validate_path path, opts[:path_must_match]

  stdout = run "find #{path} -type f -exec #{shred_cmd} '{}' ';'"
  FileUtils.rm_rf path
  stdout
end

find is used to execute shred, since it lacks a recursive option.  I initially tried execdir instead of exec for security, but travis and other build environments hate it.  Potential problem?
validate_path tries to keep the user from screwing themselves by expanding the path, better ways of doing this?


texts: To extract specific information in the stack trace using regular expression

texts:
I encountered a problem at http://regexone.com/example/6?
You can view the problem by clicking the link.
There was required a regular expression to extract the method name, filename and the line number from a particular stack trace in an android development application.

I used the following regular expression to solve the problem :

at widget.List.([a-zA-Z]+).([A-Za-z]+\.java).(\d{3,4}).

The expression works for the problem but i don't think its the correct regular expression as there is no hat(^) and dollar ($) included in it.


texts:
I was reading an article on Wikipedia about memoization, so I wanted to try and apply it. I am fairly new to this subject, so I thought I'd start small. Does the program use memoization correctly? Is there anything that I can improve?

#include <iostream>

int fibonacci(int num, int* memoize);

int main()
{
    int num;

    std::cout << "i: ";
    std:: cin >> num;

    // i will assume that num > 2, just to keep it short and simple
    int* memoize = new int[num + 1];
    memoize[0] = 0;
    memoize[1] = 1;

    // -1 indicates that the value is not within the array
    for (int i = 2; i <= num; i++)
        memoize[i] = -1;

    std::cout << num << "th fibonacci number: " << fibonacci(num, memoize) << std::endl;

    delete [] memoize;
    return 0;
}

int fibonacci(int num, int* memoize)
{
    // if value has not been calculated yet
    if (memoize[num] == -1)
    {
        // calculate it and store it in the array
        memoize[num] = fibonacci(num - 1, memoize) + fibonacci(num - 2, memoize);
    }

    return memoize[num];
}

I read that the recursive solution to fibonacci is not preferred, but I am still trying to figure out the iterative solution.


texts:
I want to know if my SCSS code looks correct.
Note: Everything works as I expected. The Main Idea of this code is to generate Word Break Utilities for controlling word breaks in an element.
using SCSS mean I can declare only css classes in html element.
here is the result of my code :
.break-normal {
  overflow-wrap: normal;
  word-break: normal;
}

.break-words {
  overflow-wrap: break-word;
}

.break-all {
  word-break: break-all;
}

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

My SCSS CODE :
$wordBreak: (
  "break-normal": normal,
  "break-words": break-word,
  "break-all": break-all,
  "truncate": (
    "overflow": hidden,
    "text-overflow": ellipsis,
    "white-space": nowrap
  ),
) !default;

@each $wordBreakClassName , $wordBreakType in $wordBreak {
  @if ($wordBreakClassName) == "break-normal" {
    .#{$wordBreakClassName} {
      overflow-wrap: $wordBreakType;
      word-break: $wordBreakType;
    }
  }
  @else if ($wordBreakClassName) == "break-words" {
    .#{$wordBreakClassName} {
      overflow-wrap: $wordBreakType;
    }
  }
  @else if ($wordBreakClassName) == "break-all" {
    .#{$wordBreakClassName} {
      word-break: $wordBreakType;
    }
  }
  @else if ($wordBreakClassName) == "truncate" {
    .#{$wordBreakClassName} {
      overflow: map-get(map-get($wordBreak, truncate), overflow);
      text-overflow: map-get(map-get($wordBreak, truncate), text-overflow);
      white-space: map-get(map-get($wordBreak, truncate), white-space);
    }
  }
}


texts: Implementation of Dijkstra's Algorithm in JavaScript that returns both shortestDist/shortestPaths

texts:
I decided to try to understand the basic idea behind Dijkstra's algorithm better so I implemented it in JavaScript (the only language I am proficient in as of now) so I could really see what was happening in the Chrome debugger.

I chose not to use a priority queue or a heap in my implementation, but I do return both the shortest paths and the shortest distances for each vertex from the source.

//my attempt at coding the wiki pseudocode version of Dijkstra in Javascript, that returns
//both the shortest paths AND shortest distances to each vertex from the source vertex input

var INFINITY = 1/0;

function DirectedGraph(){
  this.vertices = {};
  this.addVertex = function(name, edges){
    edges = edges || null;
    this.vertices[name] = edges;
  }
}

function findSmallest(dist, q) {
  var min = Infinity;
  var minNode;

  for (var node in q) {
    if (dist[node] <= min) {
      min = dist[node]
      minNode = node;
    }
  }

  delete q[minNode]
  return minNode;
}

function djikstra(graph, startVertex) {
  var dist = {};
  var prev = {};
  var q = {};
  var shortestPaths = {};

  for (var vertex in graph.vertices) {
    dist[vertex] = INFINITY;
    prev[vertex] = null;
    q[vertex] = graph.vertices[vertex];
    shortestPaths[vertex] = [];
  }

  dist[startVertex] = 0;

  while (Object.keys(q).length !== 0) {
    var smallest = findSmallest(dist, q);
    var smallestNode = graph.vertices[smallest]
    //searches for the vertex u in the vertex set Q that has the least dist[smallest] value.

    for (var neighbor in smallestNode) {
      var alt = dist[smallest] + smallestNode[neighbor];
      //smallestNode[neighbor] is the distance between smallest and neighbor
      if (alt < dist[neighbor]) {
        dist[neighbor] = alt
        prev[neighbor] = smallest
      }
    }
  }

  getShortestPaths(prev, shortestPaths, startVertex, dist)

  return {
    shortestPaths: shortestPaths,
    shortestDistances: dist
  }
}

function getShortestPaths(previous, shortestPaths, startVertex, dist) { debugger
  for (var node in shortestPaths) {
    var path = shortestPaths[node];

    while(previous[node]) {
      path.push(node);
      node = previous[node];
    }

    //gets the starting node in there as well if there was a path from it
    if (dist[node] === 0) {
      path.push(node);
    }
    path.reverse();
  }
}

var graph = new DirectedGraph();

graph.addVertex('S', {V: 1, W: 4});
graph.addVertex('W', {T: 3});
graph.addVertex('V', {W: 2, T: 6});
graph.addVertex('T');

console.log(djikstra(graph, 'S'));

----------------->

{ shortestPaths:
   { S: [ 'S' ],
     W: [ 'S', 'V', 'W' ],
     V: [ 'S', 'V' ],
     T: [ 'S', 'V', 'W', 'T' ] },
  shortestDistances: { S: 0, W: 3, V: 1, T: 6 } }


texts: Set values with keeping immutability in React FC

texts:
I'd like to know there's a better code than I did.

interface AnswerProps{
  itemId: string;
  value: Array<string>
}

This code works like checkbox. If answers has a value, I try to put the same value again. It would be deleted like toggle.

const App = () => {
   const [answers, SetAnswers] = React.useState<AnswerProps[]>([]);

   /*

   */
   const handleAnswers = (value: string, answerIndex: number) => {
      let i = answers[answerIndex].value.indexOf(value);
      if(i === -1){
        setAnswers(answers.map((el: AnswerProps, index: number)=>{
          if(index === answerIndex) return {...el, value: el.value.concat(value);
          else return { ...el }
        }));
      }
   }

   (...)
}
```


texts:
Problem Statement:

  Write a program that will convert a binary number, represented as a
  string (e.g. '101010'), to its decimal equivalent using first
  principles

  Implement binary to decimal conversion. Given a binary input string,
  your program should produce a decimal output. The program should
  handle invalid inputs.

Code:

public class Binary {
  private final String binaryString;

  public Binary(String binaryString) {
    this.binaryString = binaryString;
  }

  public int getDecimal() {
    return toDecimal(binaryString);
  }

  public static int toDecimal(String str) {
    int decimal = 0;
    int base0 = (int)'0';
    char ch;
    for (int i = 0; i < str.length(); i++) {
      ch = str.charAt(i);
      if (charIsNotBinary(ch)) {
        return 0;
      }
      decimal = decimal * 2 + ((int)str.charAt(i) - base0);
    }
    return decimal;
  }

  private static boolean charIsNotBinary(char ch) {
    return '1' < ch || ch < '0';
  }
}

Test Suite:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class BinaryTest {

    private String input;
    private int expectedOutput;

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {"1", 1},
                {"10", 2},
                {"11", 3},
                {"100", 4},
                {"1001", 9},
                {"11010", 26},
                {"10001101000", 1128},
                {"2", 0},
                {"5", 0},
                {"9", 0},
                {"134678", 0},
                {"abc10z", 0},
                {"011", 3}
        });
    }

    public BinaryTest(String input, int expectedOutput) {
        this.input = input;
        this.expectedOutput = expectedOutput;
    }

    @Test
    public void test() {
        Binary binary = new Binary(input);

        assertEquals(expectedOutput, binary.getDecimal());
    }
}

Reference:

http://exercism.io/exercises/java/binary/readme


texts:
I need some tips on how I can improve the design of the following code. Everything works correctly in the program. It takes a string and shows each token, the only tokens being numbers and operators. The output shows all the tokens and what type of token they are.

public class Tokenizer {
    int pos;
    char[] expression;

    Tokenizer(String expression) {
        this.expression = expression.toCharArray();
        this.pos = 0;
    }

    enum Type { OPERATOR, NUMBER, UNKNOWN }

    class Lexeme {
        String type, token;
        Lexeme(String type, String token) {
            this.type = type;
            this.token = token;
        }
    }

    Lexeme getToken() {
        StringBuilder token = new StringBuilder();
        boolean endOfToken = false;
        Type type = Type.UNKNOWN;
        while (!endOfToken && hasMoreToken())
        {
            while(expression[pos] == ' ')
                pos++;
            switch (expression[pos])
            {
                case '+':
                case '-':
                case '*':
                case '/':
                    if(type != Type.NUMBER)
                    {
                        type = Type.OPERATOR;
                        token.append(expression[pos]);
                        pos++;
                    }
                    endOfToken = true;
                    break;
                case ' ':
                    endOfToken = true;
                    pos++;
                    break;
                default:
                    if(Character.isDigit(expression[pos]) || expression[pos] == '.')
                    {
                        token.append(expression[pos]);
                        type = Type.NUMBER;
                    }
                    else
                    {
                        System.out.println("Systax error at position: " + pos);
                    }
                    pos++;
                    break;
            }
        }
        return new Lexeme(type.name().toLowerCase(), token.toString());
    }

    boolean hasMoreToken() {
        return pos < expression.length;
    }

    public static void main(String[] args) {
        // TODO code application logic here
        String expression = "12.3 / 5 - 22";
        Tokenizer tokenizer = new Tokenizer(expression);
        while (tokenizer.hasMoreToken())
        {
            Lexeme nextToken = tokenizer.getToken();
            System.out.print("Type: " + nextToken.type + "\tLexeme: " + nextToken.token + "\n");
        }
    }
}


texts: Creating instance of all classes that have certain attribut value

texts:
I have a simple custom attribute MessageDeliveryAttribute that has one string filed. Also I have several classes that mark with this attribute like:

[MessageDeliveryAttribute("MessegaToDb")]

In the app.config are settings like:

  <appSettings>
    <add key="MessageToConsole" value="true"/>
    <add key="MessageToDb" value="true"/>
    <add key="MessageToService" value="false"/>
    <add key="MessageToFile" value="false"/>
  </appSettings>

I'm trying to implement class that will read all keys with value "true" from app.config, find all classes that marked with attribute

[MessageDeliveryAttribute("value of key from app.config where value = true")]

and then create a list with instance of these classes.
Here are working code, but I need your suggestions how to improve that?

public static List<IMessageDelivery> GetMessagesDelivery()
{
    var instances = new List<IMessageDelivery>();

    // list of settings from app.config where value is true
    List<string> settingValues = ConfigurationManager.AppSettings.AllKeys
        .Where(key => ConfigurationManager.AppSettings[key].Equals("true"))
        .Select(value => value)
        .ToList();

    foreach (var types in GetTypesWithMessageDeliveryAttribute())
    {
        var attributeValue = GetAttributeValue(types);
        if (settingValues.IndexOf(attributeValue) >= 0)
        {
            instances.Add(Activator.CreateInstance(types) as IMessageDelivery);
        }
    }

    return instances;
}
// Get all classes with my custom attribute
public static IEnumerable<Type> GetTypesWithMessageDeliveryAttribute()
{
    var assembly = Assembly.GetExecutingAssembly();
    return from type in assembly.GetTypes()
           where type.IsDefined(typeof(MessageDeliveryAttribute), false)
           select type;
}
// get value of attribute
public static string GetAttributeValue(Type t)
{
    var messageDeliveryAttribute = (MessageDeliveryAttribute)Attribute.GetCustomAttribute(t, typeof(MessageDeliveryAttribute));

    return messageDeliveryAttribute != null ? messageDeliveryAttribute.DeliveryPointName : string.Empty;
}


texts: Arduino code and PING))) ultrasonic rangefinder

texts:
Context
I've started digging into Arduino and different type of sensors which is fun, but I'm worried that that my coding is too explicit. I've lots of experience for coding corporate programs, though it is not in C/C++. I don't consider myself a beginner, but I think something is wrong.

Blocks
I'd place my code in this section.  It is using PING))) sensor to detect how far an object is based on the travel time of an emitted ultra-sonic signal. This sketch is taken from the TinkerCad website which can be found here: tinkercad.com.
/*
  Ping))) Sensor

  This sketch reads a PING))) ultrasonic rangefinder and returns the distance to the closest object in range. To do this, it sends a pulse to the sensor to initiate a reading, then listens for a pulse to return.  The length of the returning pulse is proportional to the distance of the object from the sensor.

  The circuit:
   * +V connection of the PING))) attached to +5V
   * GND connection attached to ground
   * SIG connection attached to digital pin 7

  http://www.arduino.cc/en/Tutorial/Ping

  This example code is in the public domain.
*/

const int speedOfSoundInAirInMetersPerSecond = 343;
const float speedOfSoundInAirInCentimeterPerMicrosecond =
  speedOfSoundInAirInMetersPerSecond / 10000.0;
const float centimeterToInchRatio = 2.54;

int inches = 0;
int cm = 0;

long readTravelTimeInMicroseconds(int triggerPin, int echoPin)
{
  pinMode(triggerPin, OUTPUT);  // Clear the trigger
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(2);

  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);

  digitalWrite(triggerPin, LOW);
  pinMode(echoPin, INPUT);

  // Reads the echo pin, and returns the sound wave travel time in microseconds
  return pulseIn(echoPin, HIGH);
}

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  // I had to divided that speed by 2 because
  // I'm only interested in the time which took
  // signal to reach an object. I don't need to know
  // how much distance we covered by the signal to the object and back.
  cm = (speedOfSoundInAirInCentimeterPerMicrosecond / 2)
    * readTravelTimeInMicroseconds(7, 7);

  inches = (cm / centimeterToInchRatio);
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.println("cm");
  delay(100);
}

My thoughts

Am I not being too explicit? I've learnt over the years that it is always better to beexplicit. But, am I not going overboard here?

Are there styles and conventions, styles I should follow when working with Arduino or electronics of this type? My question concerns with the technical side of the code.


texts: Multiple longest common subsequence (another algorithm)

texts:
Here is the algorithm:

Input: a set of \$M\$ strings \$S=\{s_i\}\$ of length \$N\$ with alphabet \$\Sigma\$

Make an index of each string by chars.
Maintain a position \$p=(p_i)\$ where \$p_i\$ is an index into string \$s_i\$.
Set the initial position such that \$\forall i: p_i = |s_i|+1\$
(1-based indexing).

While chars left in strings do:

Select the next point among matches (same char in every string) by looping through the alphabet shared by the strings and picking the point with the minimal m-dimensional euclidean distance to the current point.

Is this \$O(|\Sigma|*M*\log(N))\$?

Here is (quite bad) sample python code:

from collections import defaultdict
import sys, bisect

def mlcs(strings):
    strings = list(set(strings))
    indexes = dict()

    sigma = set()
    for x in strings:
        sigma = sigma.union(set(x))

    for x in strings:
        tx = defaultdict(list)
        for i in range(len(x)):
            tx[x[i]] += [i]
        indexes[x] = tx

    def match(pos):
        s = True
        for i in range(len(strings)-1):
            x = strings[i]
            y = strings[i+1]
            s &= x[pos[x]] == y[pos[y]]
        return s

    def distance(ind1, ind2):
        d = 0
        for x in strings:
            d += (ind1[x] - ind2[x])**2
        return d

    def find(xs, y):
        i = bisect.bisect_right(xs, y)
        return i-1

    pos = {}
    for x in strings:
        pos[x] = len(x)
    result = ""
    loop = True
    while loop:
        for x in strings:
            if pos[x] < 0:
                loop = False
        if not loop:
            break
        indr = None
        dr = 12777216
        for c in sigma:
            ind = defaultdict(int)
            for x in strings:
                indxc = indexes[x][c]
                if indxc:
                    i = find(indxc, pos[x] - 1)
                    ind[x] = indxc[i]
                    if ind[x] > pos[x] - 1:
                        ind[x] = -128
                else:
                    ind[x] = -128
            d = distance(ind, pos)
            if d < dr:
                indr = ind
                dr = d
        x = strings[0]
        def notnegative(p):
            r = True
            for x in p.values():
                if x < 0:
                    r = False
            return r
        if notnegative(indr):
            result = x[indr[x]] + result
        pos = indr
    return result

def check(string, seq):
    i = 0
    j = 0
    while i < len(string) and j < len(seq):
        if string[i] == seq[j]:
            j += 1
        i += 1
    return len(seq) - j

def checkall(strings, seq):
    for x in strings:
        a = check(x, seq)
        if not a == 0:
            print(x, seq, a)
            return False
    return True

strings = []
sigma = ["a", "b", "c", "d"]
#sigma = ["a", "b"]
sigmax = ["e", "f", "g"]
import random
Nx = 67
N = 128
M = 13 # Number of strings
x = ""
for i in range(Nx):
    x += random.choice(sigmax)
for i in range(M):
    string = ""
    for j in range(N):
        string += random.choice(sigma)
    indexes = list(range(N))
    random.shuffle(indexes)
    indexes = sorted(indexes[:len(x)])
    for j in range(len(x)):
        string = string[:indexes[j]]+x[j]+string[indexes[j]+1:]
    strings += [string]

#strings = ["abbab", "ababa", "abbba"]
#strings = ["abab", "baba", "abaa"]
#strings = ["bacda", "abcde", "decac"]
#strings = ["babbabbb", "bbbaabaa", "abbbabab", "abbababa"]
print("Strings:", strings)
l = mlcs(strings)
print("Lcs:", l, len(l), checkall(strings, l))


texts:
From K&R exercise 1-21,

  Write a program entab that replaces strings of blanks by the minimum
  number of tabs and blanks to achieve the same spacing. Use the same
  tab stops as for detab. When either a tab or a single blank would
  suffice to reach a tab stop, which should be given preference?

My solution:

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

#define MAXLEN  1000    // max line length
#define TABSTOP 8       // tabstop width

int get_line(char line[], int maxlen);
char * entab(char line[], int len);

int main(void)
{
    char line[MAXLEN];  // input line container
    char *entabbed;     // entabbed version of input line
    int len = 0;        // input line length
    int e_len = 0;      // entabbed line length

    while((len = get_line(line, MAXLEN)) > 0) {
        // produce entabbed version
        entabbed = entab(line, len);
        while (entabbed[e_len] != '\0') {
            e_len++;
        }

        // print entabbed version
        printf("%s", entabbed);
        if (entabbed[e_len-1] != '\n') {
            printf("\n");
        }

        free(entabbed);
    }

    return 0;
}

int get_line(char line[], int maxlen)
{
    int i = 0;  // current index
    int c;      // current character

    while (i < maxlen-1 && (c = getchar()) != EOF) {
        line[i++] = c;
        if (c == '\n') {
            break;
        }
    }
    line[i] = '\0';

    // clear input buffer of overflow
    if (i > 0 && line[i-1] != '\n') {
        while ((c = getchar()) != '\n' && c != EOF);
    }

    return i;
}

char * entab(char line[], int len)
{
    int i;          // index into original line
    int e;          // index into entabbed version
    int spaces;     // buffered whitespace counter
    char c;         // current char
    char *entabbed; // entabbed version

    e        = 0;
    spaces   = 0;
    entabbed = (char *) malloc(len * sizeof(char) + 1);

    for (i = 0; i < len; i++) {
        c = line[i];

        if (c == ' ') {
            if ((i+1) % TABSTOP == 0) {
                entabbed[e++] = '\t';
                spaces = 0;
            } else {
                spaces++;
            }
        } else {
            while (spaces > 0) {
                entabbed[e++] = ' ';
                spaces--;
            }

            entabbed[e++] = c;
        }
    }

    return entabbed;
}

I know there are probably more sophisticated ways of handling the input, but I've restricted myself to material covered by the first chapter of K&R.


texts:
The Challenge

  Accounting for Computer Machinists (ACM) has sufferred from the Y2K bug and lost some vital data for preparing annual report for MS Inc. All what they remember is that MS Inc.  posted a surplus or a deficit each month of 1999 and
  each month when MS Inc. posted surplus, the amount of surplus was
  s and each month when MS Inc. posted deficit, the deficit was d. They do not remember which or how many months posted surplus or deficit. MS Inc., unlike other companies, posts their earnings for each consecutive 5 months during a
  year.  ACM knows that each of these 8 postings reported a deficit but they do not know how much. The chief accountant is almost sure that MS Inc. was about to post surplus for the entire year of 1999.
  Almost but not quite.

  Write a program, which decides whether MS Inc. suffered a deficit during 1999, or if a surplus for 1999 was possible, what is the maximum amount of surplus that they can post.

  Input

  Input is a sequence of lines, each containing two positive integers
  s and d.

  Output

  For each line of input, output one line containing either a single integer giving the amount of surplus for the entire year, or output ‘Deficit’ if it is impossible.

  Sample Input

  59 237
  375 743
  200000 849694
  2500000 8000000

  Sample Output

  116
  28
  300612
  Deficit

My Solution

#include <iostream>
#include <climits>
#include <numeric>

int MONTHS_IN_A_YEAR = 12;
int post_of_month[12 + 1];
int ans;

int surplus, deficit;

void solve(int year_no, int prev_sum)
{
  // if year_no == 12, save the ans if it should be
  if ( year_no > MONTHS_IN_A_YEAR )
    {
      int total_sum = std::accumulate(post_of_month + 1,
                      post_of_month + MONTHS_IN_A_YEAR + 1, 0);
      if ( ans < total_sum )
        {
          ans = total_sum;
        }
      return;
    }

  if ( year_no > 5 )
    {
      prev_sum -= post_of_month[year_no - 5];
    }

  // try surplus for current year
  post_of_month[year_no] = surplus;
  if ( year_no < 5 ||
       (year_no >= 5 && prev_sum + post_of_month[year_no] < 0) )
    {
      solve(year_no + 1, prev_sum + post_of_month[year_no]);
    }

  // try deficit for current year
  post_of_month[year_no] = deficit;
  if ( year_no < 5 ||
       (year_no >= 5 && prev_sum + post_of_month[year_no] < 0) )
    {
      solve(year_no + 1, prev_sum + post_of_month[year_no]);
    }
}

int main()
{
  while ( std::cin >> surplus >> deficit )
    {
      deficit = -deficit;
      ans = INT_MIN;
      solve(1, 0);

      if ( ans > 0 )
        {
          std::cout << ans << std::endl;
        }
      else
        {
          std::cout << "Deficit" << std::endl;
        }
    }
  return 0;
}

Any suggestion in improving my code is welcome.


texts:
This is a LeetCode Problem

  You have a pile of stones presented as an array. On each turn you must merge k consecutive piles of stones, starting from any pile you wish. You must continue merging piles until you are left with one pile only. You must do this with minimum overall cost, where the cost is the sum of the ongoing cost plus the sum of all the piles being merged

  If this isn't possible, return -1. If this is possible, return the minimum overall cost

Example

  If k = 2 and the stones = [3,2,4,1]

  Round 1: Merge stones 3 and 2 => Cost = 5, stones = [5, 4, 1]

  Round 2: Merge stones 4 and 1 => Cost = 5 + (4+1) = 10, stones  = [5, 5]

  Round 3: Merge the piles 5 and 5 => Cost 10 + (5+5)= 20, stones = [10]

  The minimum overall cost is 20

My code is below. It runs into issues for large piles of stones such as

  stones = [29, 59, 31, 7, 51, 99, 47, 40, 24, 20, 98, 41, 42, 81, 92, 55]

  k = 2

How do I improve this code to quickly calculate the answer for large piles of stones?

Thank you

def helper(stones, k, count, min_count):
    # Basecase - if only one pile of stones, set minimum count to lowest value of current minimum and new minimum
    if len(stones) == 1:
        min_count = min(count, min_count)
        return min_count
    # Set last index
    last_index = len(stones) - k + 1
    for start in range(last_index):
        new_count = count + sum(stones[start:start + k])
        merged_count = sum(stones[start:start + k])
        new_list = stones[:start] + [merged_count] + stones[start + k:]
        min_count = helper(new_list, k, new_count, min_count)
    return min_count

def merge_stones(stones, k):
    lng = len(stones)
    # Verify if solution is possible
    if lng < k or (lng - 1) % (k - 1) != 0:
        return -1
    # Calculate solution
    minimum = helper(stones, k, 0, 99999999)
    # Return solution
    return minimum

if __name__ == "__main__":
    stones = [3, 2, 4, 1]
    k = 2
    print(merge_stones(stones, k))


texts: Eliminate axis-aligned bounding box (AABB) variables

texts:
I have an axis-aligned bounding box (AABB) that I've coded, but at the moment it is very redundant. I feel like there are variables that I can get rid of.  I need the AABB to be very fast, and I'd like it to be more lightweight than it is.

#pragma once

#include "Engine.h"
// Collision
#include "Vec2D.h"
// End Collision

#include "Renderer.h"

struct ENGINE_API AABB {
private:
    Vec2D min;
    Vec2D max;

    double x;
    double y;
    double width;
    double height;
    double xwidth; // x + width
    double yheight; // y + height

    double vertMid; // vertical mid, cached for quadtree
    double horzMid; // horizontal mid, cached for quadtree

    // Normalize
    void calcMid() {
        vertMid = x + (width / 2);
        horzMid = y + (height / 2);
        xwidth = x + width;
        yheight = y + height;
    }

    void init(Vec2D, Vec2D);
    // End Normalize
public:
    // Constructor
    AABB(Vec2D min, Vec2D max) {
        init(min, max);
    }

    AABB(double x, double y, double width, double height){
        init(Vec2D(x, y), Vec2D(x + width, y + height));
    }
    // End Constructor

    // Getters
    double getX()const {
        return x;
    }

    double getY()const {
        return y;
    }

    double getWidth()const {
        return width;
    }

    double getHeight()const {
        return height;
    }

    double getHorzMid()const {
        return horzMid;
    }

    double getVertMid()const {
        return vertMid;
    }

    double getXWidth()const {
        return xwidth;
    }

    double getYHeight()const {
        return yheight;
    }
    // End Getters

    // Base
    bool collides(AABB other) {
        if (xwidth < other.x || x > other.xwidth) { return false; }
        if (yheight < other.y || y > other.yheight) { return false; }

        return true;
    }

    bool contains(Vec2D point) {
        if (x > point.getX() || xwidth < point.getX()) { return false; }
        if (y > point.getY() || yheight < point.getY()) { return false; }

        return true;
    }

    void move(double x, double y) {
        this->x = x;
        this->y = y;
        calcMid();
    }
    // End Base
    // Testing
    void render(Renderer& renderer) {
        sf::RectangleShape shape;
        shape.setPosition(x, y);
        shape.setOutlineColor(sf::Color::Red);
        shape.setOutlineThickness(3);
        shape.setSize(sf::Vector2f(width, height));
        renderer.render(shape);
    }
    // End Testing
};

And the messy part:

void AABB::init(Vec2D one, Vec2D two) {
    double x1 = one.getX();
    double y1 = one.getY();
    double xx = two.getX();
    double yy = two.getY();

    if (x1 > xx) {
        if (y1 > yy) {
            min = Vec2D(xx, yy);
            max = Vec2D(x1, y1);
        }
        else {
            min = Vec2D(xx, y1);
            max = Vec2D(x1, yy);
        }
    }
    else {
        if (y1 > yy) {
            min = Vec2D(x1, yy);
            max = Vec2D(xx, y1);
        }
        else {
            min = Vec2D(x1, y1);
            max = Vec2D(xx, yy);
        }
    }

    x = min.getX();
    y = min.getY();
    width = max.getX() - x;
    height = max.getY() - y;

    calcMid();
}


texts:
In my Node.js applications, I often find it helpful to have an application log so that should something go wrong in production, I can have more information than I get from a crash stack trace to track down problems.

To facilitate this, I use a global instance of Winston which is set up as one of the first things in my code:

var winston = require('winston');

global.applog = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      timestamp: true,
      level: 'debug'
    })
  ]
});

I then call applog.debug(), applog.info(), applog.warn(), and applog.error() as appropriate throughout my code.  Even if I am in a class included from the main application, I will often send debug messages.

For my purposes, this works great.  I get the information I need to keep things running smoothly, and handle unexpected behaviors.  However:

This reduces the reuse of any lib code as it cannot stand on its own without having a reference to applog.
It doesn't feel like a best practice to have global references used inside modular object-oriented code.
I don't think I would ever use a log utility that didn't have the standard methods (debug, info, warn, error), but if I did switch away from Winston it's possible that all my code would need to be updated.

Is there a more appropriate pattern I should be following for logging?


texts: Given a string, print another one without a given char

texts:
My aim is to write a C program (I must create a function) that, given a string and a character, returns another string without the given char value.

For example: function("Hello World!", 'l'); /* Prints "Heo Word!" */

So I've programmed a lot with Java and I am used to programming but I am not used to C and in particular to pointers. I managed to do it with a single difference, this is the code:

#include <stdio.h>

#define STR_LEN 32

char *stringChop(char *s1, char *s2, char c);

int main() {
    char string[STR_LEN - 1] = "Esame di fondamenti";
    char stringChopped[STR_LEN - 1];
    stringChop(string, stringChopped, 'm');
    printf("%s\n\n", stringChopped);
    return 0;
}

char *stringChop(char *s1, char *s2, char c) {
    char *p = s1;
    char *q = s2;
    while (p < &s1[STR_LEN]) {
        if (*p != c) {
            *q = *p;
            p++;
            q++;
        } else {
            p++;
        }
    }
    return s2;
}

As you can see, in the function stringChop I've put 2 strings because I didn't know how to return one, so instead I used a pointer to one string initialised in the main() function and edited it with the use of pointers.
Now, my question is: How can I achieve the same thing with a function that accepts only one string and only a char value?


texts:
Given an array a, check to see if z numbers inside a total up to n.
If a = [1,2,3], n=3 and z=2, then this function should return true, since z numbers in that array combine to equal n.

I recently took a test for a job to fill out this function, and this was my answer. It was presumably rejected by the robots for being too slow, since one of the tests terminated with a timeout error.
var isSumPossible = function isSumPossible(a, n, z) {
  return +a.some(function (val, ix) {
    return z === 1 ? val === n : isSumPossible(a.slice(ix - 1, ix).concat(a.slice(ix + 1)), n - val, z - 1);
  });
};

How can this code be optimized to make it faster?