C++ equivalent of Python's deque with maxlen - sliding window In Python it is really easy to get sliding window functionality using a deque with maxlen:

from collections import deque
deck = deque(maxlen=4)
deck.append(0x01)
deck.append(0x02)
deck.append(0x03)
deck.append(0x04)
deck.append(0x05)
for item in deck:
    print(item)  # outputs 2, 3, 4, 5

This does two things - it grows until maxsize and then once maxsize has been reached items drop off the deque.

I wanted something similar in C++ and wrote the following (note, I know C++ has a deque, but I couldn't see how to reserve the size):

template <typename T>
auto rotate_push(std::vector<T> &container, const T& val) -> void
{
    if (container.size() < container.capacity()) {
        container.resize(deck.size() + 1);
    }
    else {
        std::rotate(container.begin(), container.begin() + 1, container.end());
    }

    container[container.size() - 1] = val;
}

auto deck = std::vector<int>();
deck.reserve(4);
rotate_push(deck, 1);
rotate_push(deck, 2);
rotate_push(deck, 3);
rotate_push(deck, 4);
rotate_push(deck, 5);

for (auto const &item : deck) {
    printf("%d\n", item); // outputs 2, 3, 4, 5
}

My Questions are:

Are the implementations basically equivalent (If not then why)
Is there a better custom implementation
Is there a easier/pre-existing implementation using STL
Is there a easier/pre-existing implementation using other
Is there a more performant implementation

Answers:

No, they have different push complexity [by Johnbot]
Use a free function or wrap std::deque [by Johnbot]
(Un-answered)
Boost Circular Buffer [by ratchet freak]
Circular Buffer [by ratchet freak]

You will get better performance using a ring buffer. (With an existing implementation in Boost)

This will keep an extra set of indexes into the buffer to specify the start and end of where the data is and wrap around automatically.


How to handle Throw exception + close connection I have a function that works with a database. If something wrong happens I want to throw an exception, and I also want that all resources have to be closed.

Is this a good way to do it? There is a better way to do it?

public Strint getStuff(Integer id) throws Exception {

    String result = "";

    Connection connection = db.openConection();
    ResultSet rs = null;

    try {
       // DO STUFF WITH DB
    } catch (Exception e) {
        throw e;
    } finally {
        rs.close();
        db.closeConection(connection);
    }
    return result;
}

You can skip catch part of try-catch-finally block
You should check that rs is not null


Building an SQL query string How can I write this PHP code better? It puts together an SQL query string from user input. The task is to return search results based on one or more text fields. The user can determine if partial matches are allowed.

$compop = $allowpartial ? "LIKE" : "="; // use LIKE for wildcard matching
$any = $allowpartial ? "%" : ""; // SQL uses % instead of * as wildcard

$namecondstr    = ($name === "")    ? "TRUE" : ("Name    $compop '$any$name$any'");
$citycondstr    = ($city === "")    ? "TRUE" : ("City    $compop '$any$city$any'");
$itemnocondstr  = ($itemno === "")  ? "TRUE" : ("ItemNo  $compop '$any$itemno$any'");
$ordernocondstr = ($orderno === "") ? "TRUE" : ("OrderNo $compop '$any$orderno$any'");
$serialcondstr  = ($serial === "")  ? "TRUE" : ("Serial  $compop '$any$serial$any'");

$sortstr = ($name !== "") ? "Name" :
           (($city !== "") ? "City" :
           (($itemno !== "") ? "ItemNo" :
           (($orderno !== "") ? "OrderNo" :
                                    "Serial")));

$query = "SELECT * From Licenses
          LEFT JOIN Items
            ON Licenses.LicenseID = Items.LicenseID
          WHERE $namecondstr
            AND $citycondstr
            AND $itemnocondstr
            AND $ordernocondstr
            AND $serialcondstr
          ORDER BY $sortstr, Licenses.LicenseID";

Use Prepared Statements

Your code is vulnerable to SQL injection attacks.  Use PDO or mysqli prepared statements to avoid this. See this answer for how to use PDO for this.  If you are using mysql_* you should know that it is already in the deprecation process.

Miscellaneous

Consider using empty to check for empty strings (see comment from Corbin below).
Personally I would use an if else rather than have two identical ternary conditions.


MergeSort performance Do you see any inefficient parts with the following code? On internet I see 30 ms for 100.000 integers but I can sort 100.000 integers in 300ms. The data is random. I am using late 2013 macbook pro so I don't expect a 10x slowdown from CPU, but who knows.

void mergesort2(int* list, int begin, int end,int *tmplist=0){
    bool allocated = false;
    if (end-begin < 1) {
        return;
    }
    if (tmplist == 0) {
        allocated = true;
        tmplist = new int[end-begin+1];
    }

    int middle = (begin+end)/2;

    mergesort2(list, begin, middle, tmplist);
    mergesort2(list, middle+1, end, tmplist);

    for (int first=begin, second=middle+1, tmp=0; tmp<end-begin+1; tmp++) {
        if (first > middle) {

            memcpy(tmplist+tmp, list+second, sizeof(int)*(end-begin-tmp+1));
        }
        else if (second > end) {
            memcpy(tmplist+tmp, list+first, sizeof(int)*(end-begin-tmp+1));

        }
        else if (list[first] <= list[second]) {
            tmplist[tmp] = list[first++];
        }else{
            tmplist[tmp] = list[second++];
        }
    }

    memcpy(list+begin, tmplist, (end-begin+1)*sizeof(int));

    if (allocated) {
        delete tmplist;
    }
}

A C++ merge sort in the style of a Standard Library algorithm could be written as

template<class BiDirIt, class Compare = std::less<typename std::iterator_traits<BiDirIt>::value_type>>
void merge_sort(BiDirIt first, BiDirIt last, Compare cmp = Compare())
{
        auto const N = std::distance(first, last);
        if (N < 2) return;
        auto middle = std::next(first, N / 2);
        merge_sort(first, middle, cmp);
        merge_sort(middle, last, cmp);
        std::inplace_merge(first, middle, last, cmp);
}

Let's look at how this improves upon your design:

generic interface: it takes two iterators and a comparison function of arbitrary types, instead of two indices into a pointer to an array of int and the implicit but fixed < comparison.
in-place: behind the covers it calls std::inplace_merge that can allocate extra memory but it does it so that users don't have to supply this, instead of your tmplist parameter.
half-open intervals: it will split the input range [first, last) into [first, middle) and [middle, last) which automically takes care of easy to make "off-by-one" errors in code like middle + 1 (in your code it is correct, but you still have to think about it, half-open intervals are easier to get right).
named algorithms: it uses std::inplace_merge as a ready-to-use component instead of a somewhat long and certainly tricky final step in your algorithm. Not only makes this your merge_sort more compact, the inplace_merge itself is a resuable component in its own right!
heavily optimized: Standard Library experts are very likely to know about the state of the art in writing performance-optimized algorithms. A factor of 10 of performance compared to your code seems a lot, but if you forget some hidden copies, use a hand-written loop that has O(N^2) complexity instead of O(N log N) you can quickly get there.


Mimicking classes with structs in C I'm trying to mimic classes. Is there anything with this code that I should not do with C or any ways that I can improve it at all, such as best practices or anything?

structs.h

#ifndef PLAYER_H
#define PLAYER_H

typedef struct  {
    char name[30];
    int damage;
    int durability;
} weapon;

typedef struct {
    int health;
    int armor_level;
    int currency;
    weapon player_weap;
} player;

#endif

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "structs.h"

player new_player();
void print_player(player user);

int main(void) {

    player user = new_player();
    print_player(user);

    return 0;
}

player new_player() {

    player new_player;
    new_player.health = 100;
    new_player.armor_level = 0;
    new_player.currency = 0;
    strcpy(new_player.player_weap.name, "Starter Sword");
    new_player.player_weap.damage = 1;
    new_player.player_weap.durability = 100;

    return new_player;

}

void print_player(player user) {
    printf("The players health is %d.\n", user.health);
    printf("The players armor is %d.\n", user.armor_level);
    printf("The players currency is %d.\n", user.currency);
    printf("The players weapon is the %s.\n", user.player_weap.name);
    printf("The players weapon does %d damage and has %d durability.\n", user.player_weap.damage, user.player_weap.durability);
}

It's pretty simple and readable as far as it goes, which is good. It doesn't do a whole lot but I have some comments that you might consider.

methods?

It's curious that you mention mimicking classes but there are no function pointers in the structs. In C it's more difficult to get the constructor in there, but print could be a function pointer.

typedef struct {
    //...
    void (*print)(struct player);
    //...
} player;

player new_player() {
    //...
    new_player.print = print_player;
    //...
}

int main(){
    //...
    user.print(user);
    //...
}

Initializers

C does have a nice initializer syntax, esp. with C99's designators. Your
constructor function could be somewhat nicer by using the initializer.

player new_player() {

    player new_player = {
    .health = 100,
    .armor_level = 0,
    .currency = 0,
    .player_weap = {
        .name = "Starter Sword",
        .damage = 1,
        .durability = 100
        }
    };

    return new_player;
}

Or even simpler with a compound literal.

player new_player() {
    return (player) {
    .health = 100,
    .armor_level = 0,
    .currency = 0,
    .player_weap = {
        .name = "Starter Sword",
        .damage = 1,
        .durability = 100
        }
    };
}


Determining if a string can be permuted to a palindrome I am going through Elements of Programming Interview by Aziz, Lee and Prakash one of the questions is how to determine if a string can be permuted to a palindrome. For example edified can be permuted to deified and now its a palindrome.

So my first implementation is this:

bool CanFormPalindrome(const string& s) {
    std::unordered_map<char, int> letter_count;
    for(char c : s) {
      letter_count[c]++;
    }

    int odd_letter_count = 0;
    for(std::pair<char, int> letter : letter_count) {
      if(letter.second%2 != 0) {
        odd_letter_count++;
      }
    }

    return odd_letter_count <= 1;
}

After I passed all the tests I saw the book's cleaner and sleeker implementation (compared to my implementation) which is:

bool CanFormPalindrome(const string& s) {
  std::unordered_set<char> char_counter;
  for(char c : s) {
    if(char_counter.count(c)) {
      char_counter.erase(c);
    }
    else {
      char_counter.insert(c);
    }
  }
  return char_counter.size() <= 1;
}

When I saw the time difference the tester timed my test at around 30 ms and the book's implementation at around 100 ms. I am wondering why my implementation is faster than the book's. My suspicion is that the calls to unordered_set's count, erase, and insert probably is the main bottle neck as opposed to just insert it just once and increment the value if it exists.

Another question is if you were to ask this on an interview would you care about the space time complexity over speed? Obviously the unordered_set is far more space efficient than the unordered_map, but if its for greater performance gain can we take up more space?

I much prefer your solution. It's easy to read and straightforward. The difference in size between the 2 is probably not that much. Their code has an unordered_set with a few elements in it. Your code has an unordered_map with likely 26 elements in it. We're talking about 26 * 5 = 130 bytes vs. say 5 or 10 bytes for the set on average. On modern systems, this is not a difference in memory usage. It's all below 1KB. If you're working with some old or oddball hardware and that becomes an issue, you can deal with it then.

However, if I were to see this code in production, I would probably want the following changes:

I would opt for using auto instead of the long type name in this line:

for(std::pair<char, int> letter : letter_count) {

I'd make it:

for(const auto& letter : letter_count) {

As mentioned in the discussion in the comments, making it a reference saves a copy of the pair and making it const lets a reader know that you aren't going to be modifying it.

I'd use more space between operators in the next line:

if(letter.second%2 != 0) {

would become:

if (letter.second % 2 != 0) {

It's just easier to read.

I might make that conditional into a named function just to make it clearer:

bool isOdd(const int x)
{
    return (x % 2) != 0
}

// ...
if  (isOdd(letter.second)) {


Menu traversing on next and prev button click up and down Can anyone optimize this code?  I am new to jQuery.

I want add class on next and previous button click.  I wrote this code that works for me, but could anyone optimize it using jQuery predefined methods?  That would be helpful.

$(document).ready(function () {
    var length = $('#slides li').size() - 1;
    var curren = 0;
    console.log(length);
    $('.next').on('click', function () {
        if (curren >= 0 && curren < length) {
            curren++;
            $('.selected').removeClass('selected');
            $('#slides li:eq(' + curren + ')').addClass('selected');
        }
    });
    $('.prev').on('click', function () {
        if (curren >= 1) {
            curren--;
            $('.selected').removeClass('selected');
            $('#slides li:eq(' + curren + ')').addClass('selected');
        }
    });
});

My HTML code:

first

second

third

fourth

five

six

CSS code:

.selected{
color:red;
}

There's not much in the way of predefined jQuery methods to add. Here's what I came up with though...

$(document).ready(function () {
    var $slides = $('#slides li'); //Save repeated selector result.
    var length = $slides.length - 1; //size is deprecated
    var curren = 0;
    console.log(length);
    // used .click due to personal preference .on('click', does the same thing
    $('.next').click(function () {
        if (curren < length) { //Removed check that will always be true
            curren++;
            changeSelected(curren); //Moved repeated code to function
        }
    });
    $('.prev').click(function () {
        if (curren >= 1) {
            curren--;
            changeSelected(curren);
        }
    });

    function changeSelected(index) {
        $('.selected').removeClass('selected');
        $slides.eq(index).addClass('selected'); //Use previously selected object
    }
});

Here's a link to the doc for .size() where you can find it is deprecated.


Remove value from linked list if it is equal to a parameter Problem: Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k.

My solution works, but I suspect it's not smart and optimized because I have many extra variables to solve this question.

Node.h:

#ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED

 template<typename T>
 struct ListNode {
   ListNode(const T &v) : value(v), next(nullptr) {}
   T value;
   ListNode *next;
};

#endif // NODE_H_INCLUDED

main.cpp:

#include<iostream>
#include "Node.h"

void print(ListNode<int> * l){
    while(l != nullptr){
        std::cout << l->value << "\n";
        l = l->next;
    }
}

ListNode<int> * removeKFromList(ListNode<int> * l, int k) {
    if(l == nullptr){
        return nullptr;
    }else{
        if(l->value != k){
            ListNode<int> * L2 = new ListNode<int>(l->value);
            ListNode<int> * current = L2;
            l = l->next;
            while(l != nullptr){
                if(l->value != k){
                    ListNode<int> * L3 = new ListNode<int>(l->value);
                    while(current->next != nullptr){
                        current = current->next;
                    }
                    current->next = L3;
                }
                l = l->next;
            }
            return L2;
        }else{
            return removeKFromList(l->next, k);
        }
    }
}

int main(){
    ListNode<int> * L = new ListNode<int>(5);
    ListNode<int> * L1 = new ListNode<int>(6);
    ListNode<int> * L2 = new ListNode<int>(8);
    L1->next = L2;
    L->next = L1;
    print(removeKFromList(L, 7));
    return 0;
}

Thank you for your interest in improving your code! Please, don't be confused about amount of comments. Programming is all about mastering your skills!

What's wrong with the code?

You leak memory!

For each call of new there must be a call for delete. Otherwise objects are not removed. Think of these operators as a C++ wrappers around malloc and free calls.

What could be improved?

Use T type in your methods

You used int k as a function argument, but an actual type you want is T. So it goes:

ListNode<T> * removeKFromList(ListNode<T> * l, T k)

Same for print method.

Use auto

When you change your signature to ListNode<T> notice, that using auto for statements, like

ListNode<int> *L2 = new ListNode<int>(node->value);

would not require any additional changes in the return types:

auto *L2 = new ListNode<T>(node->value);

It is common to use lowercase letters for variable names, even though you create all the list objects in uppercase.

Moreover, it looks nicer. But, do not overload your code with auto.
Use it only when it is obvious, what the type of your variable is.
So iterators, lambdas and new operators are the common case.

Variable & method names

Naming method removeKFromList suggests "remove key from the list", so we expect ListNode to contain pairs of key-value. It is confusing to see only T value in the struct, treated as a key in your methods. So it is better to rename method removeAllFromList. All here would stand for all occurrences. Do not use terms "key" and "value" together, unless you mean dictionary. Now:

ListNode<T> * removeAllFromList(ListNode<T> * l, T value)

It is considered a good practice to name variables in the way it makes sense what they stand for. Anyone should understand their meaning without reading more then couple of lines of code ahead. Ideally, write your code like a book. It wouldn't require much efforts. Try not to use variable names shorter then 3 symbols (except some particular cases, like in for-loop iteration):

ListNode<T> * removeAllFromList(ListNode<T> * list, T value)

Now we see another issue. If you pass ListNode<T> * it is actually a node, that is being passed by, but not the list. Fix:

ListNode<T> * removeAllFromList(ListNode<T> * node, T value)

const &

If integer instantiation is used, it is only a 4 bytes that are copied, so performance changes are unnoticeable. But since we use more complex classes, that would be an issue.
Use const & to fix this:

ListNode<T> *removeAllFromList(const ListNode<T> *node, const T &value)

Also make sure that nodes are not modified by writing const ListNode<T> *node

Style

Usually, it is hard to manually track all your spaces and tabulation. Use code refactoring tools. You sometimes mix styles by writing ) { and ){ with or without a space. We love perfection:)

Nesting levels

When you write:

if(l == nullptr){
    return nullptr;
}else{
   // ...
}

It is better to omit else body. That makes code more readable:

if (l == nullptr) {
    return nullptr;
}
   // ...

Reducing the amount of nested levels is good. And yes, use spaces.

File separation

ListNode methods are better placed in Node.cpp file, because they are relevant to ListNode.

Explicit

You may want to use explicit keyword to avoid unintentional type conversions.

What else could be improved?

Create LinkedList class

It is good to encapsulate your ListNode implementation. Hide your nodes, so no one could modify the values from outside, causing memory leaks or any kind of unintended behavior. It would also allow you to control memory by calling delete on each ListNode element in destructor.

There are more issues I may cover. But, please, start with those, provided above.
The method removeAllFromList could now look like this:

template<typename T>
shared_ptr<ListNode<T>> removeAllFromList(shared_ptr<ListNode<T>> node, const T &value) {
    if (node == nullptr) {
        return nullptr;
    }

    // The beginning node
    shared_ptr<ListNode<T>> root = nullptr;

    // Node used for iteration
    shared_ptr<ListNode<T>> current = nullptr;

    while (node != nullptr) {
        if (node->value == value) {
            node = node->next;
            continue;
        }
        if (root == nullptr) {
            root = std::make_shared<ListNode<T>>(node->value);
            current = root;
        } else {
            current->next = std::make_shared<ListNode<T>>(node->value);
            current = current->next;
        }

        node = node->next;
    }

    return root;
}

In my answer, I assume that you need to create a copy of the linked list and delete all the nodes with the value provided.


Filtering of maximum value by ID and category sum I have a task that is quite simple: I need to get the sum of values in the categories of each ID, and keep the category with the highest sum:
id    category   value
1       A         10
1       A         15
1       B         13
2       A         80

So, in this case the sum of value for each category-id pair would be:
id    category   value
1       A         25
1       B         13
2       A         80

And then the maximum for id == 1 is 25 and for the other is 80, so the final dataframe is:
id    category   value
1       A         25
2       A         80

I achieved this like this:
(df.groupby(['id', 'category'])['value']
 .sum().reset_index().sort_values(by=['id', 'value'])
 .drop_duplicates(['id'], keep='last'))

I feel this can be done in lesser steps, maybe with some transform, but I can't find a better way. Any ideas?
Thanks

You could also do the following. Compute the first grouping by id and category, sum up the values:
y = df.groupby(["id","category"])["value"].sum()

Afterwards, grab the best category according to your definition:
y.groupby("category").sum().nlargest(1)

Combining these, so that we get the full job done:
y = df.groupby(["id","category"])["value"].sum()
cat = y.groupby("category").sum().nlargest(1).index
y.loc[:,cat]


.Net 5.0 Get User Email From Claims From searching online I have identified two ways to get the user email, but I don't know if either has pro's/con's beyond Option.1 being a larger number of lines of code?
Option.1
I have a dedicated ClaimsPrincipalExtension.cs class, which I can call from anywhere in my app using var email = ClaimsPrincipalExtensions.GetLoggedInUserEmail(User);. Within which I have a method to get the email as shown:
using System;
using System.Security.Claims;

namespace FunctionalLogicLibrary {

public static class ClaimsPrincipalExtensions {
public static string GetLoggedInUserEmail(this ClaimsPrincipal principal) {
if (principal == null)
throw new ArgumentNullException(nameof(principal));
return principal.FindFirstValue(ClaimTypes.Email); }
 }
}

Option.2
I just add using System.Security.Claims; to any class where I need it and use
var email = User.FindFirstValue(ClaimTypes.Email);

I'm just trying to learn here. Which method is more appropriate and why?

I frequently write extension methods for IPrincipal and ClaimsPrincipal objects (depending on .NET framework version). Creating an abstraction for a business concept is a good idea, because it centralizes this knowledge (think: Single Source of Truth). If this happens to change in the future, you have one file, one method to modify. Option 1 is preferred, since it simplifies maintenance.
Some additional improvements:

Call extension methods from the object context: user.GetCurrentlyLoggedInUserEmail()
This is what extension methods are for. Take advantage of their syntactical sugar.

Do not duplicate concepts in the method name that already exist in the type it extends. This just makes method names too long for no added benefit: calling user.GetEmail() conveys the same information in a fraction of the characters.
Plus, "LoggedIn" is contextual, and assumes you are calling this on a ClaimsPrincipal that is the currently logged in user. This is not something the .NET type system enforces, so your method name should not make this assumption.


Avoiding multiple if conditions in a Car class In this dummy structure, we have a race car manager class. this class contains a method named execute().  There is a List which contains all participating racing cars.

This is the Car class, the List's type is based off:

public Car {

    private boolean driverBeltOn;
    private boolean engineOn;

    public boolean engineReady() {
        return this.engineOn;
    }

    public boolean driverBeltOn() {
        return this.driverBeltOn;
    }

    public void warn(String message) {
        // Send warning to car
        // ....
        // .....  (<;D>-<;
        // ......
    }
}

The job of the execute method, is to loop through all cars, and make sure they are ready for the race, but if at-least one of the two conditions is false, then the car will not  participate in the race.

If one condition is false, then the car should be notified, about why it can't participate.

Basic solution:

public void execute() {
    for (Car car : carList) {
        if (car.engineOn()) {
            if (car.driverBeltOn()) {
                // Can go..
            }
            else {
                car.warn("Please wear a damn belt!");
            }
        }
        else {
            car.warn("How are you planning to participate in a race with an off engine??");
        }
    }
}

What is the best way to handle things like this, where you have to check multiple conditions, and each condition should do something if it's false in the check?

Example of a bad solution, because it's impossible to let the car know what's wrong:

public void execute() {
    for (Car car : carList) {
        if (car.engineOn() && car.driverBeltOn()) {
            // Can go..
        }
        else {
            car.warn("Something went wrong...");
        }
    }
}

Unless you add multiple checks inside the else block, which could be double work/bad practice.

What is the best practice do handle this? Or if inside if for this case is totally fine?

If you don't want to return early (because you want to go through all checks to warn about all problems), then you can use a flag to keep track of any problems:

for (Car car : carList) {
    boolean goodToGo = true;
    if (!car.engineOn()) {
        car.warn("How are you planning to participate in a race with an off engine??");
        goodToGo = false;
    }
    if (!car.driverBeltOn()) {
        car.warn("Please wear a damn belt!");
        goodToGo = false;
    }
    if (goodToGo) {
        // Vroooomm....
    }
}

Btw, I guess you forgot a return statement here:

public boolean driverBeltOn() {
    this.driverBeltOn;
}

And I recommend to rename your methods to isDriverBeltOn and isEngineReady, as it's a fairly common practice to prefix boolean getters with "is...".


Export class instances to a string (for sharing, backup) and importing them I have a class (Patient) with many instances.. I need a way to share the instances with other users, so I thought of converting the instance into a string and sharing it, then reconverting it into an instance

From instance to string

func ToString(pt: Patient) -> String {
    let myarray: [String] = [
        pt.id,
        pt.name,
        String(pt.age),
        pt.address,
        pt.tele,
        pt.notes,
        dateToString(pt.date),
        pt.history,
        pt.diagnosis,
        (pt.investigations.map {$0.name + "{|}" + $0.value}).joinWithSeparator("{|X|}"),
        (pt.treatments.map {$0.name + "{|}" + $0.dose}).joinWithSeparator("{|X|}"),
        (pt.images.map {$0.imagePath + "{|}" + $0.caption}).joinWithSeparator("{|X|}")
    ]

    return myarray.joinWithSeparator("{|NEWLINE|}")
}

From string to instance

func FromString(mystring: String) {
    let pt = Patient()

    let ptarray = mystring.componentsSeparatedByString("{|NEWLINE|}")
    let ixarray = ptarray[9].componentsSeparatedByString("{|X|}")
    let rxarray = ptarray[10].componentsSeparatedByString("{|X|}")
    let photoarray = ptarray[11].componentsSeparatedByString("{|X|}")
    let ixcarray = ixarray.map { Investigation(name: $0.componentsSeparatedByString("{|}")[0], value: $0.componentsSeparatedByString("{|}")[1]) }
    let rxcarray = rxarray.map { Treatment(name: $0.componentsSeparatedByString("{|}")[0], dose: $0.componentsSeparatedByString("{|}")[1]) }
    let photocarray = photoarray.map { Pic(imagePath: $0.componentsSeparatedByString("{|}")[0], caption: $0.componentsSeparatedByString("{|}")[1]) }

    pt.id = ptarray[0]
    pt.name = ptarray[1]
    pt.age = Int(ptarray[2]) ?? -1
    pt.address = ptarray[3]
    pt.tele = ptarray[4]
    pt.notes = ptarray[5]
    pt.date = stringToDate(ptarray[6])
    pt.history = ptarray[7]
    pt.diagnosis = ptarray[8]

    pt.savePatient()

    _ = ixcarray.map { x in pt.addInvestigation(x) }
    _ = rxcarray.map { x in pt.addTreatment(x) }
    _ = photocarray.map { x in pt.addImage(x) }
}

Notes:

investigation, treatment, and images are array of classes with two properties
I used "|" as a separator because I disabled it in my app so the user can't interfere with my functions
I use Realm in my app for data persistance
My specific concern is performance issues because thousands of instances may be shared at once

I don't see a question here, but I think I understand your concerns...

Regarding performance - I don't think you need to worry. Note that JSON and XML exist, in part, as formats for transmitting objects between apps in a platform independent way and there isn't a whole lot of worries about performance with either of them.

That said, I suggest you use one of these standard data interchange formats rather than trying to invent your own. Both JSON and XML already have very efficient and OS provided functions for doing the conversion...

extension Patient {
    init(dictionary dict: [String: AnyObject]) {
        id = dict["id"] as! String
        name = dict["name"] as! String
        age = dict["age"] as! Int
        // etc...
    }

    var dictionary: [String: AnyObject] {
        var dict: [String: AnyObject] = [:]
        dict["id"] = id
        dict["name"] = name
        dict["age"] = age
        // etc...
        return dict
    }
}

Once you have the above, you can easily convert a Patient to and from a Dictionary object and once you have that, you can use Apple's methods to convert the dictionary to/from either JSON or XML depending on what you like best.

You might also want to consider using SwiftyJSON instead of [String: AnyObject] dictionaries.


Calculating triangular numbers A triangular number is a product of three factors as follows:

$$
\text{Triangular number} = x(x + 1)(x + 2)
$$

Is there a way to make this code faster? As it is the code calculates every triangular number less than or equal to the integer given by the user.

#include <stdio.h>

int main(void) {

    int firstFactor = 0;
    int secondFactor = 1;
    int thirdFactor = 2;

    int userInput;
    int product = 0;

    printf("Enter a integer: ");
    scanf("%d", &userInput);

    if(userInput == 0) {
        printf("User input is a triangular number\n");
        return 0;
    }

    do {
        firstFactor++;
        secondFactor++;
        thirdFactor++;
        product = firstFactor * secondFactor * thirdFactor;
    } while(product < userInput);

    if(product == userInput) {
        printf("User input is a triangular number\n");
    } else {
        printf("User input is not a triangular number\n");
    }
    return 0;
}

I see a couple of ways to speed this up.

Observe that at least one factor is even, and exactly one factor is a multiple of 3, so these numbers are all divisible by 6. Assuming random input, testing for that at the beginning will find the answer in one inexpensive operation in 5 out of 6 cases:

if (userInput % 6) {
    printf("User input is not a triangular number\n");
    return 0;
}

As for the rest of it, if we set n = x + 1, we get

$$T(n-1)=(n-1)(n)(n+1)=n^3-n$$

Thus, we can solve in O(1) time, though the cube root is a somewhat expensive operation:

#include <math.h>    /* Link with -lm in gcc */

int n;

n = (int) (ceil(cbrt(userInput)) + 0.1);
if (n * (n-1) * (n+1) == userInput)
    printf("User input is a triangular number\n");
else
    printf("User input is not a triangular number\n");

We add 0.1 after the ceil because the double value might be something like 6.9999999999759, which would round to the wrong number when converted to int. The (int) cast suppresses a compiler warning about conversion from double to int.


Converting to and from Roman numerals I wrote a simple Boot script for converting to and from Roman numerals using instaparse. Here's my EBNF grammar (roman.bnf):

number = thousands hundreds tens ones

I = 'I'
V = 'V'
X = 'X'
L = 'L'
C = 'C'
D = 'D'
M = 'M'

IV = 'IV'
IX = 'IX'
XL = 'XL'
XC = 'XC'
CD = 'CD'
CM = 'CM'

ones = V? I? I? I? | IV | IX
tens = L? X? X? X? | XL | XC
hundreds = D? C? C? C? | CD | CM
thousands = M? M? M?

And here's the Boot script itself (roman.clj):

#!/usr/bin/env boot

(set-env! :dependencies '[[instaparse "1.4.5"]])

(require '[boot.cli :as cli]
         '[instaparse.core :as insta])

(defn digits
  "Returns a lazy sequence of the digits of n in the specified base, starting
  with the least significant digit."
  [base n]
  (->> (iterate #(quot % base) n)
       (take-while pos?)
       (map #(mod % base))))

(defn int->roman
  "Returns the Roman numeral representation of n."
  [n]
  (let [[ones tens hundreds thousands] (concat (digits 10 n) (repeat 0))]
    (->> (letfn [(digit [one five ten n]
                   (case n
                     4 [one five]
                     9 [one ten]
                     (cons (when (<= 5 n) five)
                           (repeat (mod n 5) one))))]
           [(repeat thousands "M")
            (digit "C" "D" "M" hundreds)
            (digit "X" "L" "C" tens)
            (digit "I" "V" "X" ones)])
         (apply concat)
         (apply str))))

(def parser (insta/parser (slurp "roman.bnf")))

(def symbols
  {:I 1 :V 5 :X 10 :L 50 :C 100 :D 500 :M 1000
   :IV 4 :IX 9 :XL 40 :XC 90 :CD 400 :CM 900})

(defn roman->int
  "Converts the Roman numeral string s to an integer."
  [s]
  (let [parsed (parser s)]
    (if-some [failure (insta/get-failure parsed)]
      failure
      (->> (rest parsed)
           (mapcat rest)
           (map first)
           (map symbols)
           (apply +)))))

(cli/defclifn -main
  "Converts to and from Roman numerals."
  [t to ARABIC int "The number to convert to a Roman numeral."
   f from ROMAN str "The number to convert to an Arabic numeral."]
  (cond
    (and to from) (println "Please choose only one conversion.")
    to (println (if (< 0 to 4000) (int->roman to) "Out of range."))
    from
    (let [result (roman->int from)]
      ((if (insta/failure? result) print println) result))))

Here are some examples (test.sh):

./roman.clj -t 1
./roman.clj -t 52
./roman.clj -t 294
./roman.clj -t 2780
./roman.clj -f IX
./roman.clj -f LXIX
./roman.clj -f CCXCV
./roman.clj -f MMDCLXXXII

$ chmod +x roman.clj
$ chmod +x test.sh
$ ./test.sh
I
LII
CCXCIV
MMDCCLXXX
9
69
295
2682

Obviously this is completely impractical due to Clojure's startup time, but meh.

Are there any improvements I can make? I'm especially interested in ways to make the grammar more elegant; for instance, I can't seem to find a good way to remove the repetition in I? I? I? etc., but if there is a way to genericize the maximum number of occurrences, that would be cool. Any improvements on the Clojure side of things would also be most welcome.

Looking at int->roman ...

It simply ignores digits that are too big. 10000 maps to ""!
Surely better to repeat the biggest signifier as often as necessary.
The logic for the  one five ten units for digit is in your head. We can derive them from a list of the symbols in increasing order. And it's easier to wrap them as a single argument to digit.
I've done the string concatenation within digit.
I've dumped the base argument and done the digit-ising inline.

For what it's worth ...

(def symbols "IVXLCDM")

(defn digit [[one five ten] n]
  (let [chars (case n
                4 [one five]
                9 [one ten]
                (cons (when (<= 5 n) five)
                      (repeat (mod n 5) one)))]
    (apply str chars)))

(defn int->roman
  "Returns the Roman numeral representation of n."
  [n]
  {:pre [(integer? n) (pos? n) (odd? (count symbols))]}
  (let [triples (partition 3 2 symbols)
        heads (->> n (iterate #(quot % 10)))
        digits (map (fn [t i] (digit t (mod i 10))) triples heads)
        left-over (nth heads (count triples))
        left-overs (->> (last symbols)
                        (repeat left-over)
                        (apply str))]
    left-over
    (->> (concat digits left-overs)
         reverse
         (apply str))))

For example,

(int->roman 11976)
;"MMMMMMMMMMMCMLXXVI"

It could be made faster as a big fat reduce, but I prefer it slow and fairly clear. It gave me enough trouble!


A recursive sort and filter for a nested object I have a nested object which I need to filter and sort.

I have a nested Object where some keys like app1 are nested inside another object.
I need to be able to filter out objects with the status of True.
I also need to be able to sort by date irrespective of how deep the object is nested.

This is the expected result.

[
  "appsd",
  {
    "appsf": {
      "date": "2017-01-05T17:13:53.956Z",
      "status": false
    }
  }
] [
  "appse",
  {
    "apps1": {
      "date": "2017-02-05T17:13:53.956Z",
      "status": false
    }
  }
] [
  "apps5",
  {
    "date": "2017-03-11T15:15:39.027Z",
    "status": false
  }
] [
  "apps4",
  {
    "date": "2017-04-11T15:15:39.027Z",
    "status": false
  }
] [
  "apps2",
  {
    "date": "2017-05-11T15:15:39.027Z",
    "status": false
  }
] [
  "appsf",
  {
    "apps1": {
      "date": "2017-07-05T17:13:53.956Z",
      "status": false
    }
  }
] [
  "appb",
  {
    "apps1": {
      "date": "2017-08-05T17:13:53.956Z",
      "status": false
    }
  }
] [
  "appsa",
  {
    "apps1": {
      "date": "2017-09-05T17:13:53.956Z",
      "status": false
    }
  }
]

From this original object

var object = {
  appsa: {
    apps1: {
      date: "2017-09-05T17:13:53.956Z",
      status: false
    }
  },
  appb: {
    apps1: {
      date: "2017-08-05T17:13:53.956Z",
      status: false
    }
  },
    appsf: {
    apps1: {
      date: "2017-07-05T17:13:53.956Z",
      status: false
    }
  },
  apps2: {
    date: "2017-05-11T15:15:39.027Z",
    status: false
  },

  apps3: {
    date: "2017-06-11T15:36:33.063Z",
    status: true
  },
  apps4: {
    date: "2017-04-11T15:15:39.027Z",
    status: false
  },
  apps5: {
    date: "2017-03-11T15:15:39.027Z",
    status: false
  },
   appse: {
    apps1: {
      date: "2017-02-05T17:13:53.956Z",
      status: false
    }
  },
   appsd: {
    appsf: {
      date: "2017-01-05T17:13:53.956Z",
      status: false
    }
  },
};

Concerns about my code.

recursive style.
pushing order and deeply nested object
am also not doing any recursion on the filter.
variable naming efficiency and clarity

var object = {
  appsa: {
    apps1: {
      date: "2017-09-05T17:13:53.956Z",
      status: false
    }
  },
  appb: {
    apps1: {
      date: "2017-08-05T17:13:53.956Z",
      status: false
    }
  },
  appsf: {
    apps1: {
      date: "2017-07-05T17:13:53.956Z",
      status: false
    }
  },
  apps2: {
    date: "2017-05-11T15:15:39.027Z",
    status: false
  },

  apps3: {
    date: "2017-06-11T15:36:33.063Z",
    status: true
  },
  apps4: {
    date: "2017-04-11T15:15:39.027Z",
    status: false
  },
  apps5: {
    date: "2017-03-11T15:15:39.027Z",
    status: false
  },
  appse: {
    apps1: {
      date: "2017-02-05T17:13:53.956Z",
      status: false
    }
  },
  appsd: {
    appsf: {
      date: "2017-01-05T17:13:53.956Z",
      status: false
    }
  },
};

let apps = Object.entries(object)
  .filter(([key, value]) => !value.status)
  .sort((val=> (a, b) => {
    let temp = [];
    let sortMatch = root => {
      if (root.date) {
        temp.push(root.date);
      }
      for (let key in root) {
        if (typeof root[key] === "object") {
          sortMatch(root[key]);
        }
      }
    };
    sortMatch({
      a: a,
      b: b
    });
    val['tempB'] = temp.pop();
    val['tempA'] = temp.pop();
    return val.tempA.localeCompare(val.tempB);
  })({}));

console.log(...apps);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

If you have control over the format of the object you're filtering and sorting, then you should definitely consider reformatting it into something more palatable.
Using localeCompare() to sort Date objects seems funky. You can do something like this:

return new Date(tempB).getTime() - new Date(tempA).getTime()

If you don't know how deep the object is nested, then recursion is a pretty solid way to go. If you want to try a more hackish solution, you could also use JSON.stringify() and regex to extract the date fields from deeply nested objects (not suggested). Please provide more examples of valid objects to sort though, your code seems like it would break on certain instances.


Simple temperature converter in C I have just begun to learn the C language and wanted to start off small with a temperature conversion calculator. The program works, and I'm looking for feedback on do's and don'ts as I am sure there are at least a few errors in technique that can be improved. (I just realized Fahrenheit is spelled incorrectly).

/*Calculates user provided temperature in Farenheight or Celsius depending on option chosen.*/

#include "stdafx.h" //don't actually know what this is for however will not compile without it.
#include <stdio.h>
#include <stdBool.h>
#include <conio.h>

/*Calculator options*/
#define option_1 1
#define option_2 2
#define option_3 3
#define option_4 4

void welcome();
void calculator();
void get_input(_Bool*, int*, float*);
void display_result(int, float);
float F_to_C(float);
float C_to_F(float);

int main(void)
{
    welcome();
    calculator();
    _getch();
}

void welcome() /*Welcome message + instruction*/
{
    printf("Welcome to the Temperaure Conversion Calculator\n\n");
    printf("Please select an option:\n\n");
    printf("Options:\t1)F to C\t2)C to F\t3)OFF\n\n");
}

void calculator() /*Conversion Calclator*/
{
    int option = 0;
    float input_temp = 0.0f;
    _Bool calc_off = 0;

    while (!calc_off)

    {
        get_input(&calc_off, &option, &input_temp);

        if (option == option_1) /*F to C*/
        {
            display_result(option_1, input_temp);
        }
        else if (option == option_2) /*C to F*/
        {
            display_result(option_2, input_temp);
        }
    }

}

void get_input(_Bool *calc_off, int *option, float *input_temp) /*Retrieve user input*/
{
    int trash = 0;
    int data_check;
    printf("Select option: "); scanf_s("%d", option); /*Obtains option*/
    scanf_s("%c", &trash); /*obtains newline character that will cause infinite loop*/

    while (*option != 1 && *option != 2 && *option != 3) /*incorrect option selection*/
    {
        display_result(option_4, option_4);
        scanf_s("%d", option);
        scanf_s("%c", &trash); /*Collects garbage newline character (Prevents infinite loop)*/

    }

    if (*option == option_3) /*Calculator off*/
    {
        *calc_off = 1;
        display_result(option_3, option_3);
        return;
    }

    printf("Temperature: "); scanf_s("%f", input_temp); /*Obtains temperature*/

    return;
}

void display_result(int option, float input_temp) /*Display results*/
{
    if (option == option_1)
        printf("Farenheight to Celsius of %.1f F is: %.1f C\n", input_temp, F_to_C(input_temp));

    else if (option == option_2)
        printf("Celsius to Farenheight of %.1f F is: %.1f F\n", input_temp, C_to_F(input_temp));

    else if (option == option_3)
        printf("Calculator OFF\n");

    else if (option == option_4)
        printf("Invalid option choice, please try again...\nOption: ");
}

float F_to_C(float input_temp) /*Convert Farenheight to Celsius*/
{
    return (5.0 / 9.0)*(input_temp - 32);
}

float C_to_F(float input_temp) /*Convert Celsius to Farenheight*/
{
    return (9.0 / 5.0)*(input_temp)+32;
}

Use an enum instead of #define. So instead of:

#define option_1 1
#define option_2 2
#define option_3 3
#define option_4 4

You can use enum:

enum {F_to_C, C_to_F, Off} option_type; // I am leaving off the fourth option!

You will also have to modify other portions of your code to use enums.

Stop using so many if statements. Use switch-case statements instead. There are a few places that you do this in your code but for example:

if (option == option_1)
    printf("Farenheight to Celsius of %.1f F is: %.1f C\n", input_temp, F_to_C(input_temp));

else if (option == option_2)
    printf("Celsius to Farenheight of %.1f F is: %.1f F\n", input_temp, C_to_F(input_temp));

else if (option == option_3)
    printf("Calculator OFF\n");

else if (option == option_4)
    printf("Invalid option choice, please try again...\nOption: ");

Instead:

switch(option) {
    case F_to_C:
        printf("Farenheight to Celsius of %.1f F is: %.1f C\n", input_temp, F_to_C(input_temp));
        break;
     ...
     default:
         printf("Invalid option choice, please try again...\nOption: ");
         break;

Notice that we have a default. You can give garbage as option_4, more than just the value 4. You should try handling this best you can.

Don't use _Bool! Just use bool and use true and false instead of 1 and 0. So this:

_Bool calc_off = 0;

Should be:

bool calc_off = false;

But actually I don't really believe you need calc_off because you use pointers unnecessarily.

This:

int option = 0;
float input_temp = 0.0f;
_Bool calc_off = 0;

while (!calc_off)

{
    get_input(&calc_off, &option, &input_temp);

    if (option == option_1) /*F to C*/ // Rewrite this to use switch case!
    {
        display_result(option_1, input_temp);
    }
    else if (option == option_2) /*C to F*/
    {
        display_result(option_2, input_temp);
    }
}

get_input in particular is troublesome.

Why not let get_input return an option? then:

while((option = get_input(...)) != Off) {


Parallel extension enchancement As suggested in comments here I created a new topic for next version. I edited a bit original code, added exception processing and optimization, that first N = 1/core count tasks are processed on main thread.

public static void Foreach<T>(ICollection<T> source, Action<T> action)
{
    var toBeProcessedOnMainThread = (int) Math.Ceiling((double)source.Count / Environment.ProcessorCount);
    var countdown = new CountdownEvent(source.Count - toBeProcessedOnMainThread);
    ConcurrentBag<Exception> exceptionsBag = null;
    var onMainThread = source.Take(toBeProcessedOnMainThread);
    foreach (var item in source.Skip(toBeProcessedOnMainThread))
    {
        ThreadPool.QueueUserWorkItem(state =>
        {
            var closure = (T)state;
            try
            {
                action(closure);
            }
            catch (Exception ex)
            {
                HandleException(ref exceptionsBag, countdown, ex);
            }
            finally
            {
                countdown.Signal();
            }
        }, item);
    }
    foreach (T value in onMainThread)
    {
        try
        {
            action(value);
        }
        catch (Exception ex)
        {
            HandleException(ref exceptionsBag, countdown, ex);
        }
    }
    countdown.Wait();
    if (exceptionsBag != null)
        throw new AggregateException(exceptionsBag);
}

private static void HandleException(ref ConcurrentBag<Exception> exceptions, object syncRoot, Exception ex)
{
    if (exceptions == null)
        lock (syncRoot)
            if (exceptions == null)
                exceptions = new ConcurrentBag<Exception>();

    exceptions.Add(ex);
}

I do lock countdown because I do not want to introduce another local variable, and it locks only once and only if exception occurs. Normally it won't be called an thus won't be locked.

RubberDuck is right. It looks like you are reinventing the wheel. Unless you are doing this whole thing for educational purposes, you should rather use TPL. ForEach method does exactly what you are trying to do and most likely does a better job at splitting processing power between the tasks:

Parallel.ForEach(source, action);

Regarding your implementation: CountdownEvent implements IDisposable, so you should dispose it after you are done using it. Or wrap it into a using block.

Also this code is the kind of micro-optimization you should avoid:

if (exceptions == null)
    lock (syncRoot)
        if (exceptions == null)
            exceptions = new ConcurrentBag<Exception>();

Is new ConcurrentBag call a bottleneack of this method? Does it take anywhere near as much resources as calling an Action method? "No? Then don't introduce additional concurrency!" :)  Just call ConcurrentBag<Exception> exceptionsBag = new ConcurrentBag<Exception>(); and forget about synchronization. Or at least follow Eric's advice in above link and use Lazy<T>.


Rotating greyscale images For educational purposes I wrote a little piece of code to rotate greyscale images as "low level" as possible, that is, not using any rotate() function, but doing the math. I was wondering if it could be improved in any way, specially in order to achieve better performance. I'm not concerned with the libraries or the programming language chosen to perform this task, I am aware that they aren't the best option if what I want is performance. I'm only concerned with the code itself.

It basically maps the pixels on the new image to the ones in the original image and interpolates using nearest neighbor or bilenear.

def affine_t(x, y, a, b, c, d, e, f):
    # A lot faster than numpy.dot([[a,b],[c,d]],[x,y])+[e,f]
    return round(a*x + b*y + e, 3), round(c*x + d*y + f, 3)

def mrotate(r, cx=0, cy=0):
    # Returns the coefficients to an affine transformation which rotates
    # a point clockwise by r radians in respect to a central point. For counter
    # clockwise, just pass r as -r.
    return (math.cos(r), -math.sin(r), math.sin(r), math.cos(r), cx, cy)

def lin_interp(x, x0, x1, y0, y1):
    # Faster than numpy.interp()
    return y0 + (y1 - y0)*((x-x0)/(x1-x0))

def bilinear(bmp, ox, oy):
    # Try to interpolate. If the pixel falls on the image boundary, use the
    # nearest pixel value (nearest neighbor).
    try:
        x0, x1, y0, y1 = int(ox), int(ox)+1, int(oy), int(oy)+1
        a = lin_interp(ox, x0, x1, bmp[y0][x0], bmp[y0][x1])
        b = lin_interp(ox, x0, x1, bmp[y1][x0], bmp[y1][x1])
    except IndexError:
        return nn(bmp, ox, oy)
    return int(lin_interp(oy, y0, y1, a, b))

def nn(bmp, ox, oy):
    return bmp[oy][ox] # bmp is numpy.array, it casts float indexes to int

def rotate(bmp, r, mx=0, my=0, filename=None, interpol=None):
    """Rotate bitmap bmp r radians clockwise from the center. Move it mx, my."""

    # Get the bitmap's original dimensions and calculate the new ones
    oh, ow = len(bmp), len(bmp[0])
    nwl = ow * math.cos(r)
    nwr = oh * math.sin(r)
    nhl = ow * math.sin(r)
    nhu = oh * math.cos(r)
    nw, nh = int(math.ceil(nwl + nwr)), int(math.ceil(nhl+nhu))
    cx, cy = ow/2.0 - 0.5, oh/2.0 - 0.5 # The center of the image
    # Some rotations yield pixels offscren. They will be mapped anyway, so if
    # the user moves the image he gets what was offscreen.
    xoffset, yoffset = int(math.ceil((ow-nw)/2.0)), int(math.ceil((oh-nh)/2.0))
    for x in xrange(xoffset,nw):
        for y in xrange(yoffset,nh):
            ox, oy = affine_t(x-cx, y-cy, *mrotate(-r, cx, cy))
            if ox > -1 and ox < ow and oy > -1 and oy < oh:
                pt = bilinear(bmp, ox, oy) if interpol else nn(bmp, ox, oy)
                draw.point([(x+mx,y+my),],fill=pt)
    if filename is not None:
        im.save(filename)

The complete code, used to generate the examples below:

http://pastebin.com/2j7BQyzi

Some example rotations, first image is the original, to the left is one rotated 90 degrees and the one below is rotated 45 degrees.

Using Nearest Neighbors:

Using Bilinear:

Note: The original "Lenna.png" image was first resized to 0.5 the original size using bilinear interpolation and flatten to a greyscale.

1. Comments on your code

For most of your functions, you've written a comment describing what it does. It's usual in Python to put this in a docstring, so that a user can get at it from the interactive interpreter using the help function.
The function rotate relies on a global variable draw. This makes it hard to reuse and test. (And you couldn't use it in a multi-threaded program.)
The function rotate carries out multiple tasks: it rotates the bitmap; translates it; draws the result to an Image object; and saves it to a file. It would make the code easier to use and more general if you separated these functions.
The comments suggest that you have not understood how to use NumPy. For example, you write that your function lin_interp is "Faster than numpy.interp()". Which no doubt it is for the case of a single point. But when properly vectorized, NumPy will beat pure Python.

For a very simple example, consider a pure-Python implementation of the dot product operation:

def dot(v, w):
    return sum(x * y for x, y in zip(v, w))

Let's compare the speed with numpy.dot. The pure-Python version is substantially faster for very small arrays:

>>> import numpy as np
>>> from timeit import timeit
>>> timeit(lambda:dot([1, 2], [3, 4]))
2.1183970817364752
>>> timeit(lambda:np.dot([1, 2], [3, 4]))
11.150392828974873

but the NumPy version is hundreds of times faster for large arrays:

>>> v = np.arange(1000)
>>> w = np.arange(1000)
>>> timeit(lambda:dot(v, w), number=1000)
1.4182810601778328
>>> timeit(lambda:np.dot(v, w), number=1000)
0.0053491611033678055

So in order to get a performance benefit out of NumPy, you have to vectorize your algorithm so that each step of the algorithm operates on many elements simultaneously.
Here's another example. In this extract you iterate over a grid of coordinates (x, y) and rotate each coordinate by −r radians about the point (cx, cy):

for x in xrange(xoffset,nw):
    for y in xrange(yoffset,nh):
        ox, oy = affine_t(x-cx, y-cy, *mrotate(-r, cx, cy))

Let's put that in a function for timing purposes:

def rotate1(a, theta, ox, oy):
    """Rotate array of 2-dimensional coordinates by theta radians about
    the point (ox, oy).

    """
    for x, y in a:
        affine_t(x-ox, y-oy, *mrotate(theta, ox, oy))

To be as generous as possible with the timing results, I haven't even attempted to store or return a result. Let's try that out on an array of a million coordinates:

>>> grid = np.meshgrid(np.arange(1000), np.arange(1000))
>>> coords = np.vstack(grid).reshape(2, -1).T
>>> timeit(lambda:rotate1(coords, np.pi / 4, 500, 500), number=1)
94.44321689195931

Here's how the same operation looks when vectorized:

def rotate2(x, y, theta, ox, oy):
    """Rotate arrays of coordinates x and y by theta radians about the
    point (ox, oy).

    """
    s, c = np.sin(theta), np.cos(theta)
    x, y = x - ox, y - oy
    return x * c - y * s + ox, x * s + y * c + oy

Instead of looping over the coordinates and applying all the stages of the  transformation to one coordinate at a time, we apply each stage of the transformation to all the coordinates simultaneously.

>>> timeit(lambda:rotate2(grid[0], grid[1], np.pi / 4, 500, 500), number=1)
0.06842728098854423

So although your comment says that affine_t is "A lot faster than numpy", in fact, when properly vectorized, NumPy runs more than 1300 times faster.

2. Revised code

If I was doing this for real, then obviously I'd use scipy.misc.imrotate or skimage.transform.rotate or whatever. But considered only as an exercise, here's how I'd program this (in the nearest neighbour case, which is quite enough for one answer).

import numpy as np

def rotate_coords(x, y, theta, ox, oy):
    """Rotate arrays of coordinates x and y by theta radians about the
    point (ox, oy).

    """
    s, c = np.sin(theta), np.cos(theta)
    x, y = np.asarray(x) - ox, np.asarray(y) - oy
    return x * c - y * s + ox, x * s + y * c + oy

def rotate_image(src, theta, ox, oy, fill=255):
    """Rotate the image src by theta radians about (ox, oy).
    Pixels in the result that don't correspond to pixels in src are
    replaced by the value fill.

    """
    # Images have origin at the top left, so negate the angle.
    theta = -theta

    # Dimensions of source image. Note that scipy.misc.imread loads
    # images in row-major order, so src.shape gives (height, width).
    sh, sw = src.shape

    # Rotated positions of the corners of the source image.
    cx, cy = rotate_coords([0, sw, sw, 0], [0, 0, sh, sh], theta, ox, oy)

    # Determine dimensions of destination image.
    dw, dh = (int(np.ceil(c.max() - c.min())) for c in (cx, cy))

    # Coordinates of pixels in destination image.
    dx, dy = np.meshgrid(np.arange(dw), np.arange(dh))

    # Corresponding coordinates in source image. Since we are
    # transforming dest-to-src here, the rotation is negated.
    sx, sy = rotate_coords(dx + cx.min(), dy + cy.min(), -theta, ox, oy)

    # Select nearest neighbour.
    sx, sy = sx.round().astype(int), sy.round().astype(int)

    # Mask for valid coordinates.
    mask = (0 <= sx) & (sx < sw) & (0 <= sy) & (sy < sh)

    # Create destination image.
    dest = np.empty(shape=(dh, dw), dtype=src.dtype)

    # Copy valid coordinates from source image.
    dest[dy[mask], dx[mask]] = src[sy[mask], sx[mask]]

    # Fill invalid coordinates.
    dest[dy[~mask], dx[~mask]] = fill

    return dest

Here's fabio.jpg, a 200×200 image (courtesy of Oasisisgood at en.wikipedia, licensed under CC-BY-SA):

and here are some rotated versions:

>>> from scipy.misc import imread, imsave
>>> img = imread('fabio.jpg')
>>> for angle in (45, 75, 90, 120):
...     imsave('fabio-{}.jpg'.format(angle),
...            rotate_image(img, angle * np.pi / 180, 100, 100))

The rotation of this 200×200 image takes about 1/60 of a second:

>>> timeit(lambda:rotate_image(img, np.pi / 4, 100, 100), number=1)
0.01648401003330946

(scipy.misc.imrotate is about 4 times faster than this when using interp='nearest'.)


Multiple search filter like the one in freshdesk I have requirement to apply multiple filters on database. I will have multiple conditions in the front end where the user can select the conditions he wants to filter with and then see the output. This is similar to the filter that Freshdesk has or for instance similar to many ecommerece sites.

This is my CoffeeScript file:

read = ->
$("#payment_status_filter :checkbox").click ->
    collect_data()
$("#status_filter :checkbox").click ->
    collect_data()

collect_data = ->
    status_array = []
    if $("#status_filter :checkbox").is(":checked")
        console.log("####*******status filter##########@@@@@@")
        $("#status_filter :checked").each ->
            status_array.push $(this).val()
        console.log(status_array)
    payment_status_array = []
    if $("#payment_status_filter :checkbox").is(":checked")
        $("#payment_status_filter :checked").each ->
            console.log("*****PAYMENT STATUS**********")
            payment_status_array.push $(this).val()
            console.log(payment_status_array)
    ajax_call(payment_status_array,status_array)

ajax_call= (payment_status,status) ->
    $.ajax(
        type: "GET"
        url: "/admin/filter_request"
        format: 'js'
        dataType: "script"
        data:
            payment_status: payment_status
            status: status
    ).done (data) ->
        console.log data
        $(".request_table_span").html data
        return

$(document).ready read
$(document).on "page:load", read

What I am doing above is that when the user clicks a checkbox for a payment_status conditions say "Paid" or "Unpaid" then it will fire a ajax request to a controller which will respond with a result. I have written such that when the requisite condition is clicked all the conditions in the whole page will be collected and sent along because more than one filter can be applied at the same time.

The following is my controller code:

def filter_request
    Rails.logger.info params
    @requests = Request.all
    @requests = @requests.where(payment_status: params[:payment_status]) if params[:payment_status]
    @requests = @requests.where(status: params[:status]) if params[:status]
    respond_to do |format|
       format.js
    end
end

The above approach seems not very good when the requirement has many filters, especially the controller part. How do I go about this? Any better approaches?

I would advise you to implement search in Index action. If there are no search filters passed, then simply return everything (both for HTML and JSON).

You should rebuild a bit of the form so search params are nested, and you won't have to filter them.

Finally, you can move the search logic to model:

class Request
  def self.search(opts={})
    #reject empty filters
    filters = opts.reject(&:blank?)
    where(filters)
  end
end

class RequestsController
  def index
    @requests = Request.search(params[:search])
  end
end

Now you need to worry only about passing correct params (form fields should match db columns). Some transformations may be necessary depending on how you expect to build the query.

Be sure to fully test the form with integration spec; you are relying on view a lot.


Overwriting an existing file in C# I just found out about the existence of this forum and it's exactly what I needed. I just asked this question on Stack Overflow and after reading the answers I came up with a code (not the one I posted there but the one I'm posting here).

First, this is my messed up code:

string tempFile = Path.GetTempFileName();

using (Stream tempFileStream = File.Open(tempFile, FileMode.Truncate))
{
    SafeXmlSerializer xmlFormatter = new SafeXmlSerializer(typeof(Project));
    xmlFormatter.Serialize(tempFileStream, Project);
}

if (File.Exists(fileName)) File.Delete(fileName);
File.Move(tempFile, fileName);
if (File.Exists(tempFile)) File.Delete(tempFile);

When saving to an existing file that is in my Dropbox, it will, sometimes, delete the original file and fail to move the temporary file to the original location in File.Move(tempFile, fileName);. So here is my new code that I think it should never, unless the OS became self-conscious and evil, delete the original file without saving the new one. The worst it can happens is that the original will be renamed and will stay like that and I will have to let the user know (see the MessageBox at the bottom):

private string GetTempFileName(string dir)
{
    string name = null;
    int attempts = 0;
    do
    {
        name = "temp_" + Player.Math.RandomDigits(10) + ".hsp";
        attempts++;
        if (attempts > 10) throw new Exception("Could not create temporary file.");
    }
    while (File.Exists(Path.Combine(dir, name)));

    return name;
}

private void TryToDelete(string path)
{
    try { File.Delete(path); }
    catch { }
}

private void SaveProject(string fileName)
{
    bool originalRenamed = false;
    string tempNewFile = null;
    string oldFileTempName = null;
    Exception exception = null;

    try
    {
        tempNewFile = GetTempFileName(Path.GetDirectoryName(fileName));

        using (Stream tempNewFileStream = File.Open(tempNewFile, FileMode.CreateNew))
        {
            SafeXmlSerializer xmlFormatter = new SafeXmlSerializer(typeof(Project));
            xmlFormatter.Serialize(tempNewFileStream, Project);
        }

        if (File.Exists(fileName))
        {
            oldFileTempName = GetTempFileName(Path.GetDirectoryName(fileName));
            File.Move(fileName, oldFileTempName);
            originalRenamed = true;
        }

        File.Move(tempNewFile, fileName);
        originalRenamed = false;

        CurrentProjectPath = fileName;
    }
    catch (Exception ex)
    {
        exception = ex;
    }
    finally
    {
        if (tempNewFile != null) TryToDelete(tempNewFile);

        if (originalRenamed)
        {
            try
            {
                File.Move(oldFileTempName, fileName);
                originalRenamed = false;
            }
            catch { }
        }

        if (exception != null) MessageBox.Show(exception.Message);

        if (originalRenamed)
        {
            MessageBox.Show("'" + fileName + "'" +
                " have been corrupted or deleted in this operation.\n" +
                "A backup copy have been created at '" + oldFileTempName + "'");
        }
        else if (oldFileTempName != null) TryToDelete(oldFileTempName);
    }
}

Player.Math.RandomDigits is just a function that returns a string with random digits. Do you think my code is safe as I think it is or am I missing something? It's hard for me to test every possible exception.

Using File.Replace() still seems the best option to me. As you mentioned on SO, the following might give a problem:

  If the sourceFileName and
  destinationFileName are on different
  volumes, this method will raise an
  exception. If the
  destinationBackupFileName is on a
  different volume from the source file,
  the backup file will be deleted.

To prevent this exception from being thrown, can't you first check whether you can serialize the temp file directly to the desired volume? If this isn't possible, further processing will fail as well, so you can already show a message that the volume isn't writeable.

Afterwards, call the Replace function, creating a backup file. When it fails, handle appropriately and check in which state your files are, indicate to the user when something is 'corrupt' (so point to the backup file). In the finally check whether the backup file exists and remove.


Haskell zmq & protobuf message forwarding I wrote a test program (and first "real" Haskell program!) that receives a zmq request on 1 socket, and forwards part of that message to another socket.

There are a 2 things I specifically don't like:

I couldn't figure out a way to build a protobuf message without specifying every field.  This is especially annoying for fields like failure_message, which I had to set to Nothing
I'm not a fan of the lazyToStrictBS conversion

Is there any way to avoid these?  Also, any other things I should fix? I would be shocked if there were no other issues.

The code:

module Main where

import System.ZMQ4.Monadic
import Control.Monad (forever)
import Data.ByteString.Char8 (pack, unpack)
import qualified Data.ByteString as ByteString (ByteString, concat)
import Data.ByteString.Lazy as LBS (ByteString, toChunks)
import Control.Concurrent (threadDelay)

import Text.ProtocolBuffers.WireMessage (messageGet)
import Text.ProtocolBuffers.WireMessage (messagePut)

import ProtoMsg.ForwardRequest (ForwardRequest)
import ProtoMsg.ForwardResponse
import ProtoMsg.ReqResponse (ReqResponse)
import ProtoMsg.Status
import ProtoMsg.Retort

lazyToStrictBS :: LBS.ByteString -> ByteString.ByteString
lazyToStrictBS x = ByteString.concat $ LBS.toChunks x

main :: IO ()
main =
    runZMQ $ do
        repSocket <- socket Rep
        bind repSocket "tcp://*:9000"

        pubSocket <- socket Pub
        bind pubSocket "tcp://*:9001"

        liftIO $ putStrLn "Ready"
        forever $ do
            msg <- receive repSocket
            (liftIO.putStrLn.unwords) ["Received request:", unpack msg]

            let repMsg = ProtoMsg.ForwardResponse.ForwardResponse {
                header = ProtoMsg.ReqResponse.ReqResponse {
                    message_id = Nothing,
                    user_id = Nothing,
                    request_id = Nothing,
                    ProtoMsg.ReqResponse.status = Just ProtoMsg.Status.OK,
                    failure_message = Nothing
                }
            }
            let respMsg = ProtoMsg.Retort.Retort {
                status = Just ProtoMsg.Status.OK,
                failure_message = Nothing
            }
            send repSocket [] (lazyToStrictBS (messagePut respMsg))

1) If you have used hprotoc to generate Haskell modules then you should be able to use defaultValue and optional fields will be assigned to Nothing by default i.e.

header = ProtoMsg.ReqResponse.ReqResponse {
    message_id = Nothing,
    user_id = Nothing,
    request_id = Nothing,
    ProtoMsg.ReqResponse.status = Just ProtoMsg.Status.OK,
    failure_message = Nothing
}

could be replaced with

header = defaultValue {
    ProtoMsg.ReqResponse.status = Just ProtoMsg.Status.OK
}

2) Instead of your lazyToStrictBS you could use the standard function toStrict in the bytestring package


Powershell function to get hash value of a file I created a function to get the hash value of a file. Normally the output is 3 lines. My function does 3 things:

extracts the hash value
removes the spaces in between the hash value
prints hash value

Here is the output when using CertUtil -hashfile FILENAME.EXE SHA1

SHA1 hash of file FILENAME.EXE:
XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
CertUtil: -hashfile command completed successfully.

My function:

function MyHash($file, $hashtype) {
    $hash = CertUtil -hashfile $file $hashtype
    $hashstring = $hash[1] -replace ' ',''
    echo $hashstring
}

my output:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Am I ok calling commands such as CertUtil from within a function the way I am doing? Can the syntax and code be improved? I feel like I'm just throwing commands inside a function but it works.

I think your code is okay. Some notes:

PowerShell 4 has a Get-FileHash command. Granted, most people don't have PS4 yet.
Why reinvent the wheel when other people have already done it better? E.g.: Boe Prox's Get-FileHash.
I believe the PowerShell Community Extensions also have a file hash command.
The dependency on certutil is not ideal. Do we know that the output format from all versions of certutil will be same everywhere and for all time?
You don't need the echo in the last line. The last line can consist of just $hashstring by itself. Since that value is not being consumed, it will be placed in the pipeline. (It's important, by the way, to understand how the pipeline works to use PowerShell.)


Handling null arguments in a factory class I have a Factory class that gives out instances of ResponseImpl class. It accepts one Destination class and up to four Source classes. At least one of the four Source classes should be not null.

So, instead of asking calling program to pass nulls in the arguments to Factory class, I have overloaded the method to accept at least one up to four Source classes. But, something tells me that this way of doing it is not a good idea. Although this works, I feel like this can be handled better.

Could you let me know how to make the following piece of code better?

public static Response initResponse(final Destination destination, final Source1 source1) {
    return initResponse(destination, source1, null, null, null);
}

public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2) {
    return initResponse(destination, source1, source2, null, null);
}

public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2, final Source3 source3) {
    return initResponse(destination, source1, source2, source3, null);
}

public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2, final Source3 source3, final Source4 source4) {
    try {
        if(source1 == null && source2 == null && source3 == null && source4 == null) {
            throw new ABODataException("Atleast one source has to be not null");
        }
        return ResponseImplManager.getInstance(destination, source1, source2, source3, source4);
    } catch (Exception e) {
        throw new ABODataException("Unable to instantiate Response:"+e.getMessage());
    }
}

It seems to me that you are not quite making good use of exceptions and as long as I believe it is possible that you are disrespecting some principles. First things first, you really should be using IllegalArgumentException because that is the java standard exception class for invalid arguments. You shouldn't also throw a exception and then catch it so your throw statement should be outside the try block. Why should you ever raise a error to treat it imeadiatly? You should avoid it instead!

public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2, final Source3 source3, final Source4 source4) {
    if(source1 == null && source2 == null && source3 == null && source4 == null) {
        throw new IllegalArgumentException ("Atleast one source has to be not null");
    }
    try {
        return ResponseImplManager.getInstance(destination, source1, source2, source3, source4);
    } catch (Exception e) {//if possible catch the specific type of the exception that is thrown by getInstance thought I don't see it as a huge issue as you don't have any other method calls
        throw new ABODataException("Unable to instantiate Response:"+e.getMessage());
    }
}


Generating parallel random numbers in a thread-safe way and using them in computations implemented by class method I have the following code that I managed to make thread-safe but I am not sure if I am using C++ technology optimally.

#include <iostream>
#include <omp.h>
//#include <memory>

class GenNo
{
public:

    int num;

    explicit GenNo(int num_)
    {
        num = num_;
    };

    void create(int incr)
    {
        num += incr;
    }
};

class HelpCrunch{
public:
    HelpCrunch() {

    }

    void helper(int number)
    {
        std::cout << "Seed is " << number << " for thread number: " << omp_get_thread_num() << std::endl;
    }
};

class calculate : public HelpCrunch
{
public:

    int specific_seed;
    bool first_run;

    void CrunchManyNos()
    {
        HelpCrunch solver;

        thread_local static GenNo RanNo(specific_seed);
        //std::unique_ptr<GenNo> GenNo_ptr(nullptr);
        /*
        if(first_run == true)
        {
            GenNo_ptr.reset(new GenNo(specific_seed));
            first_run = false;
        }
         solver.helper(GenNo_ptr->num);
*/
        RanNo.create(1);
        solver.helper(RanNo.num);

        //do actual things that I hope are useful.
    };
};

int main()
{

    calculate MyLargeProb;
    MyLargeProb.first_run = true;

#pragma omp parallel firstprivate(MyLargeProb)
    {
        int thread_specific_seed = omp_get_thread_num();
        MyLargeProb.specific_seed = thread_specific_seed;

        #pragma omp for
        for(int i = 0; i < 10; i++)
        {
            MyLargeProb.CrunchManyNos();
            std::cout << "Current iteration is " << i << std::endl;
        }

    }
    return 0;
}

The code that is commented out can be used as an alternative but the pointer gets destroyed after the method finishes which crashes the programme. Moreover, it was pointed out to me that I could use threadprivate for the static instance of GenNo. The use case equivalent of GenNo is a random number generator that gets seeded once per thread with a known seed and then is left alone, i.e. not reinitialised, but called upon to generate fresh random numbers in each iteration.

I know the whole structure seems a bit contrived but my hands are tied somewhat: the classes and their dependence are dictated to me by the tools I would like to use and I think this scenario is common in the scientific computing community.
It compiles fine and upon manual testing appears to be thread-safe and working but again, I don't think this is particularly good style and a bit cobbled together, so I would love to hear everyone's comments.
Important note: I am using gcc as my compiler and gcc for over ten years now doesn't support threadprivate class instances. Intel's compiler which can be obtained for academics and students on a trial license, does.

The following is an example of code that would not compile in GCC (even the most recent version).

#include "myclass.h"
#include <omp.h>
int main

{
   myclass myinstance;
   #pragma omp parallel threadprivate(my_instance)

    {

      // do parallel things

     }
    return 0;
}

The error message would be my_instance declared threadprivate after first use which is a long-standing bug or rather not a bug but a missing feature, see here, for example.

what is the problem with just creating a range of random number generators from <random> and assign each to a thread?

Mind that using thread_local might not be a good way, as initialization of random number generators is costly. Also i do not know, how therngs would be seeded in a thread_local environement.


How to optimize this HTML5 animation? I'm just learning the basics of animating with Javascript and HTML5. I'm trying to create this scrolling logos element for my site, and I'm pretty sure that my code is very inefficient. Can anyone give me any tips on how to do a better job of what I'm trying to do here?

http://jsbin.com/anagug/1/edit

Thanks!

EDIT: Here is the code:

        var ctx;
        var count = 0;
        var xpos;
        var ypos;
        var revealTimer;

        var img = new Image();
        img.src = "http://www.firewalkcreative.com/2012/images/logos_1.png";

        function switchImage(){

            xpos = count * 150;
            ypos = 0;

            count++;
            ctx.globalAlpha = 0.1;
            revealTimer = setInterval(revealImage,100);

            if(count == 5)
                count = 0;

        }

        function revealImage() {
            ctx.drawImage(img, 0, 0, 840, 90, xpos, count, 840, 90);
            ctx.drawImage(img, 0, 0, 840, 90, xpos-900, 0, 840, 90);
            ctx.save();
            ctx.globalAlpha += 0.1;
            if (ctx.globalAlpha >= 1.0)
                clearInterval(revealTimer);
            ctx.restore();
        }

        function init() {

            ctx = document.getElementById("canvas").getContext("2d");
            setInterval(switchImage,3000);
        }

Always do a clearInterval() before doing a new setInterval() on the same variable. Doesn't matter if it has been cleared or not.

e.g.

clearInterval(revealImage);
revealTimer = setInterval(revealImage,100);

You're code has a bug where the revealTimer is being reset before being cleared.

Why do you need to reset it?

function init() {
    ctx = document.getElementById("canvas").getContext("2d");
    setInterval(switchImage,3000);
    setInterval(revealImage,100);
}

Should work just as well.


Python arbitrary objects Serialization and Deserialization I am trying to convert objects inside an object(arbitrary objects) to Json and later retrieve it. I have developed some codes and would like to share if there is any problem in the code.
import json

Here is the first class
class Foo():
    def __init__(self,x,y,bar):
        self.x =x
        self.y = y
        self.bar = bar #Second class object is here

    def toJson(self):
        return json.dumps(Foo(self.x,self.y,self.bar).__dict__)

    @staticmethod
    def fromJson(jsonData):
        data =  json.loads(jsonData)
        return Foo(
            x = data['x'],
            y = data['y'],
            bar = Bar.fromJson(data['bar'])
        )

Here is the second class
class Bar():
    def __init__(self, z):
        self.z = z

    def toJson(self):
        return json.dumps(Bar(self.z).__dict__)

    @staticmethod
    def fromJson(jsonData):
        data =  json.loads(jsonData)
        return Bar(
            z = data['z'],
        )

Convert to Json
jsonData = Foo(100,500,Bar(900).toJson()).toJson()

Retrieve the Json and convert to Object
foo = Foo.fromJson(jsonData)

Print the Object attributes
print(foo.bar.z)

It works actually. But is there any memory leakage? Any security issue?

There's a library for this dataclasses-json. Whilst it's a pretty poor library the internal code is bad, there's few tests, the documentation is quite small and the design is starting to suffer from these poor decisions. It works, and for your code it is good enough.
You should be able to see that all serialization and deserialization is performed automatically. This is good as then you can focus on using the objects rather than converting to and from them.
from __future__ import annotations

from dataclasses import dataclass

from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class Foo:
    x: int
    y: int
    bar: Bar

@dataclass_json
@dataclass
class Bar:
    z: int

raw = '{"x": 100, "y": 500, "bar": {"z": 900}}'
obj = Foo.from_json(raw)
assert obj == Foo(100, 500, Bar(900))
assert obj.to_json() == raw


Implementing printf to a string by calling vsnprintf twice I'm experimenting with writing a dynamic string library in C, and I decided to write an implementation of sprintf.

In my code, I call vsnprintf with a buffer of 0 bytes, just so I can get the number of bytes it requires. I was wondering if there is anything wrong with this code and if there a better way to do this. It feels wrong to me, but I can't seem to think of a better way to do so yet have the same effect.

string string_printf(const char *fmt, ...) {
    va_list in, copy;
    string a = NULL;
    int size;

    /* start the main input */
    va_start(in, fmt);
    /* make a copy of the input */
    va_copy(copy, in);

    /* run vsnprintf just to see how much bytes needed */
    size = vsnprintf(a, 0, fmt, copy) + 1;
    va_end(copy);

    /* allocate the amount now */
    a = string_new_size(size);
    string_to_sr(a)->len = size - 1;

    /* re-run */
    vsnprintf(a, size, fmt, in);
    va_end(in);

    /* done */
    return a;
}

Looks reasonable to me.

The efficiency of this code really depends on your expected workload. For example, if you're expecting to use this code with a lot of strings of length 50 to 60, and you don't mind wasting a bit of memory in the case that the strings are shorter, then you could probably avoid a vsnprintf in the common case by writing

string string_printf(const char *fmt, ...) {
    va_list in, copy;
    const int INITIAL_SIZE = 60;
    string a = string_new_size(INITIAL_SIZE);

    /* start the main input */
    va_start(in, fmt);
    /* make a copy of the input */
    va_copy(copy, in);

    /* run vsnprintf just to see how much bytes needed */
    int length = vsnprintf(a, INITIAL_SIZE, fmt, copy);
    va_end(copy);

    /* allocate the amount now */
    if (length >= INITIAL_SIZE) {
        /* re-run */
        a = string_new_size(length+1);
        int new_length = vsnprintf(a, length+1, fmt, in);
        assert(new_length <= length);
    }
    string_to_sr(a)->len = length;
    va_end(in);

    /* done */
    return a;
}

Notice that I've also changed your size = ... + 1, size-1 to length = ..., length, on the principle that adding and subtracting 1 all the time is less efficient than not adding and subtracting 1 all the time; and on the principle that everybody knows what "string length" means (it's strlen), whereas "string size" is a bit ambiguous (does it include the null terminator or not?).

Somewhat off-topic: I'm leery of your use of string a; to declare a pointer. To me, a bare identifier always means "value-semantic object", as in FILE or char; and if the object is supposed to have pointer semantics, you add a star, as in FILE* or char*. Hiding the star inside a typedef strikes me as a bad idea. Although I admit that if you're coming from Java or Objective-C or Python or any other non-C, non-C++ language where

a = b;

traditionally means "don't copy the value, just reseat the pointer a to point to the same heap object as b", then your use of string a; a->something(); will seem perfectly natural. To me it seems confusing; I'd rather write string *a; a->something();.


Serialize C# objects of unknown type to bytes using generics Usage example

var qm = new QueueMessage("foo", 99);
var ba = ByteArraySerializer<QueueMessage>.Serialize(qm));

Class that performs the serialization / deserialization

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Codingoutloud
{
   public static class ByteArraySerializer<T>
   {
      public static byte[] Serialize(T m)
      {
         var ms = new MemoryStream();
         try
         {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, m);
            return ms.ToArray();
         }
         finally
         {
            ms.Close();
         }
      }

      public static T Deserialize(byte[] byteArray)
      {
         var ms = new MemoryStream(byteArray);
         try
         {
            var formatter = new BinaryFormatter();
            return (T)formatter.Deserialize(ms);
         }
         finally
         {
            ms.Close();
         }
      }
   }
}

Example of an object we would serialize

using System;

namespace Codingoutloud
{
   [Serializable]
   public class QueueMessage
   {
      public QueueMessage() {}
      public QueueMessage(string name, int id)
      {
         Name = name;
         Id = id;
      }

      public string Name { get;  set; }
      public int Id { get; set; }
   }
}

Your methodology is solid on the generics front. Highly recommend using using statements rather than try..finallys. I also converted the methods to extension methods.

namespace Codingoutloud
{
   using System.IO;
   using System.Runtime.Serialization.Formatters.Binary;

   public static class ByteArraySerializer
   {
      public static byte[] Serialize<T>(this T m)
      {
         using (var ms = new MemoryStream())
         {
            new BinaryFormatter().Serialize(ms, m);
            return ms.ToArray();
         }
      }

      public static T Deserialize<T>(this byte[] byteArray)
      {
         using (var ms = new MemoryStream(byteArray))
         {
            return (T)new BinaryFormatter().Deserialize(ms);
         }
      }
   }
}


Remove Nth Node From End of List Given a linked list, remove the nth node from the end of list and return its head.

For example,

  Given linked list: 1->2->3->4->5, and n = 2.

  After removing the second node from the end, the linked list
  becomes 1->2->3->5.

ListNode *removeNthFromEnd(ListNode *head, int n) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    if (head == NULL) {
      return NULL;
    }

    ListNode *pre, *cur;
    pre = cur = head;
    for (int i = 0; i < n; ++i) {
      pre = pre->next;
    }

    while (pre != NULL && pre->next != NULL) {
      cur = cur->next;
      pre = pre->next;
    }

  //mistake
  //if (cur == head) {
  // I use the above line to check if it's the first node to be deleted,
  // there is a problem for this case: list: 1->2, n : 1
    if (pre == NULL) {
      ListNode *newHead = head->next;
      delete head;
      return newHead;
    }
    else {
      ListNode *tmp = cur->next;
      cur->next = tmp->next;
      delete tmp;
      return head;
    }
}

Your function fails if n is 0 or greater than the list size.

Also, I prefer to see one variable defined per-line:

ListNode *pre = head;
ListNode *cur = head;

And the opening brace belongs in column 0 (I guess you don't agree, but there are - or were anyway - tools that rely on this).

An alternative implementation might use a function to find the number of entries in the list and another to return a specified entry (size - n - 1, in this case). Then once you've checked that 0 < n <= size, the main function is simple - but no better than yours :-)

BTW, delete is C++, not C


Partial Sudoku Verifier To practice my JavaScript for future employment, I've decided to take up the challenge of writing a javascript sudoku verifier. This code only verify's one of the nine 3x3 blocks there are. I would like feedback on this portion of the code, so I can continue my development with more knowledge and more efficient code. Also, any feedback on my HTML/CSS is warmly welcome. I'm using a fullscreen chrome browser for development, so the #middle centers the box on my screen, but it might not on yours.

You will have to click on full page -> to view the CSS correctly.

function checkAnswer() {

 //reset each time button is clicked
 document.getElementById('correct').style.display = 'none';
 document.getElementById('incorrect').style.display = 'none';

 //add each input into 2D array
 let first_row = document.getElementsByClassName('row1');
 let second_row = document.getElementsByClassName('row2');
 let third_row = document.getElementsByClassName('row3');
 let sudoku = [
  [first_row[0].value, first_row[1].value, first_row[2].value],
  [second_row[0].value, second_row[1].value, second_row[2].value],
  [third_row[0].value, third_row[1].value, third_row[2].value]
 ]

 //check if each number is unique in the 2D array
 for (let i = 0; i < sudoku.length; i++) {
  for (let j = 0; j < sudoku[i].length; j++) {
   if(!isUnique(sudoku[i][j], sudoku)) {
    document.getElementById('incorrect').style.display = 'block';
    return;
   }
  }
 }
 document.getElementById('correct').style.display = 'block';
}

function isUnique(num, arr) {
 let count = 0;
 //check entire array
 for(let i = 0; i < arr.length; i++) {
  for(let j = 0; j < arr[i].length; j++) {
   if(arr[i][j] == num) {
    count++;
   }
  }
 }
 return count == 1;
}
body {
 background-color: pink;
}
input {
 width: 50px;
 height: 50px;
 font-size: 20px;
 text-align: center;
}
button {
 width: 100px;
 height: 50px;
 font-size: 15px;
 margin-left: 40px;
}

#middle {
 margin-left: 900px;
 margin-top: 300px;
}
<!DOCTYPE html>

  <meta charset='UTF-8'>
  <title>Sudoku</title>
  <link rel="stylesheet" type="text/css" href="style.css">

     <input type="text" class="row1" maxlength="1" value="3">
     <input type="text" class="row1" maxlength="1">
     <input type="text" class="row1" maxlength="1">

     <input type="text" class="row2" maxlength="1">
     <input type="text" class="row2" maxlength="1" value="2">
     <input type="text" class="row2" maxlength="1">

     <input type="text" class="row3" maxlength="1" value="7">
     <input type="text" class="row3" maxlength="1">
     <input type="text" class="row3" maxlength="1">

   <button type="button" onclick="checkAnswer()">Check</button>

Incorrect Entry!

Correct Entry!

Styling

You can align centered elements relatively to their parent.

#middle {
  margin-left: 900px;
  margin-top: 300px;
}

#middle {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  top: 50%;
  transform: translateY(50%);
}

Naming

In my opinion, for algorithms it is OK to use short variable names.

let first_row = document.getElementsByClassName('row1');
let second_row = document.getElementsByClassName('row2');
let third_row = document.getElementsByClassName('row3');
let sudoku = [
  [first_row[0].value, first_row[1].value, first_row[2].value],
  [second_row[0].value, second_row[1].value, second_row[2].value],
  [third_row[0].value, third_row[1].value, third_row[2].value]
]

let r1 = document.getElementsByClassName('row1');
let r2 = document.getElementsByClassName('row2');
let r3 = document.getElementsByClassName('row3');
let sudoku = [
    [r1[0].value, r1[1].value, r1[2].value],
    [r2[0].value, r2[1].value, r2[2].value],
    [r3[0].value, r3[1].value, r3[2].value]
]