texts:
This is a cocoa app that adds a right click menu option to change whether a file is executable. It works by executing the system command chmod on each of the files. But I want to know if there is a better way to change the permission of a file, such as a cocoa function that can change the permission of a file.

What are some other ways that I can improve my code?

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    [NSApp setServicesProvider:self];
    NSUpdateDynamicServices();
}
void runSystemCommand(NSString *cmd)
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/chmod"];
    if ([[NSFileManager defaultManager] isExecutableFileAtPath:cmd]) {
        //NSLog(@"is executable \n");
        [task setArguments:@[ @"-x", cmd]];
        [task launch];

    } else {
        //NSLog(@"is not executable \n");
        [task setArguments:@[ @"+x", cmd]];
        [task launch];

    }
}
- (void)handleServices:(NSPasteboard *)pboard
              userData:(NSString *)userData
                 error:(NSString **)error {
    if([[pboard types] containsObject:NSFilenamesPboardType]){
        NSArray* fileArray=[pboard propertyListForType:NSFilenamesPboardType];
        int i;
        int count;
        count = [fileArray count];
        for (i = 0; i < count; i++){
            //NSLog (@"%@", [fileArray objectAtIndex: i]);
            runSystemCommand([fileArray objectAtIndex: i]);
        }
    }
}

@end

Here is the repository for the complete project.


texts:
I have been given a requirement to create a symbol toolbar, a toolbar where each button represents a unique symbol.

This is how the toolbar would work:

A user clicks inside a text field and enters data.
The user would then click a symbol on the toolbar and it will be appended to that specific text field.
The browser will put focus back on that text field.

I have created this toolbar, but I really dislike my implementation because it feels really hacky. In my implementation, I created two functions, addSymbol and setLastFocused in my controller:

$scope.addSymbol = function (field)
{
    if (!$scope.product[$scope.lastFocusedModelKey])
    {
        $scope.product[$scope.lastFocusedModelKey] = "";
    }

    $scope.product[$scope.lastFocusedModelKey] = $scope.product[$scope.lastFocusedModelKey] + field.symbol.SymbolCharacter;

    $('#' + $scope.lastFocusedModelKey).focus();
}

$scope.setLastFocused = function (lastFocusedModelKey)
{
    $scope.lastFocusedModelKey = lastFocusedModelKey;
}

SetLastFocused is called every time a user puts focus on a text field. I pass in a string of the field name like this:

<input type="text" id="Foo" name="FooName" ng-model="product.Foo" class="form-control input-xs" ng-focus="setLastFocused('Foo')">

AddSymbol accepts the button field as a parameter, and appends the symbol to the model that is bound to the text field, and then re-focuses on the text field.

I feel like this is hacky because:

I have to use jQuery to re-focus on the text field.
I'm passing in a hardcoded string representing the field name (meaning if I change the name of the field and forget to change the hardcoded string, then this symbol feature will break for that specific text field).

This works fine now with a few text fields in which the users may want to append symbols, but now I'm learning I need to add the functionality to append symbols to text fields inside a whole Angular Ui-Grid (which exists inside a separate controller). So I am realizing I need to refactor this if I want this to work with a Ui-Grid as well. I know I need to move this code to a separate service, but I would also like to make this cleaner. I'm just not really sure how.

How can I make this code follow best Angular practices?


texts: Von Neumann extractor to remove bias from pseudorandom array

texts:
Von Neumann extraction is a technique to remove bias from a source of entropy. You extract an unbiased array of bits from a biased one by comparing pairs of consecutive bits in the array and returning the first one when they are different, or nothing when they are the same. The extracted array will be smaller than the source array, but will be more balanced in terms of overall 0s and 1s.

To accomplish this in JavaScript I ended up writing two extraction methods: one for extracting a bit (given an array and an index) and one for extracting an entire array (given an array). The code appears to work as desired, but I'd love to hear any insights or suggestions related to best practices, naming conventions, performance concerns, or problematic edge cases.

Here's my bit-extraction method:

function extractBitFromArray(arr, i) {
    var a = arr[i];
    var b = arr[i + 1];
    return (a ^ b ? a : null);
}

And here's my array-extraction method:

function extractUnbiasedArray(randomArray){
    var extractedArray = [];
    for (var i = 0; i + 1 < randomArray.length; i += 2) {
        var extracted = extractBitFromArray(randomArray, i);
        if (extracted !== null) {
            extractedArray.push(+extracted);
        }
    }
    return extractedArray;
}

For the sake of completion, here are some analogous dummy functions used to generate a biased but still pseudorandom array:

function getBiasedArray(length){
    var randomArray = [];
    for (var i = 0; i < length; i++) {
        randomArray.push(getBiasedBit());
    }
    return randomArray;
}
function getBiasedBit() {
    return +(Math.pow(Math.random(), Math.random()) > Math.random());
}

Example of how the functions would be used:

var randomArray = getBiasedArray(5000);
var extractedArray = extractedUnbiasedArray(randomArray);

I have a fiddle demonstrating how the technique works, but it's polluted with logging and metrics, and doesn't have all the logic encapsulated into functions; I'd rather any critiques be directed to the above code rather than the code in the fiddle: http://jsfiddle.net/thriggle/Ljojyn6p/


texts: Refactoring if statement based on a hash key

texts:
I have to call Article.to_draft/to_archive/publish method depending on the presence of the corresponding key in the params hash.

I do, however, have no idea to implement it properly.

def update_state
  method = if params[:draft].present?
             :to_draft
           elsif params[:archived].present?
             :to_archive
           else
             :publish
           end
  @article.send method
end

The code works, but the number of possible states of an article will probably grow in the future.

I would like to have a hash like this:

{ draft: :to_draft, archived: :to_archive, default: :publish }

and let #update_state decide what should be called, based on the params hash.


texts: Basic JavaScript template engine using replace, match and RegExp

texts:
To practice with regular expressions, I wrote this basic template engine in JavaScript in addition to a simple test case to make sure it works correctly.

I am wondering if there is any improvements I can do or if I am correctly following JavaScript coding style and conventions. Thanks in advance.

In short,

{{= expression}} --> evaluates expression (context is optional)
{{0}}            --> evaluates based on given array index
{{name}}         --> evaluates based on given json values

Template code (does not require any dependency):

(function() {
    this.amirTemplateEngine = function() {
        var self = this;
        var _tokensToReplace, _values, _array;

        // evaluate in-line expressions
        self.evaluateString = function(string, options) {
            _tokensToReplace = string.match(new RegExp(/({{=[^}]*}})/g)) || [];

            _tokensToReplace.map(function(token) {
                string = string.replace(token, (function() {
                    return eval(token.replace("{{=", "").replace("}}", ""));
                }).call(options && options.context ? options.context : self));
            });

            return string;
        };

        // replace given object
        self.replaceGivenObject = function(string, options) {
            _values = options && options.values ? options.values : {};
            _tokensToReplace = string.match(new RegExp(/({{[ ]*[^}.]+[ ]*}})/g)) || [];

            _tokensToReplace.map(function(token) {
                string = string.replace(token, _values[token.replace(" ", "").replace("{{", "").replace("}}", "")]);
            });

            return string;
        };

        // replace given array index
        self.replaceGivenArray = function(string, options) {
            _array = options && options.array ? options.array : {};
            _tokensToReplace = string.match(new RegExp(/({{[ ]*[0-9]+[ ]*}})/g)) || [];

            _tokensToReplace.map(function(token) {
                string = string.replace(token, _array[parseInt(token.replace(" ", "").replace("{{", "").replace("}}", ""))]);
            });

            return string;
        };

        // helper function
        self.format = function(string, options) {
            // evaluate expressions
            string = self.evaluateString(string, options);

            // if options.array is defined, then evaluate template
            string = self.replaceGivenArray(string, options);

            // if options.values is defined, then evaluate template
            string = self.replaceGivenObject(string, options);

            return string;
        };

        // for chainability
        return self;
    };
})();

Testing the code (making sure output is correct):

var template = require('./amir-template-engine');

(function() {
    var self = this;
    something = "something else!";
    var template = "\

{{0}} {{1}} {{2}}
\

{{= 4 > 0 ? 'good' : 'bad'}}
\

{{= something }}
\

{{name}}
\
                ";

    var result = "\

seyed amir hossein
\

good
\

something else!
\

amir
\
                ";

    var templateObj = new amirTemplateEngine();

    testResult = templateObj.format(template, {
        array: ["seyed", "amir", "hossein"],
        values: {
            name: "amir"
        },
        context: self
    }) == result;

    console.log("Test is" + (testResult ? "" : " NOT") + " passing!");
})();

Link to GitHub repository


texts:
I'd like to create a cookie wrapper in my application to help support a DRY approach to coding  common cookie methods, provide IntelliSense for cookie-type properties (keys), and protect against typo-errors when working with cookies from multiple classes and namespaces.

The best structure for this (that I can think of) is to apply a base class like such:

abstract class CookieBase{
   protected HttpRequestBase request;
   protected HttpCookie cookie;
   protected string name;

   public HttpCookie Cookie { }

   public string Name { get; }

   public HttpCookie Get(){ ... }

   protected string GetValue(string key){ ... }

   public bool IsSet(){ ... }

   protected void SetValue(string key, string value){ ... }
}

Then for each cookie-type that inherits the base class define properties for each key that should be stored in the HttpCookie, and define a constructor that accepts the Request object as a parameter and instantiates the Cookie property of the base class.

Any ideas on how I might improve this design, or suggestions to alternative approaches to attaining the goals I stated at the start of this post?


texts:
Problem statement

There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be \$\mathcal{O}(\log (m+n))\$.

Implementation

 def median(A, B):
    m, n = len(A), len(B)
    if m > n:
        A, B, m, n = B, A, n, m
    if n == 0:
        raise ValueError

    imin, imax, half_len = 0, m, (m + n + 1) / 2
    while imin <= imax:
        i = (imin + imax) / 2
        j = half_len - i
        if j > 0 and i < m and B[j-1] > A[i]:
            # i is too small, must increase it
            imin = i + 1
        elif i > 0 and j < n and A[i-1] > B[j]:
            # i is too big, must decrease it
            imax = i - 1
        else:
            # i is perfect
            if i == 0: max_of_left = B[j-1]
            elif j == 0: max_of_left = A[i-1]
            else: max_of_left = max(A[i-1], B[j-1])

            if (m + n) % 2 == 1:
                return max_of_left

            if i == m: min_of_right = B[j]
            elif j == n: min_of_right = A[i]
            else: min_of_right = min(A[i], B[j])

            return (max_of_left + min_of_right) / 2.0

Concern

I suspect that it is safe to change this line of code

j > 0 and i < m and B[j-1] > A[i]

to

i < m and B[j-1] > A[i]

and also it is safe to change this line of code

i > 0 and j < n and A[i-1] > B[j]

to

i > 0 and A[i-1] > B[j]

I think remove the condition check of j is safe since we already making sure size of A is no bigger than size of B.


texts: A GapHelper static class to create unique (non-existing) size restricted names

texts:
I am working with a 3th party library which has following interface defined for a processing task:

public interface IProcessor {
    void Execute( FileContent fileContent );
}

Such an IProcessor gives me the possibility to change the FileContent before it gets written to the database. For legacy reasons, and for integration reasons with an unnamed ERP, its unique identifiers are string identifiers which have a limitation in length, and they are padded on the left with padding char '0'.

Names will therefore always have the form of 00100 or 02301 or 10179 for a 5 digit identifier.

Sometimes, we need to add new content inside the fileContent.Components, but we are not allowed to change the existing identifiers. Theoretically any number of items could be added to the components, but for the question at hand, I simplified it to just adding 20 items.

The existing identifiers do not have any order to them, nor can I be sure that the highest number inside the string would be lower than the theoretical maximum number for this identifier.

To handle this addition, I thought I could use a IEnumerator<string> function (not class) as an iterator, that creates the next number starting from the theoretical minimum value to the theoretical maximum value, and throw when it exceeds the maximum value.

public static class GapHelper {
    public static IEnumerator<string> GetNextName( int maxSize, IEnumerable<string> items, Func<int, string> transform ) {
        var maxLength = (long)Math.Pow( maxSize, 10 );
        var hashSet = new HashSet<string>( items );
        for (var i = 0; i < maxLength; i++) {
            var text = transform(i);
            if (hashSet.Contains( text )) {
                continue;
            }
            yield return text;
        }
        throw new ArgumentOutOfRangeException( "Iteration exceeded maximum numbers of items at " + maxSize );
    }

    public static IEnumerator<string> GetNextName( int maxSize, IEnumerable<string> items) {
        return GetNextName( maxSize, items, i => i.ToString().PadLeft( maxSize, '0' ) );
    }
}

and this would be used inside such an IProcessor in the following way:

public class ProcessingTask : IProcessor {
    public void Execute( FileContent fileContent ) {
        using (var nameGenerator = GapHelper.GetNextName( 5, fileContent.Components.Select( c => c.Name ) ) ) {
            for (var i = 0; i < 20; i++) {
                nameGenerator.MoveNext();
                fileContent.Components.Add( new Component {
                    Name = nameGenerator.Current, Content = "Foo"
                } );
            }
        }
    }
}

What I cannot change:

How the processor is called, and with which parameters
How the file is processed afterwards, and might have been processed before
My bracket positioning, we have them at the end of each line
I am aware I didn't add documentation to the methods

A full simplified example can be found in this dotnetfiddle.

I am interested in how this code looks from maintainability perspective, and what other potential options I might have overlooked. I am also curious if having an IEnumerator<string> implemented as a method rather than a class makes a big difference, either for this implementation or from an iterator perspective.


texts:
There are N boys standing in line in order 1 to n. For each ith boy (i from 1 to N) W[i] gives his weight. A boy in line can push another boy if his weight is more than or equal to the sum of weight of boys between them. We have to calculate for each boy, the number of boys he can get pushed by. My solution is taking too much time.
(1<=N<=10^5)
first line has N, second has weight of N boys in line.
For example:
INPUT:
5
2 5 8 10 12
OUTPUT:
2 3 3 2 1
My code:

 class A {

public static void main(String[] args) throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(br.readLine());
        int n=Integer.parseInt(st.nextToken());
        long[] W=new long[n];
        long[] sumtill_i=new long[n];
        int[] pushedby=new int[n];
        long sum=0;
        st=new StringTokenizer(br.readLine());
        for(int i=0;i<n;i++)
        {
            W[i]=Long.parseLong(st.nextToken());
            sum+=W[i];
            sumtill_i[i]=sum;
        }
        int j;
        for(int i=0;i<n;i++)
        {
            j=n-1;
            while(j>=0)
            {
                if(j>i)
                {
                    if(W[j]>=(sumtill_i[j]-sumtill_i[i]-W[j]))
                        pushedby[i]++;
                }
                if(j<i)
                {
                    if(W[j]>=(sumtill_i[i]-sumtill_i[j]-W[i]))
                        pushedby[i]++;
                }
                j--;

            }
        }
        for(int i=0;i<n;i++)
            System.out.print(pushedby[i]+" ");
}
 }


texts:
I am trying to write industry standard code.
https://www.quora.com/How-do-I-follow-a-user-on-Spoj-for-solving-problems-Refer-Details

Someone gave me this A2A.
And I wrote this code for it

//compile with g++ -std=c++11
#include <bits/stdc++.h>
using namespace std;
struct PROBLEM
{
    string name;
    string links;
    int users;
    double points;
};
bool compare (PROBLEM & p1 , PROBLEM & p2)
{
    return p1.users < p2.users;
}
void savePage(string & username)
{
    string url = "http://www.spoj.com/users/" + username +"/";
    string cmd = "curl " + url + " >" + username + ".txt";
    system (cmd.c_str());
}
bool checkRegex(string & str)
{
    return regex_match (str , std::regex("^\\s{0,}<td\\salign.{0,}$"));
}
bool checkRegexProb(string & str)
{
    return regex_match(str , std::regex("^\\s{0,}' ; i++);
    i++;
    for(;str[i] != '<' ; i++)
        temp += str[i];
    return stoi(temp);
}
int getUsers(string & str)
{
    string url = "http://www.spoj.com/ranks/" + str + "/";
    string cmd = "curl " +url + " >" + str +".txt";
    system(cmd.c_str());
    string filename = str + ".txt";
    int Count = 0;
    ifstream myfile(filename.c_str());
    if (myfile)
    {
        string line;
        while (getline( myfile, line ))
        {
            if (checkRegexProb(line) )
            {
                Count ++;
                if(Count == 2)
                {
                    myfile.close();
                    string deleteFile = "rm -r " + filename;
                    system(deleteFile.c_str());
                    return getNum(line);
                }
            }
        }
    }
}
vector<PROBLEM> readFile(string & username)
{
    std::vector<PROBLEM> v;
    string filename = username + ".txt";
    ifstream myfile(filename.c_str());
    if (myfile)
    {
        string line;
        while (getline( myfile, line ))
        {
            if (checkRegex(line) )
            {
                string temp;
                size_t found = line.find("/status/");
                for(size_t i = found + 8 ; line[i]!=',' ; i++)
                    temp += line[i];
                if(temp != "")
                {
                    PROBLEM p;
                    p.name = temp;
                    p.users = getUsers(p.name);
                    while(p.users == 0)
                        p.users = getUsers(p.name); // bug -> curl gives empty response
                    v.push_back(p);
                }
            }
        }
        myfile.close();
    }
    return v;

}
void makeLink(std::vector<PROBLEM> & v)
{
    for(int i = 0 ; i < v.size() ; i++)
        v[i].points = 80.0/(40.0+ v[i].users),
        v[i].links = " " + v[i].name +" "+ to_string(v[i].points) +"
";
}
string makeHtml(std::vector<PROBLEM> & v)
{
    string list ;
    for (int i = 0 ; i < v.size() ; i++ )
        list += v[i].links;
    string HTML =
    ""+ list +"";
    return HTML;
}
int main(int argc, char const *argv[])
{
    string username ;
    cin >> username ;
    savePage(username) ;
    std::vector<PROBLEM> v = readFile(username);
    sort(v.rbegin(), v.rend(),compare);
    makeLink(v);
    std::ofstream outfile ((username + ".html").c_str());
    outfile <<makeHtml(v);
    system(("rm -f "+ username + ".txt").c_str());
    system(("gnome-open " + username + ".html").c_str());
    return 0;
}

How can I improve it so that it matches industry standard?


texts: Convert string of hex into vector of bytes

texts:
I want to write a function that gets a string of hex numbers (two hex numbers represent a u8 value) then returns a vector of u8 values, e.g. the string 1f 0a d1 should be converted into [31, 10, 209]. The input string may contains non hex characters, then the function must be able to filter these characters, such as:

1f\x0ad1
1f \x0a\xD1
\x1F \x0a \xd1
\x1f    \x0A\xd1
...

All of them lead to the output [31, 10, 209]. My solution is that following:

fn parse_hex(hex_asm: &str) -> Vec<u8> {
    let hex_chars: Vec<char> = hex_asm.as_bytes().iter().filter_map(|b| {
        let ch = char::from(*b);
        if ('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F') {
            Some(ch)
        } else {
            None
        }
    }).collect();

    let mut index = 0usize;
    let (odd_chars, even_chars): (Vec<char>, Vec<char>) = hex_chars.into_iter().partition(|_| {
        index = index + 1;
        index % 2 == 1
    });

    odd_chars.into_iter().zip(even_chars.into_iter()).map(|(c0, c1)| {
        fn hexchar2int(ch: char) -> u8 {
            if '0' <= ch && ch <= '9' {
                ch as u8 - '0' as u8
            } else {
                0xa +
                if 'a' <= ch && ch <= 'f' {
                    ch as u8 - 'a' as u8
                } else if 'A' <= ch && ch <= 'F' {
                    ch as u8 - 'A' as u8
                } else {
                    unreachable!()
                }
            }
        }
        hexchar2int(c0) * 0x10 + hexchar2int(c1)
    }).collect::<Vec<u8>>()
}

But it does make me happy. There are several problems that I may think of:

It needs to create two sub-vectors, one for odd-index element, one for even-index
Because of performance, I wrote the function hexchar2int (which is ugly) to convert two hex number into a u8 value instead of using u8::from_str_radix

I wonder if there is a better method to do that.


texts: Script that creates an active CSS on link

texts:
I have a script that creates an active CSS on link, but I think there are a lot of if statements.  Can someone help me refactor this?

var link = window.location.pathname;
var currentPageName = window.location.href.match(/[^\/]+$/)[0];

var hl = $('#ih').val();

if (hl == 'True') {
    var currentPageName = 'WVD';
}

if (window.location.href.indexOf("R") > -1) {
    var currentPageName = window.location.href.match(/[^\/]+$/)[0];
}

if (window.location.href.indexOf("C") > -1) {
    var currentPageName = window.location.href.match(/[^\/]+$/)[0];
}

if (location.pathname == "/") {
    var currentPageName = 'MD';
}

$(".main-navigation ul li a").each(function () {
    var link = $(this).attr("href");
    if (link.indexOf(currentPageName) > -1) {
        $(this).addClass("active");
        $(this).css("color", "white");
        $(this).css("text-decoration", "bold");
    }
});


texts: Most efficient way to validate multiple textboxes against a tolerance value

texts:
I have a series of text boxes in a table to gather input as below:

The user will input a target and actual value for each measurement point they require. I would then like to validate the actual values against the target values based upon the tolerance inputted in the tolerance textbox. The tolerance will be the same for all measurement points inputted, however the user will not always input all 10 measurement points.

I have also created a very basic class containing a function that accepts the target, actual and tolerance values then returns a Boolean depending on whether the actual value is within tolerance. I realise I could use this with a ruck load of if statements to check each textbox for input then use the class to perform the validation, however this seems like a lot of code repetition and a bit crude. My question being is there a better way I can perform this validation?

Class content

Public Class TolerenceHelper

Public Function IsInTolerence(ByVal target As Integer, ByVal actual As Integer, ByVal tolerence As Integer) As Boolean

    Dim upper As Integer = target + tolerence
    Dim lower As Integer = target - tolerence

    If actual < lower OrElse actual > upper Then
        Return False
    Else
        Return True
    End If
End Function

Calling the function as below:

Dim m1 As TolerenceHelper
Dim flag As Boolean = True

m1 = New TolerenceHelper

If m1.IsInTolerence(Integer.Parse(txtT1.Text), Integer.Parse(txtA1.Text), Integer.Parse(txtTolerance.Text)) = False Then
    flag = False
End If

If flag = False Then
    lblTest.Text = "Out of tolerance"
Else
    lblTest.Text = "In tolerance"
End If


texts: Triangulate the divisors and divide the triangulars

texts:
Project Euler 12 - Highly divisible triangular number

  The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be \$1 + 2 + 3 + 4 + 5 + 6 + 7 = 28\$. The first ten terms would be: \$1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\$

  (...) 28 is the first triangle number to have over five divisors.

  What is the value of the first triangle number to have over five hundred divisors?

I did spend quite a bit of time on this one to figure out a faster solution than what I first attempted. My first, very naive approach, to finding the number of divisors for a number was to loop through all the numbers and count them, like this:

public static long numDivisors(long number) {
    long count = number == 1 ? 1 : 2;
    for (int i = 2; i <= number / 2; i++) {
        if (number % i == 0) {
            count++;
        }
    }
    return count;
}

I knew there was a faster approach. And I didn't give up until I found one.

I realized, after factorizing some numbers, that the fastest way is to keep a track of the unique prime factors that make up the number, and use them to calculate the number of divisors.

For example, 36. It has 9 divisors in total, 1, 2, 3, 4, 6, 9, 12, 18, 36. We know though that 36 is 2*2*3*3. That's 2 factors of 2 and 2 factors of 3. So by choosing 0-2 2's and 0-2 3's we can get the 9 divisors of 36.

The same goes for a bigger number, such as 32063349528. If we prime-factorize it, it is 2 * 2 * 2 * 3 * 3 * 3 * 7 * 7 * 17 * 19 * 83 * 113. So 4*4*3*2*2*2*2 = 768 divisors.

public class ProjEuler12 {

    public static long triangleNumberN(long n) {
        if (n <= 0) {
            throw new IllegalArgumentException("n must be positive: " + n);
        }
        return (1 + n) * n / 2;
    }

    public static int divisorCount(long number) {
        if (number <= 0) {
            throw new IllegalArgumentException("number must be positive: " + number);
        }
        int divisors = 1;
        long lastNum = 0;
        int lastCount = 0;
        while (number != 1) {
            if (number % 2 == 0) {
                lastCount++;
                number /= 2;
                continue;
            }
            for (long i = 3; i <= number; i += 2) {
                if (number % i == 0) {
                    if (lastNum != i) {
                        divisors *= lastCount + 1;
                        lastCount = 1;
                        lastNum = i;
                    } else {
                        lastCount++;
                    }
                    number /= i;
                    break;
                }
            }
        }
        return divisors * (lastCount + 1);
    }

    public static void main(String[] args) {
        long result = LongStream.iterate(1, i -> i + 1)
                .map(ProjEuler12::triangleNumberN)
                .filter(n -> divisorCount(n) > 500)
                .findFirst().getAsLong();
        System.out.println(result);
    }

}

Any improvements possible? Can it be made even faster? Is the naming just as good as you would expect?


texts:
This is my solution of string calulator kata in scala(i'm new of tdd).
I'd like a general review of this.

  String Calculator

  Create a simple String calculator with a method int Add(string
  numbers) The method can take 0, 1 or 2 numbers, and will return their
  sum (for an empty string it will return 0) for example “” or “1” or
  “1,2”

  -Allow the Add method to handle an unknown amount of numbers

  -Allow the Add method to handle new lines between numbers (instead of commas). the following input is ok:  “1\n2,3”  (will equal 6) the
  following input is NOT ok:  “1,\n” (not need to prove it - just
  clarifying)

  -Support different delimiters to change a delimiter, the beginning of the string will contain a separate line that looks like this:
  “//[delimiter]\n[numbers…]” for example “//;\n1;2” should return three
  where the default delimiter is ‘;’ .

  -Numbers bigger than 1000 should be ignored, so adding 2 + 1001  = 2

  -Delimiters can be of any length with the following format:  “//[delimiter]\n” for example: “//[***]\n1***2***3” should return 6

package stringcalculator

    import org.scalatest.{BeforeAndAfter, FunSuite}

    class StringCalculetor3 extends FunSuite with BeforeAndAfter {

    private val calculator = new Calculator(new InputParser())

    before {}

    test("sum of empty string is 0") {

      assert(0 === sum(""))

    }

    test("sum of one number  string is number") {

      assert(5 === sum("5"))
      assert(6 === sum("6"))

    }

    test("sum of two  numbers  separated with comma") {

      assert(3 === sum("1,2"))
      assert(5 === sum("1,4"))

    }

    test("sum of 3  numbers separated with comma") {

      assert(6 === sum("1,2,3"))

    }

    test("sum of 2  numbers  separated new line  separetor") {

      assert(3 === sum("1\n2"))
      assert(6 === sum("1\n2,3"))

    }

    test("sum of 2 numbers with another separator") {

      assert(3 === sum("//;\n1;2"))

    }

    test("sum of 2 numbers with multiple separator") {
      assert(3 === sum("//[;]\n1;2"))
      assert(3 === sum("//[--]\n1--2"))
    }

    test("numbers > 1000 do not fall in the sum") {
      assert(3 === sum("1,2,1001"))
    }

    private def sum(in: String): Int = {
      calculator.sum(in)
    }

The calculator

package stringcalculator

/**
 * Created by MarcopTo on 20/10/2015.
 */
class Calculator(inputParser: InputParser) {

  def sum(input: String): Int = {
    val (in, separetor) = inputParser.parse(input)
    val numbers = in.split(separetor).map(_.toInt).filter(_ < 1001)
    numbers.sum
  }

}

The parser

package stringcalculator

/**
 * Created by MarcopTo on 20/10/2015.
 */
class InputParser() {

  private val defaultSeparator: String = ",|\n"
  private val singleSeparatorPosition: Int = 2

  def parse(input: String): (String, String) =
    if (containsSeparator(input)) {
      val endOfHeader: Int = input.indexOf("\n")
      val separetor = extractSeparator(input,endOfHeader)
      val in = extractInput(input,endOfHeader)
      (in, separetor)
    }else
      (defaultInput(input), defaultSeparator)

  private def defaultInput(input: String): String = if (input.isEmpty) "0" else input

  private def containsSeparator(in: String): Boolean = in.contains("//")

  private def extractInput(input: String,endOfHeader: Int): String = input.substring(endOfHeader+1)

  private def extractSeparator(in: String,endOfHeader: Int): String = {
    val header = getHeader(in, endOfHeader)
    if (containsMultipleSeparator(header))
      in.substring(in.indexOf("[") + 1, in.indexOf("]"))
    else
      header.charAt(singleSeparatorPosition).toString
  }

  private def getHeader(in: String, endOfHeader: Int): String = in.substring(0, endOfHeader)
  private def containsMultipleSeparator(in: String): Boolean = in.contains("[")

}


texts:
I have extended this class http://wiki.unity3d.com/index.php/CSharpMessenger_Extended to accept strings containing wildcards as eventTypes, therefore I am able to write things like

Messenger.AddListener("*", () => Console.WriteLine("woohoo, generic handler"));

But I am highly concerned about the performance of this implementation.

I've extended the Dictionary class like this:

public class EventDictionary : Dictionary<string, Delegate>
    {
        public Delegate[] GetHandlers(string Event)
        {
            List<Delegate> matches = new List<Delegate>();
            foreach (string pattern in Keys)
                if (Regex.IsMatch(Event, Regex.Escape(pattern).Replace( @"\*", ".*" ).Replace( @"\?", "." )))
                    matches.Add(this[pattern]);
            UnityEngine.Debug.Log(matches.Count);
            return matches.ToArray();
        }
    }

As you see, for every key in the dictionary, I first convert it to a regular expression, then check if it is a match for the event name, if it's so, add it to a collection and return the array.

But, this code runs in a game where the messenger script is used frequently, therefore I am really concerned about the performance of this approach.

I think storing regex's directly in the dictionary would be better but my main concern is about the regex matching.

Is my solution acceptable? If not what would be a better approach for solving my problem?


texts:
I wrote a simple thread pool, which works pretty well. I would like to see your review of it.

One important feature that I needed in the pool is the ability to wait until all the tasks that I sent to the pool are complete (so that later I could send other tasks that are dependent on the result of the previous tasks).

This is the basic task which you inherit from, to send tasks:

class Task
{
public :
    virtual void ExecuteTask() = 0;
};

This is the .h file of the Thread pool:

#include<time.h>
#include <Windows.h>
#include<list>

using namespace std;

class ThreadPool
{
public :
    ThreadPool(int threadCount=0);
    bool ScheduleTask(Task* task);
    bool WaitForWorkToBeFinished(DWORD dwMilliseconds);
    ~ThreadPool();

private :
    static DWORD WINAPI ThreadStart(LPVOID threadParameters);
    DWORD ThreadMain();

    list<Task*> mTasks;
    HANDLE* mThreads;
    int mThreadCount;
    CRITICAL_SECTION mCriticalSection;
    CONDITION_VARIABLE mConditionVariable;
    CONDITION_VARIABLE mConditionVariableTaskFinished;
    int mNumberOfTasksNotFinished;
    bool mConsum;
};

This is the CPP file:

#include "ThreadPool.h"

ThreadPool::ThreadPool(int threadCount)
{
    mThreadCount=threadCount;
    mThreads = new HANDLE[mThreadCount]; //This handles will be used to wait upon them

    InitializeCriticalSection(&mCriticalSection);
    InitializeConditionVariable(&mConditionVariable);
    InitializeConditionVariable(&mConditionVariableTaskFinished);
    mConsum = true;
    mNumberOfTasksNotFinished = 0;
    for(int i = 0; i< mThreadCount;i++)
        mThreads[i] = CreateThread(NULL, 0, ThreadStart, (void*)this, 0,NULL);
}

bool ThreadPool::ScheduleTask(Task* task)
{
    EnterCriticalSection(&mCriticalSection);
    mTasks.push_back(task); //This is a simple std::list
    mNumberOfTasksNotFinished++;
    LeaveCriticalSection(&mCriticalSection);

    WakeConditionVariable(&mConditionVariable); //Waking up the threads so they will know there is a job to do
    return true;
}

DWORD WINAPI ThreadPool::ThreadStart(LPVOID threadParameters) //Just a static function to help me use member function as a thread
{
    ThreadPool* referenceToThis = (ThreadPool*)threadParameters;
    return referenceToThis->ThreadMain();
}

DWORD ThreadPool::ThreadMain() //The main thread function
{
    do
    {
        Task* currentTask;
        EnterCriticalSection(&mCriticalSection);

        while(mTasks.size() ==0 && mConsum)
            SleepConditionVariableCS(&mConditionVariable,&mCriticalSection, INFINITE);

        if(!mConsum) //Destructor ordered on abort
        {
            LeaveCriticalSection(&mCriticalSection);
            return 0;
        }

        //If we got here, we successfully aquired the lock and the list<Task> is not empty
        currentTask = mTasks.front();
        mTasks.pop_front();

        LeaveCriticalSection(&mCriticalSection);

        currentTask->ExecuteTask();
        //delete currentTask;

        EnterCriticalSection(&mCriticalSection);
        mNumberOfTasksNotFinished--;
        LeaveCriticalSection(&mCriticalSection);

        WakeConditionVariable(&mConditionVariableTaskFinished);
    }while(mConsum);

    return 0;
}
//This function is very important, it gives the user the ability to send 10 tasks to the thread pool
// then to wait till all the tasks completed, and give the next 10 which are dependand on the result of the previous ones.
bool ThreadPool::WaitForWorkToBeFinished(DWORD dwMilliseconds)
{
    EnterCriticalSection(&mCriticalSection);
    while(mNumberOfTasksNotFinished!=0)
        SleepConditionVariableCS(&mConditionVariableTaskFinished,&mCriticalSection, INFINITE);
    LeaveCriticalSection(&mCriticalSection);

    return true;
}

ThreadPool::~ThreadPool()
{
    mConsum = false;
    WakeAllConditionVariable (&mConditionVariable);
    WaitForMultipleObjects(mThreadCount,mThreads, true, INFINITE);
    DeleteCriticalSection(&mCriticalSection);
}


texts:
NOTE: Here's the latest version of this program, since this question idled out.

This is a recreational script made to update my home server w/ the latest anime from HorribleSubs. I'd like to know if there are any obvious syntactical and performance improvements, details on my usage of Selenium and BS4 and whether or not this usage is proper. More features will be added later, but as it as now I feel there are ways to improve it. One idea I've had is to install uBlock Origin on the browser instance to decrease the number of elements to iterate over, but I don't know if this would be significant.

Windows Setup

Install Scoop to install any necessary programs.
Run the following commands for whatever you don't have installed:

scoop bucket add extras
scoop install python geckodriver qbittorrent
pip install beautifulsoup4 selenium python-qbittorrent

Enable the qBittorrent web interface.

Le Code

import urllib.request as Web
from bs4 import BeautifulSoup as bs4

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

from qbittorrent import Client

qb = Client('http://127.0.0.1:8080/')
# 'Bypass from localhost' should be enabled

# TODO: Check if this drive is full, and switch to an available one
DL_PATH = "E:/Torrents/"
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:48.0) Gecko/20100101 Firefox/48.0"
req = Web.Request('https://horriblesubs.info/current-season/', headers=headers)
src = Web.urlopen(req).read()
parser = bs4(src, features='html.parser')
divs = parser.body.find_all('div', attrs={'class': 'ind-show'})
size = len(divs)

for i, div in enumerate(divs):
    driver = webdriver.Firefox()
    driver.get('https://horriblesubs.info' + div.a['href'])
    WebDriverWait(driver, 50).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, 'rls-info-container')))

    # Expand the whole listing to get all the episodes
    elem = driver.find_element_by_class_name('show-more')
    while elem.text != 'No more results':
        elem.click()
        elem = driver.find_element_by_class_name('show-more')

    src = driver.page_source
    driver.close()
    parser = bs4(src, features='html.parser')
    hs = parser.body\
        .find('div', attrs={'class': 'hs-shows'})\
        .find_all('div', attrs={'class': 'rls-info-container'})

    for block in hs:
        # TODO: If a resolution is updated, delete the lower resolution alternative on disk
        link_rel = block.find('div', attrs={'class': 'rls-link link-1080p'})

        if (link_rel is None):
            link_rel = block.find('div', attrs={'class': 'rls-link link-720p'})

        if (link_rel is None):
            link_rel = block.find('div', attrs={'class': 'rls-link link-480p'})

        if (link_rel is not None):
            magnet = link_rel.find('a', attrs={'title': 'Magnet Link'})['href']
            qb.download_from_link(magnet, category='anime', savepath=DL_PATH + div.a.text)

    print('Progress: ' + str(round(((i + 1) / size) * 100, 2)) + '%')


texts: My first login class in PHP with PDO and bcrypt

texts:
This is the first time using a class. Please review this and tell me if it's secure and if it's the right way to do it.  The code itself is working, but I have doubts in the way I used all this.

// register.php
<?php
...
$db_password = $hash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 10));
....
// store in the 'users' table only the hash of the password provided by user.
?>

// clases/manageUsers.php

<?php
include_once('connect.php');

class ManageUsers{
public $link;
public $hash;

function __construct(){
    $db_connection = new dbConnection();
    $this->link = $db_connection->connect();
    return $this->link;
}
public function LogIn($id,$email,$pass,$hash){
    $query = $this->link->prepare("SELECT id,username,email,pass FROM users WHERE email = :email AND activated = 'y' LIMIT 1");
    $query->bindParam(':email', $email, PDO::PARAM_STR);
    $query->execute();
    $data = $query->fetch(PDO::FETCH_ASSOC);
    return $data;

        if(password_verify($pass,$hash)){
            return TRUE;
        }else{
            return FALSE;
        }
}

public function logOut($id){
    $query=$this->link->prepare("UPDATE users SET verify = '0', activenow = 'n' WHERE id= :id LIMIT 1");
    $query->bindParam(':id', $id, PDO::PARAM_INT);
    $query->execute();
    $countsOut = $query->rowCount();
    return $countsOut;
}

}
?>

// login.php

<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');

$errorMsg = '';
$email = '';
$pass = '';
$hash="";
$id='';
$token='';
$token = md5(uniqid(rand(),TRUE));

if (isset($_POST['e'])) {
$email = $_POST['e'];
$pass = $_POST['p'];

$email = stripslashes($email);
$pass = stripslashes($pass);
$email = strip_tags($email);
$pass = strip_tags($pass);

if ((!$email) || (!$pass)) {
    //header("location: index.php");
    $errorMsg = 'Please fill in both fields';

} else {
    include_once 'clases/manageUsers.php';
    include_once 'clases/connect.php';

$loginUsers = new ManageUsers();
$data = $loginUsers->LogIn($id,$email,$pass,$hash);
            $hash=$data['pass'];

    if(password_verify($pass,$hash) == TRUE){

        $db = new dbConnection();// <- New connection to database to update members table
        $dbh = $db->connect();   //  with new login data. I think this is WRONG...

            session_regenerate_id(TRUE);
            $id=$data['id'];
            $username=$data['username'];

            $query = $dbh->prepare("UPDATE users SET  verify= :token, lastlog=NOW(), activenow='y' WHERE id= :id LIMIT 1");
            $query->bindParam(':id', $data['id'], PDO::PARAM_INT);
            $query->bindParam(':token', $token, PDO::PARAM_STR);
            $query->execute();

                $_SESSION['id'] = $data['id'];
                $_SESSION['username'] = $data['username'];
                $_SESSION['token'] = $token;

            header("location: profile.php?id=$id");
            exit();

    } else {
            session_destroy();
            header("location: login.php");
            $errorMsg = "Incorrect login data, please try again";
    }
}
}
?>

//logout.php

<?php
session_start();
include_once 'clases/manageUsers.php';

if(isset ($_SESSION['id']) && isset ($_SESSION['username']) && isset ($_SESSION['token'])){
$id=$_SESSION['id'];
    $LgOut = new ManageUsers();
    $loggingOut = $LgOut->logOut($id);
    if($loggingOut > 0){
    session_destroy();
    session_regenerate_id(TRUE);
    header ('location: login.php');
    }else{
    echo 'Not Logged Out';
    }
}
?>


texts:
I have the following function to save points cloud in PLOT3D format:

def write(filename, mesh):
    """
    Write the mesh to filename in PLOT3D format.
    filename: is the name of the output file.
    mesh: is a numpy array of size (N,2) or (N, 3) where N is the number of points. mesh[i] is a numpy array coordinates of the i'th point.

    """
    points = mesh.points
    imax = np.unique(points[:, 0]).size
    jmax = np.unique(points[:, 1]).size

    _2d = False
    if points.shape[1] == 2:
        _2d = True
    elif np.unique(points[:, 2]).size == 1:
        _2d = True

    with open(filename, "w") as p3dfile:
        if not _2d:
            kmax = np.unique(points[:, 2]).size
            print(imax, jmax, kmax, file=p3dfile)
            for value in points.flatten(order="F"):
                print(value, file=p3dfile)
        else:
            print(imax, jmax, file=p3dfile)
            for value in points[:, 0:2].flatten(order="F"):
                print(value, file=p3dfile)

For large number of points this function is very slow.

I appreciate any suggestion to improve the code above.


texts:
I have a class with 2 date properties: FirstDay and LastDay.  LastDay is nullable.  I would like to generate a string in the format of "x year(s) y day(s)".  If the total years are less than 1, I would like to omit the year section.  If the total days are less than 1, I would like to omit the day section.  If either years or days are 0, they should say "day/year", rather than "days/years" respectively.

Examples:
2.2 years:             "2 years 73 days"
1.002738 years:   "1 year 1 day"
0.2 years:             "73 days"
2 years:                "2 years"

What I have works, but it is long:

private const decimal DaysInAYear = 365.242M;

public string LengthInYearsAndDays
{
    get
    {
        var lastDay = this.LastDay ?? DateTime.Today;
        var lengthValue = lastDay - this.FirstDay;

        var builder = new StringBuilder();

        var totalDays = (decimal)lengthValue.TotalDays;
        var totalYears = totalDays / DaysInAYear;
        var years = (int)Math.Floor(totalYears);

        totalDays -= (years * DaysInAYear);
        var days = (int)Math.Floor(totalDays);

        Func<int, string> sIfPlural = value =>
            value > 1 ? "s" : string.Empty;

        if (years > 0)
        {
            builder.AppendFormat(
                CultureInfo.InvariantCulture,
                "{0} year{1}",
                years,
                sIfPlural(years));

            if (days > 0)
            {
                builder.Append(" ");
            }
        }

        if (days > 0)
        {
            builder.AppendFormat(
                CultureInfo.InvariantCulture,
                "{0} day{1}",
                days,
                sIfPlural(days));
        }

        var length = builder.ToString();
        return length;
    }
}

Is there a more concise way of doing this (but still readable)?


texts:
I'm playing around with RAII a bit lately and I wan't to know if/how I can improve this (quite simple but very helpful) class.

A word to two decisions I've made and why:

No error handling in construct. I don't think throwing a exception would be appropriate so it's up to the user to check valid().
No copy constructor. I don't see how this could be useful. Since two objects can't share the same ptr, a copy could malloc another chunk of memory with same size and copy the old one, but I don't know if this would be useful at all.

template<typename T>
class MallocRaii {
public:
    MallocRaii(size_t size) : ptr(nullptr) {
        this->ptr = (T*)malloc(sizeof(T) * size);
    }

    ~MallocRaii() {
        if(this->ptr != nullptr)
            free(this->ptr);
    }

    MallocRaii(const MallocRaii& other) = delete; //Copy constructor
    MallocRaii& operator=(const MallocRaii& other) = delete; //Copy assignment

    MallocRaii(MallocRaii&& other) { //move constructor
        std::swap(*this, other);
    }

    MallocRaii& operator=(MallocRaii&& other) { //Move assignment
        std::swap(*this, other);
    }

    bool valid() const {
        return ptr == nullptr;
    }

    T* ptr;
};

Use it like this:

MallocRaii<unsigned long> buffer(256);
some_c_api_read_pixel_from_file(buffer.ptr, 256);
//Reads 256 pixels with 4 components from file,
// the class allocated 1024 bytes (256 * sizeof unsigned long)
do_something_with_the_data(buffer.ptr);
return; //class free's memory


texts:
I'm new in Python and consequently I am searching for a specific solution for code development. I already asked some pythonic question today and want to present my whole problem.  I have found some solution, but I really have interest to develop easier and clearer code in Python, so all improvements are welcome.

For example, in some school, the students are ordered to some of 3 different classes. Now I have some set of graduated students and want to know, how many graduated students are in some class.

I create next code:

physic = ['id_1', 'id_2', 'id_4']
chemistry = ['id_5', 'id_7']
math = ['id_3', 'id_8', 'id_9']

graduatedPhysic = []
graduatedChemistry = []
graduatedMath = []

classes = [physic, chemistry, math]
graduated = [graduatedPhysic, graduatedChemistry, graduatedMath]

Every class has the different number of students (given by students IDs) and gratuated Classes are at the first empty. I combine it also to list of lists.

Then I use my code:

graduatedlist = ['id_2', 'id_5', 'id_7']

for stud in graduatedlist:
    for pos1 in range(len(graduated)):
        for pos2 in range(len(classes[pos1])):
            if stud.find(classes[pos1][pos2]) != -1:
                graduated[pos1].append((stud))

This code works, but does not look great... I would be very grateful for comments! For example, I tried to implement the idea with itertools.product():

for item_1, item_2 in itertools.product(range(len(graduated)), range(len(classes[item_1])):

I have a problem with a declaration of item_1.

I have also a feeling that the lists isn't the best solution for implementation, but for DataFrame I need the column of similar length and every class can have the different number of the students.

For the special interest are two points:

How I really can improve my for-loop?
What I can use instead of list declaration?


texts: A program to find out the number of odd and even Fibonacci numbers between given range

texts:
I built a program in C that can tell how many odd and even Fibonacci numbers there are between a given range.

  Input Specification

  First line of the input contains T, representing the number of test cases (1 ≤ T ≤ 50). Each test case contains two integers N and M (1 ≤ N ≤ M ≤ 1018) and (|N-M| ≤ 105), where N is the Nth Fibonacci number and M is the Mth Fibonacci number of the sequence.

  Output Specification

  Case T:
  Odd = total number of odd Fibonacchi numbers between N and M
  Even = total number of even Fibonacchi numbers between N and M

The full code

#include <stdio.h>
#include <math.h>

int main()
{
    int T, i, j, k;
    scanf("%d", &T);

    for (i=0; i<T; i++)
    {
        int N, M, val;
        scanf("%d%d", &N,&M);
        val = abs(N-M)+1;

        int n,m;
        if (M>N) { n=N; m=M; }
        if (N>M) { n=M; m=N; }

        int b_tri, e_tri, even=0, odd=0;
        if (n%3==1) { b_tri=3; even++; odd+=2; }
        if (n%3==2) { b_tri=2; odd+=2; }
        if (n%3==0) { b_tri=1; odd++;  }

        if (m%3==1) { e_tri=1; even++; }
        if (m%3==2) { e_tri=2; odd++;  even++; }
        if (m%3==0) { e_tri=3; odd+=2; even++; }

        val-=(e_tri+b_tri);
        val/=3;

        for (j=0; j<val; j++)
        {
            even++;
            odd+=2;
        }

        printf("Case %d:\nOdd = %d\nEven = %d\n", i+1, odd, even);
    }

    return 0;
}

Logic

1st Fibonacci number is 0 (even).
2nd Fibonacci number is 1 (odd).
3rd Fibonacci number is 1 (even + odd = odd).
4th Fibonacci number is 2 (odd  + odd = even).
5th Fibonacci number is 3 (odd + even = odd).
6th Fibonacci number is 5 (even + odd = odd).
7th Fibonacci number is 8 (even).
8th Fibonacci number is 13 (odd).
9th Fibonacci number is 21 (odd).

I'd like advice on:

Using mathematical formulas instead of loops to calculate this
Making the code more efficient


texts:
This is a code uses mergesort algorithm to sort a list of elements.What are the possible improvements on the code?Also are there any unhealthy coding practice involved in this code?

#include<iostream>
#include<vector>
#include<random>
#include<chrono>
using namespace std;
using namespace std::chrono;
vector<int> merge(vector<int> a,vector<int> b){
    int i=0;
    int j=0;
    vector<int> result;
    while(i<a.size()&&j<b.size()){
        if(a[i]<b[j]){
            result.push_back(a[i]);
            i++;
        }
        else{
            result.push_back(b[j]);
            j++;
        }
    }
    while(i<a.size()){
        result.push_back(a[i]);
        i++;
    }
    while(j<b.size()){
        result.push_back(b[j]);
        j++;
    }
    return result;
}

vector<int> mergesort(vector<int> a,int low,int hi){
    vector<int> b,c,result;
    if(low==hi)
        return {a[hi]};
    b=mergesort(a,low,(low+hi)/2);
    c=mergesort(a,(hi+low)/2+1,hi);
    result=merge(b,c);
    return result;
}
int main(){

    std::random_device rd; // obtain a random number from hardware
    std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(0,90); // define the range
    vector <int> num;
    for(int i=0;i<30;i++)
        num.push_back(distr(eng));
    vector<int> a=mergesort(num,0,num.size()-1);
    for(auto &i:a)
        cout<<i<<" ";
}


texts: Return value when the requested variable returns null

texts:
I have a method that returns a list from a HTML page:

private List<HtmlNodes> GetRelevantNodes(HtmlDocument aHtmlDoc, string aID)
{
    List<HtmlNode> nodes = new List<HtmlNode>();

    HtmlNode currentDiv = aHtmlDoc.GetElementbyId(aID);
    if (currentDiv == null)
            return null;
    else
            //Do stuff - fill the nodes list...

    return nodes;
}

I'm not sure what to do with the return value in case the currentDiv variable is null. Obviously I can't continue the method regularly and I need to return from this method with some indication that there's no such div.

If I return null and handle it up the stack it'll work fine but it's less readable code (at list in my opinion... don't you think?). Another thing I can add is an out string with the error message and maybe use it later for the end user output but that still doesn't solve my readable problem.

I'd be happy to hear your ideas and advice.


texts: Redirecting arriving customers to the nearest empty queue

texts:
I have a task to make a checkout line controller. First it receives, as input, an amount of checkouts and commands. Then commands that are C for coming and L for leaving, and after those the number of the checkout they are coming/leaving. Also, if there is someone at the checkout, they should be sent to the nearest empty one. If 2 are equally near, the one with the lowest number is chosen.

Input could be:

3 5
C 1
C 2
L 1
C 1
C 1

As output it just tells the checkout where each arriving customer is served. So output would be:

1
2
1
3

Code:

#include <iostream>
#include <vector>
using namespace std;

int main () {
    int n, m, checkout;
    char action;
    vector <int> output (0);

    cin >> n >> m;

    vector <bool> state (n,false); //

    for (int i = 0; i < m; i++) {
        cin >> action >> checkout;
        checkout--; //Aligns checkout number with vectors number

        if (action == 'C') { //If someone comes
            if (state[checkout] == false) { //If the checkout he comes to is empty
                state[checkout] = true; // If it is, it's not anymore
                output.push_back(checkout + 1);
            } else { // If it isn't, check which is the closest empty one
                for (int i = 1; i < n; i++) { //Loops through below and above checkouts
                    if (checkout - i >= 0) {
                        if (state[checkout - i] == false) {
                            state[checkout - i] = true;
                            output.push_back(checkout - i + 1);
                            break;
                        }
                    }
                    if (checkout + i < n) {
                        if (state[checkout + i] == false) {
                            state[checkout + i] = true;
                            output.push_back(checkout + i + 1);
                            break;
                        }
                    }
                }
            }
        }
        if (action == 'L') {
            state[checkout] = false;
        }
    }
    for ( int j = 0; j < output.size(); j++) {
        cout << output[j] << endl; //Outputs after all input is over (somone said I should do this)
    }
}

My program runs too slowly. I use codejudge.net to check if it is working properly. I have already improved it a lot, from what I started with, but it still doesn't cut it.

This question was originally posted on Stack Overflow.


texts:
I've been reading about loops this morning, to try to improve this snippet of code:

$deliveryoutcode1 = array();
$deliveryoutcode1 = explode(",",$rows['deliveryoutcode1']);
$deliveryoutcode2 = array();
$deliveryoutcode2 = explode(",",$rows['deliveryoutcode2']);
$deliveryoutcode3 = array();
$deliveryoutcode3 = explode(",",$rows['deliveryoutcode3']);

I started to read about loops this morning and I came up with this:

$i=1;
while ($i <= 3) { // Output values from 0 to 3
    $deliveryoutcode[$i] = array();
    $deliveryoutcode[$i] = explode(",",$rows['deliveryoutcode' . $i . '']);
    $i++;
}

This works great, but I'm wondering if there is a better way to do this. It appears as though I've come up with the best way but as this is my first attempt at loops, I better ask the experts.


texts: Re-use of read/write object , for multiple objects

texts:
I have read a lot about serialization and I cannot figure out how I am able to serialize then deserialize multiple objects. I am very much a newb to Java, so please bear with me.

My code currently works, but my logic is flawed. I have an object called "club", which contains several fields to be serialized e.g teamname. I have used case statements with a switch, so that I can serialize more than one object, but I ended up re-trying my try/catch block and streams to get it to work.

Both objects can be independently written to a file, but I am unclear of the syntax to use, to ensure I can implement the following pseudocode.

if teamName = club1
and player would like to save the game
serialize club1
then de-serialize club1, if player selected load game.

Finally, could someone point me in the right direction of writing a game "state" to a file, rather than just pre-defined fields that I have declare as constants.

Snippets of my code are as follows :

switch (option) {

    case 1:
    chooseTeam(clubName);
    exit = true;
    break;

    case 2:
    Serialize saveclub1 = new Serialize();
    saveclub1.Serialize();
    exit = true;
    break;

    case 3:
        DeSerialize load = new DeSerialize();
        load.DeSerialize(clubName);
        exit = true;
    break;

    case 4:
    credits();
    exit = true;
    break;

    case 5:
    exit = true;
    System.out.println("Goodbye!");
    break;

    case 6:

    Serialize saveclub2 = new Serialize();
    saveclub2.Serialize();
    ClubInfo club2 = new ClubInfo();
      club2.teamName = "Aston Villa";
      club2.stadium = "Villa Park";
      club2.division = "Premier League";
      club2.SSN = 11122333;
      club2.stadiumCapacity = 40000;
    try
        {
         FileOutputStream fileOut =
         new FileOutputStream("/home/cg/root/club.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
     out.writeObject(club2);
     out.close();
         fileOut.close();

      //System.out.printf("Serialized data is saved in C:/tmp/club.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
     exit = true;
        break;

public void DeSerialize(String[] clubName)
   {
      ClubInfo club = null;

      try
      {
         FileInputStream fileIn = new FileInputStream("/home/cg/root/club.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         club = (ClubInfo) in.readObject();

         in.close();
         fileIn.close();

      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Club class not found");
         c.printStackTrace();
         return;
      }

public void Serialize()
   {

      ClubInfo club = new ClubInfo();
      club.teamName = "Arsenal";
      club.stadium = "Emirates";
      club.division = "Premier League";
      club.SSN = 11122333;
      club.stadiumCapacity = 60000;

      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/home/cg/root/club.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
     out.writeObject(club);

         out.close();
         fileOut.close();

      System.out.printf("Serialized data is saved in C:/tmp/club.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }

   }
}

public class ClubInfo implements java.io.Serializable{

   public String teamName;
   public String stadium;
   public String division;
   public transient int SSN;
   public int stadiumCapacity;

} // end ClubInfo class


texts: 15 line Rust program, which writes the numbers 1 to N to a file

texts:
I have this simple Rust program, which creates a file called numbers.txt and writes the numbers 1 to N (N is here 10000000) to it, separated with newlines:

use std::fs::File;
use std::io::Write;

const N: i32 = 1e7 as i32;

fn main() {
    let mut data = String::new();

    for i in 1..=N  {
        data.push_str(&format!("{0}\n", i));
    }

    let mut f = File::create("numbers.txt").expect("Unable to create file");
    f.write_all(data.as_bytes()).expect("Unable to write data");
}

I've been running and timing the program with:

$ time cargo run --release

numbers.txt after running:

1
2
3
4
...
9999999
10000000

I've timed the execution of the program, and it takes around 4.8 seconds to run on my machine. I tried timing just the string building, by commenting out the last two lines, and the time taken stayed pretty much the same. We can conclude that the bottleneck is the data string building and not writing to the file.

How could I make building data faster? Should I use something else than a String?


texts: Class to represent a mutable date and time

texts:
What would be the best way to refactor this class - if any at all?  I'm using this class to get the current date and time and also to modify this date by being able to change its date and time.  I have a lot of functions which appear to do similar things subtractSeconds, subtractMinutes, subtractDays etc.. But I'm not sure what software design principle I should be looking into more.  My gut tells me I need to use an interface or abstract class to reduce my code and make it simpler?

class AmazonDate
{
    protected $seconds;

    protected $days;

    protected $months;

    protected $date;

    protected $minutes;

    protected $hours;

    public function __construct()
    {
        date_default_timezone_set('America/Chicago');
        $date = new DateTime(date('Y/m/d H:i:s'));
        $this->setDate($date);
    }

    public function currentDate()
    {
        date_default_timezone_set('America/Chicago');
        $date = new DateTime(date('Y/m/d H:i:s'));
        $this->setDate($date);
    }
    public function setDate($date)
    {
        $this->date = $date;
    }
    public function getDate()
    {
        return $this->date;
    }

     public function subtractSeconds($seconds)
     {
         $this->seconds = $seconds;

         $date = $this->getDate();
         $date = date_modify($date, '- ' . $this->seconds . ' second');
         $this->setDate($date);
         return $this;
     }

    public function subtractMinutes($minutes)
    {
        $this->minutes = $minutes;

        $date = $this->getDate();
        $date = date_modify($date, '- ' . $this->minutes . ' minutes');
        $this->setDate($date);
        return $this;
    }

    public function subtractHours($hours)
    {
        $this->hours = $hours;

        $date = $this->getDate();
        $date = date_modify($date, '- ' . $this->hours . ' hours');
        $this->setDate($date);
        return $this;
    }

    public function subtractDays($days)
    {
        $this->days = $days;

        $date = $this->getDate();
        $date = date_modify($date, '- ' . $this->days . ' days');
        $this->setDate($date);
        return $this;
    }

    public function subtractMonths($months)
    {
        $this->months = $months;

        $date = $this->getDate();
        $date = date_modify($date, '- ' . $this->months . ' months');
        $this->setDate($date);
        return $this;
    }
     public function printDate()
     {
         $date = $this->getDate();
         return $this->dateToString($date);
     }

    /**
     * @param $date
     * @return mixed
     */
    private function dateToString(DateTime $date)
    {
        return $date->format('c');
    }
}


texts: Scraping required fields exhausting a full website

texts:
I've written some script in python using lxml library which is capable of dealing with a webpage with complicatedly layed-out next page links. My scraper is able to parse all the next page links without going to the next page and hardcoding any number to the lastmost link and scrape the required fields flawlessly. Although I tried to do the whole thing specklessly, any improvement on this will be highly appreciable. Here is what I've tried with:

import requests
from lxml import html

main_link = "https://www.yify-torrent.org/search/1080p/"
base_link = "https://www.yify-torrent.org"

def get_links(item_link):
    response = requests.get(item_link).text
    tree = html.fromstring(response)
    last_page = tree.cssselect('div.pager a:contains("Last")')[0].attrib["href"].split("/")[-2].replace('t-','')
    links = [item_link +"t-{0}/".format(page) for page in range(int(last_page) +1)]
    for link in links:
        process_docs(link)

def process_docs(nextpage_link):
    response = requests.get(nextpage_link).text
    tree = html.fromstring(response)
    for items in tree.cssselect('div.mv'):
        name = items.cssselect('h3 a')[0].text
        try:
            genre = items.xpath('.//div[@class="mdif"]//li[b="Genre:"]/text()')[0] # I don't know If css selector could do this
        except IndexError:
            genre = ""

        try:
            imd = items.xpath('.//div[@class="mdif"]//li[b="Rating:"]/text()')[0] # Used xpath in lieu of css selector
        except IndexError:
            imd = ""

        print(name, genre, imd)

get_links(main_link)


texts:
I have implemented binary exponentiation. Is this good?

def quad_pow(base, exponent, modul):
    alpha = (bin(exponent).replace('0b', ''))[::-1]
    a = 1
    b = base

    for i in range(0, len(alpha)):
        if int(alpha[i]) == 1:
            a = (a * b) % modul
        b = (b*b) % modul
    return a


texts:
I am developing my social network website, and I want to know if it's optimized or not.  I am good at ASP.NET 4 and WebForms, but not MVC or JavaScript.

This code is for "liking" a post.  I did not use any JavaScript to do that.  Is this "like" button optimized or not?  How many online users can my server handle (assume max online user is 500-700)?

protected void like_Click(object sender, EventArgs e)
{
    try
    {
        int ID = Convert.ToInt32(Session["ID"].ToString());
        LinkButton like = (LinkButton)sender;
        GridViewRow gvrow = (GridViewRow)like.NamingContainer;
        int ActivityTypeID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["ActivityTypeID"].ToString());
        int SourceID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["SourceID"].ToString());
        LinkButton unlike = gvrow.FindControl("unlike") as LinkButton;
        Label numberoflike = gvrow.FindControl("numberoflike") as Label;
        like.Visible = false;
        unlike.Visible = true;
        if (ActivityTypeID == 1 || ActivityTypeID == 4)
        {
              //check users liked it before or not ?
              // this code will run a stored procedure
            if (BusinessLayer.StatusLike_Table.GetByIsliked(SourceID, ID, 1) == 0)
            {
              // make an object of like table
                BusinessLayer.StatusLike_Table nl = new BusinessLayer.StatusLike_Table();
                nl.Id = Convert.ToInt32(Session["ID"].ToString());
                nl.Statusid = SourceID;
                nl.Statuslikedate = System.DateTime.Now;
                nl.Save();
                  // saves like to database
                numberoflike.Text = BusinessLayer.StatusLike_Table.GetByNumberOfLike(SourceID).ToString();
             // update number of like by counting all likes for this post
            }

                     }
        else if (ActivityTypeID == 2 || ActivityTypeID == 5)
        {
            if (BusinessLayer.StatusLike_Table.GetByIsliked(SourceID, ID, 2) == 0)
            {
                BusinessLayer.PhotoStsLike_Table nl = new BusinessLayer.PhotoStsLike_Table();
                nl.Id = Convert.ToInt32(Session["ID"].ToString());
                nl.Photostsid = SourceID;
                nl.Photostslikedate = System.DateTime.Now;
                nl.Save();
                numberoflike.Text = BusinessLayer.PhotoStsLike_Table.GetByNumberOFlike(Convert.ToInt32(SourceID)).ToString();
            }
        }
    }
    catch (Exception ee)
    {
    }
}

For the commenting system and posting system and etc, the code is the same as above.  If all the code will be server-side and does not use any JavaScript, does it cause to have a slow website or not?

"Likes" are store on a database like this:

likeID int identity specification true ! identity increment true and 1
PostID int
ID int
Date Datetime

I don't use any caching and I want to optimize user experience.


texts:
Whenever I needed something similar like a "Class" in JavaScript, I wrote it like this:

function Point(x, y){
    var self = this;
    self.x = x;
    self.y = y;
    self.dist = function(){
        return Math.sqrt( (self.x*self.x) + (self.y*self.y) );
    }
}

var p = new Point(10, 20);
p.x = 30;
alert(p.dist);

I declared a function and wrote the constructor directly into it. Public variables and methods have the self.-operator in front of it.

Now I took a look at TypeScript, which declares the exact same function this way:

var Point = ( function(){
    function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    Point.prototype.dist = function(){
        return Math.sqrt( (this.x*this.x) + (this.y*this.y) );
    }
    return Point;
})();

var p = new Point(10, 20);
p.x = 30;
alert(p.dist());

This definition makes use of a closure, and uses prototype.

My Questions:

What are the advantages/disadvantages of the 2 definitions?
Which method is more efficient?
Which method should I prefer to use (when I don't use TypeScript)?


texts: Selecting up to three thumbnail images using jQuery

texts:
I have written something in jQuery but I'm not sure whether it is an elegant solution. Every click needs to check the DOM for classes/and add and remove classes. Any feedback or suggestions would be appreciated. The idea is for a user to only be able to select 3 images.

jQuery:

$('.thumbnail-gallery-items li').click(function () {
$(this).toggleClass('selected');
var selectionCount = $('.selected').length;
if (selectionCount == 2 ) {
    $('.thumbnail-gallery-items li').addClass('disabled');
} else {
    $('.thumbnail-gallery-items li').removeClass('disabled');
}});

CSS:

.thumbnail-gallery-items li.selected:after {
  font-family: 'Material Icons';
  content: '\E876';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  background: rgba(155, 89, 182, 0.2);
  z-index: 1;
  color: #fff;
  font-size: 32px;
  padding: 5px;}

.disabled:not(.selected) {
  pointer-events: none}


texts: How to sort and search in JavaScript large set

texts:
The array "scores" tells the total points for each person involved in a contest. So for example:
User A: 100 points
User B: 90 points
User C: 90 points
User D: 80 points
User E: 75 points
User F: 60 points

According to above scores we also have this ranking:
User A: #1
User B: #2
User C: #2
User D: #3
User E: #4
User F: #5

This ranking method follows the Dense Ranking method.
Then we have a user named alice. If she gets 55 points, she will rank at position #6 (according to ranking above).
If she scores 90 points, she will rank at position #2. And so on.
I actually have an array containing different "sessions" for alice. So having for example:
[55, 90]
This means that first time will alice be ranked at position #6. While second time she will be ranked at position #2.
I coded this, and it work. However, this does not seem to be very effective. For large datasets, with half million entries in the scores-array, it times out. This is the code:
const getPosition = (element, scores) => {
    scores.push(element);
    scores.sort(function (a,b) { return b-a; });
    return scores.indexOf(element)+1;
}

function climbingLeaderboard(scores, alice) {
    var uniqueSet = new Set(scores);
    scores = [...uniqueSet];
    var positions = [];
    let aliceIndex = 0;
    while(aliceIndex < alice.length){
        positions.push(getPosition(alice[aliceIndex], scores));
        aliceIndex++;
    }
    return positions;
}

function main() {
    const scores = [100, 90, 90, 80, 75, 60];
    const alice = [50, 65, 77, 90, 102];
    let result = climbingLeaderboard(scores, alice);
    console.log(result.join("\n") + "\n");
}

I guess the "sort"-function and/or searching for the element in the array with indexOf is the problem. But I could not find a way to make these two operations more efficient.


texts: need some guidance for better coding practice

texts:
Given a int optimumMemory and int[] array with list of available memories find the pair of indexes of memories whose sum of the values will be equal to the optimumMemory?
If there exists more than one such pair whose sum of values are equal to the optimumMemory then filter out the indexes for the below conditions
condition1: find the pair of indices which has maximumMemory
condition2: If there exists 2 pairs with same maximumMemory then select the pair with lowest index
Example: int optimumMemory = 10MB int[] availableMemories= [6,3,8,1,1,4,9,2,9,7]
The pair of indices whose sum is equal to 10MB ={(0,5),(1,9),(2,7),(3,6),(3,8),(4,6),(4,8)};
applying condition1 to the above list ={(3,6),(3,8),(4,6),(4,8)};
applying condition2 to the above list will result in only one order pair = {(3,6)}
import com.sun.tools.javac.util.Pair;

public class Test(){

public static void main(String[] args){
         int optimumMemory = 10;
         int[] list = new int[]{6,3,8,1,1,4,9,2,9,7};
         Pair<Integer,Integer> result = new Pair<>(Integer.MIN_VALUE,Integer.MIN_VALUE);
         //2 pointer approach
         for(int i=0;i<list.length;i++){
            for(int j=i+1;j<list.length;j++){
                //checking if the sum of memory is equal to optimumMemory
                if(list[i]+list[j] == optimumMemory){
                    Pair<Integer,Integer> pair = new Pair<>(i,j);
                    //this happens only once, when the very first pair that satisfies the condition is found
                    if(result.fst==Integer.MIN_VALUE && result.snd == Integer.MIN_VALUE)
                    {
                        result = pair;
                        continue;
                    }
                    int maximumMemoryInResult = Math.max(list[result.fst],list[result.snd]);
                    int maximumMemoryInPair = Math.max(list[pair.fst],list[pair.snd]);
                    //applying **condition1**
                    if(maximumMemoryInResult < maximumMemoryInPair){
                        result = pair;
                        continue;
                    }//end of condition1
                    //applying **condition2**
                    else if(maximumMemoryInResult == maximumMemoryInPair){
                        int minIndexInResult = Math.min(result.fst,result.snd);
                        int minIndexInPair = Math.min(pair.fst,pair.snd);
                        if(minIndexInPair<minIndexInResult){
                            result = pair;
                            continue;
                        }
                    }//end of condition2
                }
            }//end of j loop
        }// end of i loop
   }// end of main method
}

Is there any way to improve the code I posted?


texts:
I have implemented HKDF in Rust, which passes all test vectors from RFC 5869, using HKDF with HMAC-SHA256. I also have a function to compare byte arrays in constant time, which I hope someone could confirm is correctly done. Any type of feedback is welcome.

EDIT: I mainly mean feedback on hkdf_compute(). HMAC in hkdf_extract() is defined in another module and not included here.

HKDF

pub struct Hkdf {
  pub salt: Vec<u8>,
  pub data: Vec<u8>,
  pub info: Vec<u8>,
  pub hmac: usize,
  pub length: usize,
}

impl Drop for Hkdf {
  fn drop(&mut self) {
    //println!("DROPPING");
    self.salt.clear();
    self.data.clear();
    self.info.clear()
  }
}

impl Hkdf {
  /// Return HMAC matching argument passsed to Hkdf.
  pub fn hkdf_extract(&self, data: &[u8], salt: &[u8]) -> Vec<u8> {
    let hmac_res = Hmac {
        secret_key: salt.to_vec(),
        message: data.to_vec(),
        sha2: self.hmac
    };

    hmac_res.hmac_compute()
  }

  /// The HKDF Expand step. Returns an HKDF.
  pub fn hkdf_compute(&self) -> Vec<u8> {
    // Check that the selected key length is within the limit.
    if self.length as f32 > 255_f32 * (self.hmac / 8) as f32 {
        panic!("Derived key length above max. 255 * (HMAC OUTPUT LENGTH IN BYTES)");
    }

    let n_iter = (self.length as f32 / (self.hmac / 8) as f32).ceil() as usize;

    let mut con_step: Vec<u8> = vec![];
    let mut t_step: Vec<u8> = vec![];
    let mut hkdf_final: Vec<u8> = vec![];

    for x in 1..n_iter+1 {
            con_step.append(&mut t_step);
            con_step.extend_from_slice(&self.info);
            con_step.push(x as u8);
            t_step.extend_from_slice(&self.hkdf_extract(
                &con_step,
                &self.hkdf_extract(&self.data, &self.salt))
            );
            con_step.clear();

            hkdf_final.extend_from_slice(&t_step);
    }

    hkdf_final.truncate(self.length);

    hkdf_final
  }
}

Compare constant time:

#[inline(never)]
/// Comparison in constant time.
pub fn compare_ct(x: &[u8], y: &[u8]) -> bool {

  let length = x.len();

  if length != y.len() {
    false;
  }

  let mut result: u8 = 0;

  for n in 0..length {
    result |= x[n] ^ y[n];
  }

  result == 0
}


texts: Generating a 64 bit unique integer in Java

texts:
I need to generate a 64 bit unique integer in Java. I need to make sure that there is very few or no collisions if possible.

I came up with the below code which works fine:

public class TestUniqueness {

    private static final AtomicLong TS = new AtomicLong();

    public static void main(String[] args) {
        // for testing, just added the for loop
        for (int i = 1; i <= 100000; i++) {
            System.out.println(getUniqueTimestamp());
        }
    }

    public static long getUniqueTimestamp() {
        long micros = System.currentTimeMillis() * 1000;
        for (;;) {
            long value = TS.get();
            if (micros <= value)
                micros = value + 1;
            if (TS.compareAndSet(value, micros))
                return micros;
        }
    }
}

I will be running the above code in production.


texts: Pandas Filtering based on the length of the same kind variables in a column

texts:
In my real case I have a set of time series related to different IDs stored in a single DataFrame
Some are composed by 400 samples, some by 1000 samples, some by 2000.
They are stored in the same df and:
I would like to drop all the IDs made up of time series shorter than a custom length.
I wrote the following code, but I think is very ugly and inefficient.
import pandas as pd
import numpy as np

dict={"samples":[1,2,3,4,5,6,7,8,9],"id":["a","b","c","b","b","b","c","c","c"]}
df=pd.DataFrame(dict)

df_id=pd.DataFrame()

for i in set(df.id):
  df_filtered=df[df.id==i]
  len_id=len(df_filtered.samples)

  if len_id>3: #3 is just a random choice for this example
    df_id=df_id.append(df_filtered)
print(df_id)

Output:
   samples id
2        3  c
6        7  c
7        8  c
8        9  c
1        2  b
3        4  b
4        5  b
5        6  b

How to improve it in a more Pythonic way?
Thanks


texts: Check if a record already exists and update if it exists

texts:
I want to check if a record already exists in a database, and return true or false.

If it exists, I want to update the update_at datetime field.  The method touch_with_version from the paper_trail gem will do it.

Which is better?

  def repeated?(unprocessed)
    occurrence = Occurrence.find_by(unprocessed: unprocessed)
    occurrence.touch_with_version if occurrence.present?
    occurrence.present?
  end

Or

  def repeated?(unprocessed)
    occurrence = Occurrence.find_by(unprocessed: unprocessed)

    if occurrence.present?
      occurrence.touch_with_version
      true
    else
      false
    end
  end

Is there a better way?


texts:
This code was for a university assignment.  It's well passed now so don't be scared of giving me false grades, for example. I was wondering what could be done better, or bits of code that are horribly inefficient or are bad practices.

def main():
    import time
    while True:
        try:
            num1 = int(input("Pick a number between 10 and 30: "))
        except ValueError:
            print("That's not a number!")
            continue
        if num1 > 30 or num1 < 10:
            print("Not Valid!")
            continue
        break
    while True:
        try:
            hue = str(input("Pick a colour; Red, Green, Blue: "))
        except ValueError:
            print("Letters not numbers!")
            continue
        if  (hue == "Red") or (hue == "red") or (hue == "Green") or (hue == "green") or (hue == "Blue") or (hue == "blue"):

            break
    print("Generating File")
    time.sleep(3)
    numbers ='no', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty', 'Twentyone', 'Twentytwo', 'Twentythree', 'Twentyfour', 'Twentyfive', 'Twentysix', 'Twentyseven', 'Twentyeight', 'Twentynine', 'Thirty'
    text_one = hue +' bottle%s\nHanging on the wall'
    text_two = "And if one " + hue + " bottle\nShould accidentally fall\nThere'll be"
    text_three =' \n'

    with open(numbers[num1] + ' ' + hue + ' Bottles.txt', 'w') as a:
        for l in range(num1, 0, -1):
            a.write(numbers[l]+ ' ')
            if l == 1:
                a.write(text_one % '' +'\n')
            else:
                a.write(text_one % 's' +'\n')

            a.write(numbers[l] + ' ')
            if l == 1:
                a.write(text_one %  '' + '\n')
            else:
                a.write(text_one % 's' +  '\n')
            a.write(text_two + ' ')
            a.write(numbers[l-1] + ' ')
            if (l - 1) ==1 :
                a.write(text_one % ''+'\n')
            else:
                a.write(text_one % 's'+'\n')
            a.write('\n' + '\n')

if __name__ == '__main__':
    main()

This should be saved to a folder and ran from the Python file it's saved as, not ran in an IDE.


texts: Summing all keys in the leaves of a tree

texts:
My program takes 35 sec to run example 2. How can I make my program faster?

def sum_keys(K, inputs, count=1):
    A, B, M, L1, L2, L3, D, R = list(map(int, inputs))
    x = ((A*K)+B)%M
    y = ((A*K+2*B)%M)

    if K < L1 or count == D:
        my_list.append(K)
    elif L1 <= K < L2:
        sum_keys(x, inputs, count + 1)
    elif L2 <= K < L3:
        sum_keys(y, inputs, count + 1)
    elif L3 <= K:
        sum_keys(x, inputs, count + 1)
        sum_keys(y, inputs, count + 1)

    return sum(my_list)

def read_input(inputstring):
    inputs = inputstring.split()
    A, B, M, L1, L2, L3, D, R = list(map(int, inputs))
    x = ((A*R)+B)%M
    y = ((A*R+2*B)%M)

    if L1 <= R < L2:
        return sum_keys(x, inputs)
    elif L2 <= R < L3:
        return sum_keys(y, inputs)
    elif L3 <= R:
        sum_keys(x, inputs)
        return sum_keys(y, inputs)

my_list = []
if __name__ == '__main__':
    print(read_input(input()))


texts:
I've made a quick game in C++ where you race down a vertical track and dodge 'X's or obstacles. The player is represented as a 'v', and the score is counted by how far you manage to get down the track. The obstacles are randomly generated at the bottom of the map and slide up each time the player moves (using the arrow keys).

I have the dodgeGame() function linked from another source, so that's where the program actually starts.

How can I make it better?

#include <conio.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;

void restartMap(char map[9][9]) //Sets all values on map to ' '
{
        for(int i = 0; i < 9; i++)
    {
        for(int g = 0; g < 9; g++)
        {
            map[i][g] = ' ';
        }
    }
}

void drawMap(char map[9][9]) //Displays full array, with lines on each side
{
    for(int i = 0; i < 9; i++)
    {
        cout << '|';
        for(int g = 0; g < 9; g++)
        {
            cout << map[i][g];
        }
        cout << '|' << endl;
    }
}

void slideMap(char map[9][9], int player) //Slides each value in the array up, adjusts bottom row
{
    for(int i = 0; i < 8; i++)
    {
        for(int g = 0; g < 9; g++)
        {
            map[i][g] = map[i+1][g];
        }
    }
    map[0][player] = 'v';
    for(int i = 0; i < 9; i++)
    {
        if(rand() % 6 == 0) //One in six chance to place an obstacle on the bottom row, otherwise blank space
        {
            map[8][i] = 'X';
        }
        else
        {
            map[8][i] = ' ';
        }
    }
}

void mapInfo(int player, int count)
{
    cout << "Position: " << player << endl << "Distance Traveled: " << count;
}

void dodgeGame() //MAIN
{
    srand (time(NULL));
    char map[9][9];
    restartMap(map);
    int player = 4;
    map[0][player] = 'v';
    int c = 0, count = 0;
    drawMap(map); mapInfo(player, count);
    bool crash = false;
    while(true)
    {
        c = getch();
        switch(c)
        {
            case 224:   //Issue with error keys
            continue;

            case 80: //down
            if(map[1][player] == 'X') crash = true;   //These test if there is an obstacle where the player is trying to move to
            break;

            case 75: //left
            if(player == 0) continue;
            if(map[1][player-1] == 'X')
            {
                crash = true;
                break;
            }
            map[0][player] = ' ';
            player--;
            map[0][player] = 'v';
            break;

            case 77: //right
            if(player == 8) continue;
            if(map[1][player+1] == 'X')
            {
                crash = true;
                break;
            }
        map[0][player] = ' ';
        player++;
        map[0][player] = 'v';
        break;

        default: continue;
    }
    count++;
    system("cls");
    slideMap(map, player);
    if(crash == true) map[0][player] = '=';
    drawMap(map); mapInfo(player, count);
    if(crash == true) break;

    }
cout << "\n|<|Crash!|>|\nFinal Score: " << count << ".\n";
}


texts: Recursive calculation of second order derivative

texts:
I am writing code to do some numerical task using the routines of the book Numerical Recipes. One of my objectives is to calculate the second derivative of a function and have a routine that calculates the first derivative of a function in a nice manner within a specified accuracy. However, I would like to generalize this method and use this function recursively to find the second derivatives or higher order derivatives if needed. I have made some changes in my code and defined a reduced function which takes one argument and achieved my aim more or less. The function that calculates the first derivatives are declared as follows:

float dfridr(float (*func)(float), float x, float h, float *err);

My aim is to set the h value by calling another function for both of the nested dfridr functions at once. For clarity I have enclosed my code. I would appreciate it if you could comment on my method and provide suggestions for improvement and general feedback. As far as I've checked, it works better than the finite difference algorithms, but I think it may be refined.

// The compilation command used is given below
// gcc Q3.c nrutil.c DFRIDR.c -lm -o Q3

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "nr.h"

#define LIM1 20.0
#define a -5.0
#define b 5.0
#define pre 100.0 // This defines the precision
/* This file calculates the func at given points, makes a
 * plot. It also calculates the maximum and minimum of the func
 * at given points and its first and second numerical derivative.
*/
float func(float x)
{
    return exp(x / 2) / pow(x, 2);
}

// We define the following functions to aid in the calculation of the
// second derivative
float reddfridr(float x)
{
    float err;
    return dfridr(func, x, 0.1, &err);
}
float dfridr2(float x, float h)
{
    float err;
    return dfridr(reddfridr, x, h, &err);
}
int main(void)
{
    FILE *fp = fopen("Q3data.dat", "w+"), *fp2 = fopen("Q3results.dat", "w+");
    int i; // Declaring our loop variable
    float min, max, err, nd1, nd2, x, y;
    // Define the initial value of the func to be the minimum
    min = func(0);
    // Initialize x
    x = 0;
    for(i = 0; x < LIM1 ; i++)
    {
        x = i / pre; // There is a singularity at x = 0
        y = func(x);
        if(y < min)
            min = y;
        fprintf(fp, "%f \t %f \n", x, y);
    }
    fprintf(fp, "\n\n");
    max = 0;
    // Never forget to initialize x again
    x = a;
    // Since i is incremented at the end of the loop
    for(i = 0; x < b  ; i++)
    {
        x = a + i / pre;
        y = func(x);
        nd1 = dfridr(func, x, 0.1, &err);
        nd2 = dfridr2(x, 0.1);
        fprintf(fp, "%f \t %f \t %f \t %f\n", x, y, nd1, nd2);
        if(y > max)
            max = y;
    }
    fprintf(fp2, "The minimum value of f(x) is %f when x is between 0 and 20. \n", min);
    fprintf(fp2, "The maximum value of f(x) is %f when x is between -5 and 5. \n", max);
    fclose(fp);
    fclose(fp2);
    return 0;
}


texts:
I write this class to process and output xml/rss feeds. I'm still working on, but any suggestion will be appreciated.
As a little trick if the xml file come from an online resource, I've added a method to cache the xml file as a json file.

<?php
class NewsFeed{

    public $url;
    private $cachedFeed;
    private $cachedFile;
    private $feed;
    private $xml;
    private $json;

    public function __construct($url){
        $this->url = $url;
    }

    public function showLiveFeed(){
        $feed = $this->processFeed();
        return json_decode($feed, true);
    }

    public function showCachedFeed(){
        $cachedFeed = $this->loadCachedFile();
        return json_decode($cachedFeed, true);
    }

    private function processFeed(){
        $feed = $this->url;
        $xml = simplexml_load_file($feed, 'SimpleXMLElement', LIBXML_NOCDATA);
        $json = json_encode($xml);
        $cacheFeed = file_put_contents('cachedFeed.json', $json);
        return $json;
    }

    private function loadCachedFile(){
        if(file_exists('cachedFeed.json')){
          $cachedFile = file_get_contents('cachedFeed.json');
          return $cachedFile;
        }

    }
}
?>


texts: Displaying a paginated list of forum topics using PHP PDO

texts:
Can someone tell me if this code is safe? Can be sql-injected or something else hacked? Code get some rows from db and show in pages with pagination... if i can improve let me know and show me how, thanks.

$conn = new PDO('mysql:host=localhost;dbname=admin_admin', 'admin_admin', 'password');
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $num_rows = $conn->query('SELECT COUNT(*) FROM a_topics')->fetchColumn();
     $pages = new Paginator($num_rows,25,array(25,50,100,250,'All'));
     $stmt = $conn->prepare('SELECT a_topics.pid, a_topics.title, a_topics.forum_id, b_forums.id, b_forums.name
        FROM a_topics INNER JOIN b_forums ON a_topics.forum_id = b_forums.id
        ORDER BY a_topics.pid DESC LIMIT :start,:end');
     $stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);
     $stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);
     $stmt->execute();
     $result = $stmt->fetchAll();
     echo $pages->display_jump_menu().$pages->display_items_per_page();
     echo $pages->display_pages();
        foreach($result as $row) {
        echo "$row[0] - $row[1] - $row[2]";
     } catch(PDOException $e) {
     echo 'ERROR: ' . $e->getMessage();
     }


texts: Fat Controller Action - Deep nested filters

texts:
I have this really really long controller action and would like someone to help me break it down.

  def index
    @credit_unions = Company.parent_with_branches

    @loan_officers = []

    @loan_requests = LoanRequest.includes(:dealer, :loan_officer, :branch => :parent)
    if params[:query].present?
      results = @loan_requests.search(params[:query]).results
      @loan_requests = LoanRequest.where(id: results.map(&:id))
    end

    if params.include? 'filter'

      if params[:filter][:branch_id].present? && params[:filter][:branch_id].reject!(&:blank?).present?
        @loan_requests = @loan_requests.where(:branch_id => params[:filter][:branch_id])
        @loan_officers = LoanOfficer.where(:company_id => params[:filter][:branch_id])
      end

      if params[:filter][:loan_officer_id].present?
        @loan_requests = @loan_requests.where(:loan_officer_id => params[:filter][:loan_officer_id])
      end

      if params[:filter][:reward_type].present?
        @loan_requests = @loan_requests.where(reward_type: params[:filter][:reward_type])
      end

      if params[:filter][:transaction_type].present?
        @loan_requests = @loan_requests.where(transaction_type: params[:filter][:transaction_type])
      end

      if params[:filter][:status].present?
        @loan_requests = @loan_requests.where(:status => params[:filter][:status])
      end

      if params[:filter][:start_date].present?
        start_date = Date.strptime(params[:filter][:start_date], '%m/%d/%Y').beginning_of_day
        @loan_requests = @loan_requests.where('printed_at >= ?', start_date)
      end

      if params[:filter][:end_date].present?
        end_date = Date.strptime(params[:filter][:end_date], '%m/%d/%Y').end_of_day
        @loan_requests = @loan_requests.where('printed_at <= ?', end_date)
      end
    end

    respond_to do |format|
      format.html do
        @q = @loan_requests.ransack(params[:q])
        @loan_requests = @q.result.paginate(:page => params[:page], :per_page => 50)
        @loan_requests = @loan_requests.order(created_at: :desc)
      end
    end
  end