texts: Map-reduce implementation for splitting strings

texts:
I have been changing this code and I don't get to make it much better. I changed a little bit the structure, reimplemeted a new function for splitting Strings which is more efficient, etc. I have been tested with MR-Unit (it's part of map-reduce code).

I'm testing the code with 1.5 millions calls. It takes about 35 seconds on my computer, but in the real environment, it could be called with much more data, so, any optimization could be great. I'm worry about a little part of the code which I call around 7 times each iteration.

The parameters of my function are a map with the values what I want to replace, and another string which is a expression. It could be something like hard-code (I won't have to do any processing) or a expression like ${0} or something more complex like ${0}_${3}.

My idea now, since it's map-reduce code, is to do some of this code out of the mapper, and it should execute just once. The code could be more complex but I would only have once for the matchers and the split. I don't know if that could improve the performance.

private static final Pattern PATTERN = Pattern
            .compile("\\$\\{.+?\\}");
private static final Pattern PATTERN_DOLLAR = Pattern
            .compile("^.*\\$.*$");

public static String replaceVariables(final String expression,
            final Map<String, String> vars) {
        String tmpExp = expression;
        Matcher matcher = PATTERN.matcher(tmpExp);

        while (matcher.find()) {
            final String group = matcher.group();
            //${4} --> 4, ${2,8} --> 2,8
            final String prop = group.substring(2, group.length() - 1);
            // If the property has a comma, special case.
            final String[] props = split(prop, ',');

            //I get the value from the Map
            String sValue = vars.get(props[0]);
            if (sValue != null) {
                //Special case, I could write ${0,3}, field 0, only the first 3 characters.
                if (props.length > 1) {
                    final int cut = Integer.parseInt(props[1]);
                    if (sValue.length() > cut) {
                        sValue = sValue.substring(0, cut);
                    }
                }
                Matcher matcherDollar = PATTERN_DOLLAR.matcher(sValue);
                if (matcherDollar.matches()) {
                    tmpExp =
                            matcher.replaceFirst(sValue.replace("$", "\\$"));
                } else {
                    tmpExp = matcher.replaceFirst(sValue);
                }
            } else {
                tmpExp = matcher.replaceFirst("");
            }
            matcher = VAR_PATTERN.matcher(tmpExp);
        }
        return tmpExp;
    }

The split function:

public static String[] split(final String s, final char delimeter) {
        int count = 1;
        for (int i = 0; i < s.length(); i++)
            if (s.charAt(i) == delimeter)
                count++;

        String[] array = new String[count];
        int a = -1;
        int b = 0;

        for (int i = 0; i < count; i++) {
            while (b < s.length() && s.charAt(b) != delimeter)
                b++;

            array[i] = s.substring(a + 1, b);
            a = b;
            b++;
        }
        return array;
    }

The possible input it could be:

Expression:

  Hi {0,2}

Map:

  0=test, 1=test1, 2=test2, ...

Usually, the expressions are pretty simple; just a hardcode of one or two variable expressions (e.g. {0,1}_{2} or even simpler). Although it's possible to find more complex expressions, it's not so common.


texts:
Looking at $wpdb class, I found get_row, and I am unsure if the function automatically prepares the query. I believe it does not and I may have to reexamine my code to prevent a future disaster.

Here is what my code looks, and I feel that it is vulnerable:

$wpdb->get_row("SELECT * FROM `my_table` WHERE column = '".$_GET['fromUrl']."'", ARRAY_A);

However, I have tried injecting a malicious input with the follow: ' or column = 'value'

And it seems not to work, should I go ahead and prepare my statements anyway?


texts: Testing a simple guard clause in isolation

texts:
I’m using decorator objects in a Rails app so that I don’t have to do nil? checks in views. Everything is working nicely and it’s easy to test, but I’m suspicious that my test:code ratio is a little high. Am I being too verbose? Is there a better way this could be done?

Test suite:

# spec/decorators/client_decorator_spec.rb
require_relative "../../app/decorators/client_decorator"

describe ClientDecorator do
  describe ".position" do
    context "with a recorded client position" do
      it "returns the name of the position" do
        occupation = double("Occupation", name: "CEO")
        client = double("Client", occupation: occupation)
        expect(ClientDecorator.new(client).position).to eq "CEO"
      end
    end

    context "with no recorded position" do
      it "returns an empty string" do
        client = double("Client", occupation: nil)
        expect(ClientDecorator.new(client).position).to eq ""
      end
    end
  end
end

Production code:

# app/decorators/client_decorator.rb
require "simple_decorator"

class ClientDecorator < SimpleDecorator
  def position
    return "" unless occupation
    occupation.name
  end
end


texts: Project Euler 22: Names scores alternative

texts:
Can someone tell me how to improve my following python code.

Code:

a = open('/home/Username/1st few programms/names.txt')

for y in a:
    c = y.split(",")
    c.sort()

dict = {'"':0, "A": 1, "B": 2,"C": 3,"D": 4, "E": 5,"F": 6,"G": 7,"H": 8,"I": 9,"J": 10,"K": 11,"L": 12,"M": 13,"N": 14,"O": 15,"P": 16,"Q": 17,"R": 18, "S": 19, "T": 20, "U": 21, "V": 22,"W": 23,"X": 24, "Y": 25, "Z": 26}

sum = 0
for x in range(len(c)):
    localsum = 0
    for y in c[x]:
        localsum += dict[y]
    sum += localsum*(x+1)
print sum

Problem statement:

  Using names.txt, a 46K text file containing over five-thousand first
  names, begin by sorting it into alphabetical order. Then working out
  the alphabetical value for each name, multiply this value by its
  alphabetical position in the list to obtain a name score.

  For example, when the list is sorted into alphabetical order, COLIN,
  which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the
  list. So, COLIN would obtain a score of 938 × 53 = 49714.

  What is the total of all the name scores in the file?


texts: Extracting top subreddits from an HTML table

texts:
I'm scraping a table and am trying to get nested td tags down the tbody tree but the code seems kind of verbose.  Is there a more Pythonic way to do this?

def get_top_subreddits(url):

    r = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(r, "lxml")

    body = soup.find_all('tbody')

    top_subreddits = []
    for i in body:
        trs = i.find_all('tr')
        for tr in trs:
            tds = tr.find_all('td')
            for td in tds:
                texts = td.get_text()
                if '/r/' in texts:
                    top_subreddits.append(texts)
    return top_subreddits


texts:
I am trying to find out if a column is binary or not. If a column is only having 1 or 0 then I am flagging it as binary, else non binary. Since I have a database background, I tried to achieve it through a SQL like statement. But when the file is big, this code is not giving me good performance.

Could you please suggest how I can improve this code:

input_data=spark.read.csv("/tmp/sample.csv", inferSchema=True,header=True)
input_data.createOrReplaceTempView("input_data")
totcount=input_data.count()

from pyspark.sql.types import StructType,StructField,StringType
profSchema = StructType([ StructField("column_name", IntegerType(), True)\
                   ,StructField("binary_type", StringType(), True)])
fin_df=spark.createDataFrame([],schema=profSchema) ##create null df

for colname in input_data.columns:
    query="select {d_name} as column_name,case when sum(case when {f_name} in ( 1,0) then 1 else 0 end) == {tot_cnt} then 'binary' else 'nonbinary'\
    end as binary_stat from input_data".format(f_name=colname, d_name="'"+str(colname)+"'",tot_cnt=totcount)
    join_df=spark.sql(query)
    fin_df=fin_df.union(join_df)


texts:
I am looking for some ways to make my code simpler for this currency converter.

currencies = {
    "BRL":"(Brazilian Real)",
    "USD":"(US Dollar)",
    "EUR":"(Euro)",
    "GBP":"(Great Britain Pound)"
}

def real_to_dollar():
    user_value = raw_input("How many reais? ")
    ammount = float(user_value)
    conversion = ammount * 0.26
    print str(user_value) + " reais is equal to " + str(conversion) + " dollars."

def dollar_to_real():
    pass

def dollar_to_euro():
    pass

def euro_to_dollar():
    pass

def euro_to_pound():
    pass

def pound_to_euro():
    pass

def real_to_euro():
    pass

def euro_to_real():
    pass

def real_to_pound():
    pass

def pound_to_real():
    pass

def dollar_to_pound():
    pass

def pound_to_dollar():
    pass

print "Welcome to currency converter."
print "Supported currencies:"
for currency in currencies:
    print currency + " " + currencies[currency]

user_choice1 = raw_input("Convert: ")
user_choice2 = raw_input("To: ")

if user_choice1 == "BRL" and user_choice2 == "USD":
    real_to_dollar()

elif user_choice1 == "USD" and user_choice2 == "BRL":
    dollar_to_real()


texts:
The idea is to lock resources in C# or Java using Qt:

lock(obj){/*process with locked obj*/}`

Now I see the problem with deleting obj under lock().

resourcelocker.h

#ifndef RESOURCELOCKER_H
#define RESOURCELOCKER_H

#include <QObject>
#include <QHash>
#include <QSemaphore>

class ResourceLocker : public QObject
{
    Q_OBJECT
public:

    friend class ResourceWatcher;
    explicit ResourceLocker(QObject *parent = 0);
    ~ResourceLocker();

    bool lock();

private:
    static QHash<QObject*,QSemaphore*> resources;
    QSemaphore * sem;
    QObject * expectedParent;
    bool doubleLock;

signals:

public slots:

};

#define _LOCK(object) for (ResourceLocker locker((object)); locker.lock(); )

#endif // RESOURCELOCKER_H

resourcelocker.cpp

#include "resourcelocker.h"
#include <QMutex>
#include <QMutexLocker>
#include <QSemaphore>
#include <QDebug>

QHash<QObject* ,QSemaphore*> ResourceLocker::resources;

class ResourceWatcher: public QObject
{
public:
    explicit ResourceWatcher(QObject * parent):
        QObject(parent)
    {
        //qDebug()<<"creating watcher";
    }

    ~ResourceWatcher()
    {
        QSemaphore * sem = ResourceLocker::resources.value(parent(),NULL);
        if (sem->available()>0)
        {
            //unlocked
            ResourceLocker::resources.remove(parent());
            delete sem;
        }
        else
        {
            //locked
            ResourceLocker::resources.remove(parent());
        }
        //qDebug()<<"removing sem";

    }
};

ResourceLocker::ResourceLocker(QObject *parent) :QObject(),expectedParent(parent),doubleLock(false)
{
}

bool ResourceLocker::lock()
{
    static QMutex internalMutex;
    {
        QMutexLocker locker(&internalMutex);

        if (doubleLock)
            return false;
        doubleLock = true;
        //qDebug()<<&expectedParent;

        sem = resources.value(expectedParent,NULL);
        if (sem == NULL)
        {
            //qDebug()<<"Crearting sem";
            sem = new QSemaphore(1);
            resources.insert(expectedParent,sem);
            new ResourceWatcher(expectedParent);
        }
    }
    //qDebug()<<"acquiring";
   sem->acquire();
   return true;
}

ResourceLocker::~ResourceLocker()
{
    QMutex internalMutex;
    QMutexLocker locker(&internalMutex);
    //qDebug()<<"releasing";
    sem->release();
    if (!resources.values().contains(sem))
        delete sem;
}

Usage:

_LOCK(smth)
    {
        //prcoess with smth locked

    }


texts:
I was recently doing a challenge on Codewars and this is what challenge said:

  There are no explanations. You have to create the code that gives the
  following results:

  oneTwoThree(0) → ['0', '0']
    oneTwoThree(1) → ['1', '1']
  oneTwoThree(3) → ['3', '111']
  oneTwoThree(19) → ['991', '1111111111111111111']

I have solved the challenge but it appears to be quite slow and I was hoping to get some constructive ideas on how to improve the speed and efficacy of this code thanks.

function oneTwoThree(n) {
  var finalOutput = ['', ''],
    slotsArray = [],
    sum = 0,
    currentSlot = 0,
    slots = 1;

  /*
      My Idea was to create an array and the sum of that array will be equal to the parameter given "n". The array will have slots and the number of slots is unknown because the parameter "n" is arbitrary. each slot will contain a number from 9-1, we will start out with 9 because it is the highest, I will add all the slots and the sum must be equal to parameter "n" thus will give us the first item in our final array.
  */
  if (n >= 10) {
    while (!(9 * slots >= n)) { // check how many slots are needed
      slots += 1;
    }
    while (slotsArray.length != slots) {
      // place a 9 in every slot, starting with the highest numbern this should give us something like "[9,9,9]" for examply
      slotsArray.push(9);
    }

    // this is how I will keep track of what slot I am currently in and we will start from right to left.
    currentSlot = slotsArray.length - 1;

    for (var i = 0; i < slotsArray.length; i++) {
      //here I test if the sum of the array is equal to "n"
      sum += slotsArray[i];
    }

    // if it is not equal we proceed here.
    while (sum != n) {
      slotsArray[currentSlot] -= 1; // subtract 1 from the current slot example: [9,9,8]

      // I check agian if the sum is equal to n
      for (var i = 0; i < slotsArray.length; i++) {
        sum += slotsArray[i];
      }

      // reset the sum to 0 if its not equal
      if (sum != n) {
        sum = 0
      }

      // This will continue until if finds the sum that equals "n"
    }

    // convert the array into a string for the final output
    for (var i = 0; i < slotsArray.length; i++) {
      finalOutput[0] += String(slotsArray[i]);
    }

    while (finalOutput[1].length != n) {
      finalOutput[1] += '1';
    }
  }

  // if the parameter "n" is less than 10
  if (n < 10) {
    finalOutput[0] = String(n);
    if (n == 0) {
      finalOutput[1] += String(n);
    } else {
      while (finalOutput[1].length != n) {
        finalOutput[1] += '1';
      }
    }
  }
  console.log(finalOutput);
  return finalOutput;
}
oneTwoThree(19);
oneTwoThree(1);
oneTwoThree(7);
oneTwoThree(36);
oneTwoThree(0);


texts:
I have a pack of cards and I am doing a 'deal' action. I am dealing n number of cards, for now to one player.

How can I DRY up the while and unless loops to have fewer lines?

def deal(number_of_players, number_of_cards_each)

 # 1..number_of_players

  players_cards_array=[]

  (1..number_of_cards_each).each do |a_card|

    added_card=false
    while added_card==false
      new_card = choose_card()
      unless @currently_dealt_cards.include?(new_card)
        players_cards_array << new_card
        added_card= true
        @currently_dealt_cards << new_card
      end
    end
  end

  return players_cards_array

end


texts:
Project Euler Problem 37 asks:

  The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

  Find the sum of the only eleven primes that are both truncatable from left to right and right to left.

  NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

My approach can generate first 8 numbers "fairly" quickly and it relies on pregenerated list of primes created using sieve of eratosthenes. I've tried with active prime generation but it was slower, any way to optimize this code ?

from algorithms import *

primes = [i for i in gen_primes(10000000)]

def is_truncatable_right(n):
    a = True
    if n > 10:
        for x in range(len(str(n))):
            if int(n) not in primes:
                a = False
            n = str(n)[:-1]
        return a
    else:
        return False

def is_truncatable_left(n):
    a = True
    if n > 10:
        for x in range(len(str(n))):
            if int(n) not in primes:
                a = False
            n = str(n)[1:]
        return a
    else:
        return False

def main():
    n = []
    a = 11
    while len(n) != 11:
        if is_truncatable_left(a) and is_truncatable_right(a):
            n.append(a)
        a += 1
    return n, sum(n)

print(main())


texts:
Do you see any security issues with this authentication approach or have any suggestions?

WebAPI is REST-based.  The user logs in by calling the Authentication Controller and expects a 401 if unauthenticated or a 200 with a session token in the header.

GitHub

Session session = null;
try
{
    session = Models.User.Login(user);
}
catch (Exception ex)
{
    var errResponse = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)
    {
        Content = new StringContent("Invalid Username or Password"),
        ReasonPhrase = ex.InnerException.ToString()
    };
    throw new HttpResponseException(errResponse);
}

On every call except Authentication the request is intercepted and expects a session header.  If a session exists in the database then the request is authenticated.

protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    try
    {
        //Unauthorized
        if (HttpContext.Current.Request.Headers[SessionHeader] == null)
        {
            var errResponse = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                Content = new StringContent(SessionError),
                ReasonPhrase = SessionError
            };
            return errResponse;

        }

        string sessionHeader = HttpContext.Current.Request.Headers[SessionHeader];

        Session session = Session.Lookup(sessionHeader);

        if (session == null)
        {
            throw new SecurityException("No session record exists");
        }
        else if (session.Expired)
        {
            throw new SecurityException("Session Expired");
        }
        else
        {
            session.LastAccess = DateTime.Now;
            session.Save();
            var identity = new SecurityPrincipal(session);
            Thread.CurrentPrincipal = identity;
            HttpContext.Current.User = identity;

        }

The session lookup is done with Entity Framework

public static Session Lookup(string sessionId) {
    using (var context = new SingleAppContextCustom())
    {
        var session = (from s in context.Sessions.IncludeChildren()
                        where s.SessionId == sessionId
                        select s).FirstOrDefault();

        return session;
    }
}


texts: Reading a csv file and making a histogram in Python using NumPy and Matplotlib

texts:
I have written the following code which reads a csv file that contains a bunch of words and their sentiment value. Words like abandon may have a value of -1, while words like progress and freedom have a value of +1. So, the csv files acts as a database while we ask user for a txt file containing a speech or an essay to compare.

After reading all the sentiment values (ranging from -1 to +1) the code attempts to build a histogram. We have five categories, i.e, "Negative", "Weakly Negative", "Neutral", "Weakly Positive", "Positive". We map how frequently certain numbers appear and put them in their respective category.

My questions are,

Can I make this code run any faster?
Can I make this code more any smaller?

import numpy as np;
import matplotlib.pyplot as plot

lexiconSentiment = np.genfromtxt("list_of_lexicon_value.csv", delimiter = ',', dtype = [('f0', 'S24'), ('f1', '<f8')])

userInput = input("Enter the file-name: ")

textFileIntoArray = np.genfromtxt(userInput, delimiter = ' ', dtype = 'str')

booleanValues = np.in1d(lexiconSentiment['f0'], textFileIntoArray)

listOfSentimentNumberValue = []

the size of booleanValue
for x in range(0,booleanValues.size):
    if booleanValues[x]:
        listOfSentimentNumberValue.append(lexiconSentiment['f1'][x])
        print lexiconSentiment['f0'][x]

xLabelDescription = ["Negative", "Weakly Negative", "Neutral", "Weakly Positive", "Positive"]

plot.xlabel("Sentiment"); plot.ylabel("Percent of Words")

plot.hist(listOfSentimentNumberValue, bins = (-1.0,-0.5,0.0,0.5,1.0,1.5),  color = 'blue', range = (0.0, 0.0), normed = True)

label_pos = [-0.75,-0.25,0.25,0.75,1.25]

plot.xticks(label_pos, xLabelDescription)


texts: Convert a number into a different base and return as string

texts:
I wanted to write a function that would take a long long int argument as well as a base and it would convert that number into an equivalent number in a different base, and return the result as a string (er, char array). For example, the call,

convertBase(9, 5)

should return "14\0". For negative values, the returned string should simply have a negative sign, '-' in front.

The code is as follows:

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

#define MIN_BASE 2
#define MAX_BASE 36
#define MAX_LLI_REP 63

char toCharacter(int v)
{
    v = abs(v);
    return (v < 10)
                ? ('0' + v)
                : ('a' + v - 10);
}

char * convertBase(long long int value, int base)
{
    if (base < MIN_BASE || base > MAX_BASE) {
        fprintf(stderr, "The base must be within [%d, %d].\n", MIN_BASE, MAX_BASE);
        return NULL;
    }
    char c[MAX_LLI_REP];
    int i, j = 0;
    long long int quotient;
    for (i = 0, quotient = value; quotient != 0; i++, quotient /= base)
    {
        c[i] = toCharacter(quotient % base);
    }
    int negative = value < 0;
    char * result = (char *) malloc(sizeof(char) * (i + 1 + negative));
    if (negative) {
        result[0] = '-';
        j = 1;
    }
    while (i) {
        result[j++] = c[(i--) - 1];
    }
    result[j] = '\0';
    return result;
}

I've ran a variety of test cases, such as both LLONG_MIN and LLONG_MAX from limits.h, in various bases, as well as trying to convert a decimal number into a decimal number (expecting the same answer). It passed in all of these cases. However, I was wondering if additional sets of eyes could spot potential errors. Also, any stylistic or performance improvement suggestions would be appreciated.


texts:
I saw this question, but was unable to answer because of my inexistant knowledge of Rust, so I decided to try and write an algorithm on my own and put it for review.

There is the casual way to compute factorials:

\$n! = \prod\limits_{k=1}^n k\$

public static BigInteger fact(BigInteger n)  => n == 0 ? 1 : n*fact(n - 1);

The problem with this one is that with big factorials, it get's slow (or, in this case, throw a StackOverflowException.

Now, reading this "paper", I figured I'd try to implement a faster algorithm to compute factorials.

From what I understood, the equation would look something like this :

\$\prod\limits_{i=1}^{\frac{n}{2}}( \sum\limits_{z=0}^i (n - z\times2))((\lceil{\frac{n}{2}\rceil})\$  (if n is odd)\$)\$

The idea is to reduce the number of multiplications by half.

public static BigInteger Factorial(int n)
{
    BigInteger sum = n;
    BigInteger result = n;
    for (int i = n - 2; i > 1; i -= 2)
    {
        sum = (sum + i);
        result *= sum;
    }

    if (n % 2 != 0)
        result *= (BigInteger)Math.Round((double)n / 2, MidpointRounding.AwayFromZero);

    return result;
}

I decided to keep a sum variable so I don't need to redo the sum computing at each multiplication's iteration.

I'd like to see if I missed something or if this can be optimized. (I'm doing this as a mathematical exercise, so there's no need for performance, I'm looking at ways to make it more performant just because I want to understant the maths behind it).


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

First, this is my messed up code:

string tempFile = Path.GetTempFileName();

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

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

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

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

    return name;
}

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

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

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

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

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

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

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

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

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

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

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


texts:
I'm getting more and more into programming js in a functional manner which makes heavy use of multiple returns via tuples (especially useful with recursion). Also, a pattern that I use often is creating simple temporary values for projections

_.chain(arr)
       .filter(...)
       .map(function(x){ return [x.foo, getSomething(x.bar)] })
       .filter(...)
       .reduce(...)

Usually I see tuples in js implemented with arrays [a, b]  though of course an object - while annoying to write would be just as valid: {a: a, b: b}.

So for this sort of use-case (creation and light usage of a bunch of temporary objects) I'm curious if there's a significant performance difference so I set up this jsperf.

Object tuple test:

var all = []
for(var x = 0; x < 100; x+=1)
for(var y = 0; y < 100; y+=1)
  all.push({x: x, y: y})

var mapped = []
for(var i=0; i < all.length; i+=1)
  mapped.push({x: all[i].x, y: all[i].y})

versus array tuple test

var all = []
for(var x = 0; x < 100; x+=1)
for(var y = 0; y < 100; y+=1)
  all.push([x, y])

var mapped = []
for(var i=0; i < all.length; i+=1)
  mapped.push([all[i][0], all[i][1]])

What do people think? Is this a sufficient test for the concept?


texts:
Place N amount of queens in such a way that none of them can attack each other.

import java.util.*;

public class NQueensRewrite {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter amount of queens");
        int n = input.nextInt();
        int[] board = new int[n];
        fillBoard(board);
        printBoard(board);
    }

    public static void fillBoard(int[] board) {
        int queens = 1;
        while (queens < board.length) {
            boolean validColumnFound = false;
            //Start from previous confirmed column or check all if valid column found in row
            for (int column = board[queens] + 1; column < board.length; column++) {
                if (isValid(column, queens, board)) {
                    board[queens] = column;
                    queens++;
                    validColumnFound = true;
                    break;
                }
            }
            //If no other valid column is found, then clear the row and go back to try another column
            if (!validColumnFound) {
                board[queens] = 0;
                queens--;
            }
        }
    }

    public static boolean isValid(int column, int row, int[] board) {
        //Check if any other row has the specified column
        for (int i = 0; i < row; i++) {
            if (board[i] == column) {
                return false;
            }

            //Check the differences bewteen the spaces if they are uniform (even)
            //If the difference between the column of ith row and column being checked is
            //the same as the difference between the current row and row being checked,
            //then some previous queen is diagnal to the current spot being checked
            if (Math.abs(board[i] - column) == Math.abs(i - row)) {
                return false;
            }
        }
        return true;
    }

    public static void printBoard(int[] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board.length; j++) {
                if (board[i] == j) {
                    System.out.print("|Q");
                }
                else {
                    System.out.print("| ");
                }
            }
            System.out.println("|");
        }
    }
}


texts:
Exercise: Checking if a sentence is considered valid under the following conditions:

Numbers less than 13 are only allowed in their written form, e.g "twelve", but "14" is considered valid.
Only 1 period marker is allowed and it must be the final character
First letter must be uppercase
number of quotation marks in the sentence must be even

if the sentence meets all above criteria, it is considered valid.

Here is my approach:

public class SentenceValidator implements ValidatesSentences {

  private static final int MINIMUM_ALLOWED_NUMBER = 13;

  public SentenceValidator() {
        //default (auto-generated without explicit declaration anyway)
  }

    /**
     * Takes a string sentence and returns if it meets the requirements
     * @param sentence -> The string sentence to analyze for validity
     * @return boolean -> if the string meets the validation requirements
     */
  @Override
  public final boolean isSentenceConsideredValid(String sentence) {
    String temporary = guardTheSentence(sentence);
    return temporary.length() > 1 && areConditionsValid(temporary);
  }

  private boolean areConditionsValid(String sentence) {
      return isTheFirstCharacterAnUppercaseLetter(sentence)
              && isTheCountOfQuotationMarksEven(sentence)
              && isTheOnlyPeriodMarkTheLastCharacterOfTheSentence(sentence)
              && isTheLowestNumberInTheSentenceGreaterThan13(sentence);
  }

  private String guardTheSentence(String sentence) {
    Objects.requireNonNull(sentence, "null is not an acceptable value");
    return sentence.trim();
  }

  private boolean isTheFirstCharacterAnUppercaseLetter(String sentence) {
    return Character.isLetter(sentence.charAt(0))
        && sentence.charAt(0) == sentence.toUpperCase().charAt(0);
  }

  private boolean isTheCountOfQuotationMarksEven(String sentence) {
    return (retrieveCountOfAGivenCharacter(sentence,'"') % 2) == 0;
  }

  private boolean isTheOnlyPeriodMarkTheLastCharacterOfTheSentence(String sentence) {
    return sentence.charAt(sentence.length() - 1) == '.' && retrieveCountOfAGivenCharacter(sentence,'.') == 1;
  }

  private int retrieveCountOfAGivenCharacter(String sentence, Character charToCount) {
    int counter = 0;
    for (char c : sentence.toCharArray()) {
      if (c == charToCount) {
        counter++;
      }
    }
    return counter;
  }

  /**
   * We don't need really need to care about words for the numbers, that is trivial All we want to
   * check is for all numeric value(s) within the string and ensure none are below 13
   * supports negative numbers using the optional (?:-)
   */
  private boolean isTheLowestNumberInTheSentenceGreaterThan13(String sentence) {
    String temp = sentence.replaceAll("[^-?0-9]+", " ");
    temp = temp.trim();

    if (temp.isEmpty()) {
        return true;
    }

    int lowestNumber = MINIMUM_ALLOWED_NUMBER;
    for (String number : temp.split(" ")) {
      lowestNumber = Math.min(lowestNumber, Integer.parseInt(number));
    }

    return lowestNumber >= MINIMUM_ALLOWED_NUMBER;
  }
}

public interface ValidatesSentences {

    boolean isSentenceConsideredValid(String sentence);
}

A jump out problem I see already is the NumberFormatException when number is greater than a max int, I should use a long/Big Integer there and handle a NumberFormatException.


texts: Username, Password and UserType Validation

texts:
I have two tables in the database:

Credentials (userid, password, usertype)
Customer (customername, userid(foreign key))

I need to validate username,password and usertype and create a session variable for customername.

I have organized the code and it works fine, but how can I minimize the code and make it efficient?

// Function that enables LOGON for a registered User into site
public string LogOn(UserInformation objLogOnUserInformation)
{
    ConnectionManager conCm = new ConnectionManager();
    try
    {
        SqlConnection con = conCm.OpenConnection();
        SqlCommand cmd,cmdOne;
        SqlDataReader dr;
        string _str = "U";
        cmd = new SqlCommand("select UserID  from Credentials", con);
        dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            //checking user name is present in database
            if (dr.GetValue(0).ToString() == objLogOnUserInformation.UserId)
            {
                dr.Close();
                //retriving Password for the existing user
                cmd = new SqlCommand("select Password  from Credentials where UserId='" + objLogOnUserInformation.UserId + "'", con);
                dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    //checking the password is matching with the database
                    if (dr.GetValue(0).ToString() == objLogOnUserInformation.Password)
                    {
                        dr.Close();
                        cmd = new SqlCommand("select UserType  from Credentials where userid='" + objLogOnUserInformation.UserId + "'", con);
                        dr = cmd.ExecuteReader();

                        while (dr.Read())
                        {
                            //checking user type
                            if (dr.GetValue(0).ToString() == _str)
                            {
                                dr.Close();
                                cmdOne = new SqlCommand("select customername from customer where userid='" + objLogOnUserInformation.UserId + "'", con);
                                dr = cmdOne.ExecuteReader();
                                dr.Read();
                                objLogOnUserInformation.SessionUserName = dr.GetValue(0).ToString();
                                dr.Close();
                                //if usertype is customer, U is returned
                                return _str;
                            }
                            else
                            {
                                dr.Close();
                                cmdOne = new SqlCommand("select customername from customer where userid='" + objLogOnUserInformation.UserId + "'", con);
                                dr = cmdOne.ExecuteReader();
                                dr.Read();
                                objLogOnUserInformation.SessionUserName = dr.GetValue(0).ToString();
                                dr.Close();
                                //If usertype is Admin, A is returned
                                return "A";

                            }
                        }
                    }

                    else
                    {
                        return " Either User Name or Password is not Valid";
                    }
                }
            }
        }


texts: Data import "upsert" from a SSIS package

texts:
I have the following "upsert" trigger in SQL Server 2005, which is handling a large data import from a SSIS package. It is taking a very long time to complete - I suspect due to the concatenation and CASTing of keys.

Is there a better, faster way of doing this?

CREATE TRIGGER [dbo].[MP_VOD_UPSERT]
ON  [dbo].[vwMP_VOD]
INSTEAD OF INSERT
AS
BEGIN

  SET NOCOUNT ON;

  UPDATE [dbo].[vwMP_VOD]
  SET
  [Org] = inserted.Org
  ,[id_vend] = inserted.id_vend
  ,[id_org_orig] = inserted.id_org_orig
  ,[id_vchr_nbr] = inserted.id_vchr_nbr
  ,[id_vchr_line] = inserted.id_vchr_line
  ,[id_vchr_line_dist] = inserted.id_vchr_line_dist
  ,[id_glac_exp] = inserted.id_glac_exp
  ,[text_ref_4] = inserted.text_ref_4
  ,[amt_exp_hcur] = inserted.amt_exp_hcur
  ,[amt_rem_hcur] = inserted.amt_rem_hcur
  ,[id_tax] = inserted.id_tax
  ,[code_type_chrg] = inserted.code_type_chrg
  ,[id_vchr_line_chrg] = inserted.id_vchr_line_chrg
  FROM inserted
  WHERE inserted.ORG + inserted.ID_VEND + inserted.ID_ORG_ORIG + CAST(inserted.ID_VCHR_NBR AS VARCHAR) + CAST(inserted.ID_VCHR_LINE AS VARCHAR) + CAST(inserted.ID_VCHR_LINE_DIST AS VARCHAR) + inserted.CODE_TYPE_CHRG + inserted.ID_VCHR_LINE_CHRG IN
  (
    SELECT ORG + ID_VEND + ID_ORG_ORIG + CAST(ID_VCHR_NBR AS VARCHAR) + CAST(ID_VCHR_LINE AS VARCHAR) + CAST(ID_VCHR_LINE_DIST AS VARCHAR) + CODE_TYPE_CHRG + ID_VCHR_LINE_CHRG
    FROM inserted
    INTERSECT
    SELECT ORG + ID_VEND + ID_ORG_ORIG + CAST(ID_VCHR_NBR AS VARCHAR) + CAST(ID_VCHR_LINE AS VARCHAR) + CAST(ID_VCHR_LINE_DIST AS VARCHAR) + CODE_TYPE_CHRG + ID_VCHR_LINE_CHRG
    FROM [dbo].[vwMP_VOD]
  )

  INSERT INTO [dbo].[vwMP_VOD]
  SELECT * FROM inserted
  WHERE ORG + ID_VEND + ID_ORG_ORIG + CAST(ID_VCHR_NBR AS VARCHAR) + CAST(ID_VCHR_LINE AS VARCHAR) + CAST(ID_VCHR_LINE_DIST AS VARCHAR) + CODE_TYPE_CHRG + ID_VCHR_LINE_CHRG IN
  (
    SELECT ORG + ID_VEND + ID_ORG_ORIG + CAST(ID_VCHR_NBR AS VARCHAR) + CAST(ID_VCHR_LINE AS VARCHAR) + CAST(ID_VCHR_LINE_DIST AS VARCHAR) + CODE_TYPE_CHRG + ID_VCHR_LINE_CHRG
    FROM inserted
    EXCEPT
    SELECT ORG + ID_VEND + ID_ORG_ORIG + CAST(ID_VCHR_NBR AS VARCHAR) + CAST(ID_VCHR_LINE AS VARCHAR) + CAST(ID_VCHR_LINE_DIST AS VARCHAR) + CODE_TYPE_CHRG + ID_VCHR_LINE_CHRG
    FROM [dbo].[vwMP_VOD]
  )

END


texts:
I'm trying to find a nice API for a Quiz Engine. This is what I have so far:

Implementation:

public class Question
{
    public string Title { get;set; }
    public List<Answer> Answers { get; set; }

    public Answer CorrectAnswer { get; set; }
}

public class Answer
{
    public bool IsCorrect { get; set; }
    public string Content { get; set; }
}

public class QuizzEngine{
    Queue<Question> questions;

    public QuizzState QuizzState { get; set; }

    public QuizzEngine(IEnumerable<Question> questions)
    {
        this.questions = new Queue<Question>(questions);
        QuestionCount = this.questions.Count;
    }

    void StartQuizz()
    {
        QuizzState = QuizzState.Going;

        while(QuizzState == QuizzState.Going)
        {
            MoveToNextQuestion();
            if(QuizzState == QuizzState.Going) return;
            Answer answer = GetAnswer();
            TryAcceptAnswer(answer);
        }
    }

    Answer GetAnswer()
    {
        Answer answer;
        GetAnswerFromUI(out answer);
        return answer;
    }

    void GetAnswerFromUI(out Answer answer)
    {
        // somehow gets Answer through the UI
        answer = null;
    }

    public void TryAcceptAnswer(Answer answer)
    {
        var isCorrectAnswer = CurrentQuestion.CorrectAnswer.Equals(answer);
        if(isCorrectAnswer) CorrectAnswerCount++;
    }

    public void MoveToNextQuestion()
    {
        if(questions.Count == 0)
        {
            QuizzState = QuizzState.Finished;
            CurrentQuestion = null;
            return;
        }

        CurrentQuestion = questions.Dequeue();
    }

    public Question CurrentQuestion { get; private set; }
    public int CorrectAnswerCount { get; private set; }
    public int QuestionCount { get; private set; }
}

public enum QuizzState{
    Going,
    Finished
}

How could this be improved?


texts:
This is my implementation of recursive merge sort, using sentinels:

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

void merge(int a[], int p, int q, int r)
{
    int n1,n2;
    int i,j,k;
    int *l,*m;

    n1 = q - p + 1;
    n2 = r - q;
    l = (int*)malloc(sizeof(int)*(n1+1));
    m = (int*)malloc(sizeof(int)*(n2+1));

    for(i=0; i<n1; i++)
        l[i] = a[p+i];
    for(j=0; j<n2; j++)
            m[j] = a[q+j+1];
    l[i] = INT_MAX;
    m[j] = INT_MAX;

    i = j = 0;
    for(k=p; k<r+1; k++){

        if(l[i] <= m[j]){
            a[k] = l[i];
            i++;
        }

        else{
            a[k] = m[j];
            j++;
        }

    }
}

void merge_sort(int a[],int p, int r)
{
    int q;

    if(p<r){
        q = (p+r)/2;
        merge_sort(a,p,q);
        merge_sort(a,q+1,r);
        merge(a,p,q,r);
    }
}
int main()
{
    int *num,n;
    int i;

    printf("Enter number of digits:");
    scanf("%d",&n);
    num = (int*)malloc(sizeof(int)*n);
    printf("Enter numbers:");
    for(i=0 ; i<n; i++){
        scanf("%d",&num[i]);
    }
    merge_sort(num,0,n-1);
    printf("Sorted array:\n");
    for(i=0; i<n; i++)
        printf("%d ",num[i]);
    free(num);
    return 0;
}

I'm looking for reviews, suggestions, and improvements.


texts:
I have an abstract Connection class which looks like this:

abstract class Connection
{

    /**
     * @var mixed $instance Represents the instance of the connection
     */
    protected $instance = null;

    /**
     * @return mixed
     */
    public function getInstance() {
        if (!$this->isInitialized()) {
            echo "Cant get instance yet because the connection isn't open";
        }
        return $this->instance;
    }

    /**
     * @return bool
     */
    public function isInitialized() {
        return $this->instance !== null;
    }

    /**
     * Initializes the connection
     */
    public abstract function initialize();

    /**
     * Closes the connection
     */
    public abstract function terminate();
}

It requires an intialize() and terminate()in its childs or subchilds.

The initialize method opens the connection
The terminate method closes the connection

The $instance determinates the object which has to be ran to start the Connection. For example, for a MySQL connection, this could be the mysqli object with its parameters.

A child class of the abstract Connection class looks like this (in this case im only showing a Connection to a database).

This class cannot be instantiated because its also abstract.

abstract class DatabaseConnection extends Connection
{

    /**
     * @var string
     */
    protected $host;

    /**
     * @var
     */
    protected $database;

    /**
     * @var
     */
    protected $username;

    /**
     * @var
     */
    protected $password;

    /**
     * @var
     */
    protected $credentials = [];

    /**
     * @param float  $host
     * @param string $database
     * @param string $username
     * @param string $password
     * @param array  $credentials
     */
    public function __construct($host, $database, $username, $password, $credentials = []) {
        $this->host        = $host;
        $this->database    = $database;
        $this->username    = $username;
        $this->password    = $password;
        $this->credentials = $credentials;
    }

    public final function initialize() {
        if ($this->isInitialized()) {
            throw new Exception("Database connection isnt open yet.");
        }
        $this->instance = $this->getConnectionObject();
    }

    public final function terminate() {
        if ($this->isInitialized()) {
            throw new Exception("Database is closed");
        }
        $this->instance = null;
    }

    protected abstract function getConnectionObject();
}

This mostly speaks for itself, you initialize the credentials in the __construct method.

The getConnectionObject() determinates the object wich has to be instantiated to initialize a Database Connection.

A child class of the DatabaseConnection looks like this:

class MySQLConnection extends DatabaseConnection
{

    /**
     * @return mysqli
     */
    public function getConnectionObject() {
        return new mysqli($this->host, $this->username, $this->password, $this->database);
    }
}

This can be instantiated, to use this, i need to use the following code:

$connection = new MySQLConnection('127.0.0.1', 'db', 'username' 'password');

To open the connection you use the following method:

$connection->initialize();

To close the connection you use the following method:

$connection->terminate();

To give this DatabaseConnection functionality I call  the getInstance() method on the $connection object i've just made.

$connection->getInstance();

In this case this returns the mysqli object, from here i can call all needed functions.

A few notes:

This is for practice, i was trying to create a connection class wich had support for multiple types of connections.
What I originally wanted was to seperate each database function in a seperate class, but i did not know how to do this.


texts: How can I make this primality test algorithm faster?

texts:
Is it possible to make this algorithm faster ?  Algorithm represents primality test for Wagstaff numbers .

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;

public class WPT
{
public static void main(String[] args)
{
   int n;
n = Integer.parseInt(args[0]);

BigInteger m;
m = BigInteger.valueOf(n);

BigDecimal a = new BigDecimal("1.5");
BigDecimal b = new BigDecimal("5.5");
BigDecimal c = new BigDecimal("13.5");
BigDecimal d = new BigDecimal("16.5");

BigDecimal s;
BigDecimal r;

if (m.mod(BigInteger.valueOf(4)).equals(BigInteger.ONE))
  {
     s = a;
     r = a;

  } else {
      if (m.mod(BigInteger.valueOf(6)).equals(BigInteger.ONE))
      {
           s = b;
           r = b;

      } else {
          if (m.mod(BigInteger.valueOf(12)).equals(BigInteger.valueOf(11)) &&
              (m.mod(BigInteger.valueOf(10)).equals(BigInteger.valueOf(1))) ||
              m.mod(BigInteger.valueOf(10)).equals(BigInteger.valueOf(9)))
          {
               s = c;
               r = c;

          } else {
              s = d;
              r = d;

          }
      }
  }

          BigDecimal W;
          W = BigDecimal.valueOf(2).pow(n).add(BigDecimal.ONE).divide(BigDecimal.valueOf(3));

          int k = (n-1)/2;

           for (int i = 1; i <= k; i ++)
    {
   s = s.pow(4).multiply(BigDecimal.valueOf(8)).subtract(s.pow(2).multiply(BigDecimal.valueOf(8))).add(BigDecimal.ONE).remainder(W).setScale(1, BigDecimal.ROUND_UP);

     }

     if (s.equals(r))

  {
      System.out.println("prime");

  } else {

     System.out.println("composite");

     }
}
}

very fast corresponding Mathematica code :

p = 269987;
W = (2^(p) + 1)/3;
If[Mod[p, 4] == 1, a = 3/2, If[Mod[p, 6] == 1, a = 11/2,
If[Mod[p, 10] == 3 || Mod[p, 10] == 7, a = 33/2, a = 27/2]]];
For[i = 1; s = a, i <= (p - 1)/2, i++,
s = Mod[ChebyshevT[4, s], W]];
If[s == a, Print["prime"], Print["composite"]];


texts:
Here's a fiddle: http://jsfiddle.net/YF8cg/

Focussing entirely on the javascript and on the structure of the HTML (.qapair .question and .answer), how could I improve this system?

JS:

$(document).ready(function() {
    $('.question').click(function() {
        $(this).siblings('.answer').slideToggle(400);       // Display the clicked answer

        $(this).parents('.QApair').siblings('.QApair').children('.answer').each(    // Hide all the others
            function() {
                if($(this).is(':visible')) {    // Detects if it's visible
                    $(this).slideToggle(400);   // If true then toggles it
                }
        });
    });
});

HTML:

First Question

Here would be lods of boring text, or some images, or some tables, or some fish, or some lets-pick-another-random-nouns, you get the picture. I just needed to fill space.

Second Question

I've run out of anything to write. So keyboard spas in 5... 4... 3... 2... 1... agdkfdakgjajgjregafgi iej fujagijrfgj rhgjahngufg ughuafng  uuagj u unhu up  u dnfajng hfgnajgnurngr gugnjfngja uugf n ndnfaung urgjangjnfg. That was interesting....

I'm fairly new to jQuery, so any help would be appreciated.

Thanks in advance.


texts: Project Euler #10 in Ruby. Three ways to sum primes below 2 million

texts:
Question:

  Add all prime numbers smaller than 2,000,000.

The first method is done by deriving own is_prime? method:

# First Method
def is_prime(n)
    if n <= 3
        return n > 1
    elsif (n % 2 == 0 || n % 3 == 0)
        return false
    else
        (5..Math.sqrt(n).ceil).step(6) do |i|
            if (n % i == 0 || n % (i+2) == 0)
                return false
            end
        end
        return true
    end
end

start_time = Time.now
range = 2000000
array_of_primes = []

(1..range).each do |n|
    if is_prime(n)
        array_of_primes << n
    end
end

answer = array_of_primes.inject(:+)
duration = Time.now - start_time

puts "Sum of primes below #{range} is #{answer}. Took #{duration} s to calculate using my first method."

Second Method is using Ruby's Prime.is_prime?(n) method:

# Second Method
require 'prime'
array_of_primes = []
start_time = Time.now
(1..range).each do |n|
    if Prime.prime?(n)
        array_of_primes << n
    end
end

answer = array_of_primes.inject(:+)
duration = Time.now - start_time

puts "Sum of primes below #{range} is #{answer}. Took #{duration} s to calculate using my Ruby's Prime.prime? method."

Third method is the simplest form - by using Ruby's Prime.each(2000000) method

# Third Method - Prime.each
start_time = Time.now
answer = Prime.each(range).inject(:+)
duration = Time.now - start_time

puts "Sum of primes below #{range} is #{answer}. Took #{duration} s to calculate using my Ruby's Prime.each method."

All methods gave the correct answer, but the interesting findings is they have drastically different performance, as shown below are the outputs of duration for the computation from each method.

Sum of primes below 2000000 is 142913828922. Took 3.694159 s to calculate using my first method.
Sum of primes below 2000000 is 142913828922. Took 39.370195 s to calculate using my Ruby's Prime.prime? method.
Sum of primes below 2000000 is 142913828922. Took 0.300214 s to calculate using my Ruby's Prime.each method.

As seen above, Best performing is using Prime.each method. I wonder if it already stores a list of prime numbers therefore it doesn't have to compute that long?

Comparing using my own is_prime method and Prime class' Prime.is_prime?(n) method. The Ruby method is taking suprisingly long time to compute the answer. >30s compare to ~3s. Any thoughts on this observation?


texts:
I'd like someone to suggest a better way to create this pattern in Java which I'm sure is possible:

*********
*       *
*       *
*       *
*       *
*       *
*       *
*       *
*********

I'm working my way through a new Java book and am examining string patterns.

public static void drawRectangle() {

    // y axis
    for( int y = 0; y <= 8; y++ )
    {
        if( y == 0 || y == 8 )
        {
            System.out.print( "*********\n" );
            if( y == 8 )
            {
                // Leave loop
                break;
            }
        }

        // x axis
        for( int x = 0; x <= 8; x++ )
        {
            if( x == 0 || x == 8 )
            {
                System.out.print( "*" );
                if( x == 8 )
                {
                    System.out.println();
                }
            }
            else
            {
                System.out.print( " " );
            }
        }
    }
}

Off the top of my head, I'd say that I could replace the values in the loops with constants to work towards. For example:

final static int END_POINT = 8;

Any thoughts?


texts:
I am at the moment trying to grasp multi-file programming instead of one big main.cpp.

The class I wrote is about ISBN 13.

Can you point out what could be done to improve my code?

Also is there a good guide how to write include guards? My sources differate in this respect.

Runnable code here on Wandbox

ISBN.hpp

#include <ostream>

class ISBN
{
/* examples 978-345-314-697-6
978-3-12-732320-7
*/
private:
    //the numbers between the minus signs
    unsigned int isbn_field1;
    unsigned int isbn_field2;
    unsigned int isbn_field3;
    unsigned int isbn_field4;
    unsigned int isbn_field5;
public:
    //constructors
    ISBN()
        : ISBN{978,3,12,732320,7} // a valid ISBN as default
    {}
    ISBN(const unsigned int& a, const unsigned int& b, const unsigned int& c, const unsigned int& d, const unsigned int& e);

    //output operator overloading
    friend std::ostream& operator<<(std::ostream& os, ISBN const& i);
};//ISBN

ISBN.cpp

#include "ISBN.hpp"
#include <iostream>
#include <string>

bool is_valid_isbn(const std::string& digits)
{
    unsigned int weighted_sum=0;
    std::string temp;
    for (unsigned int i=0; i<(digits.length());i++)
    {
        temp=digits[i];
        if ((i%2)==0)
        {
            weighted_sum+=std::stoi(temp);
        }
        else
        {
            weighted_sum+=std::stoi(temp)*3;
        }
    }
    if ((weighted_sum%10)!=0)
    {
        return false;
    }
    return true;
}

ISBN::ISBN(const unsigned int& a, const unsigned int& b, const unsigned int& c, const unsigned int& d, const unsigned int& e)
{
    const std::string digit_string=std::to_string(a)
    +std::to_string(b)
    +std::to_string(c)
    +std::to_string(d)
    +std::to_string(e);
    std::string temp;
    //check if last field is exactly one digit
    temp=std::to_string(e);
    if(temp.length()!=1)
    {
        throw "last unit is not a single digit\n";
    }
    //check if first field is 978 or 979
    if(a!=978 && a!=979)
    {
        throw "first unit is neither 978 nor 979\n";
    }
    //check number of digits=13
    if(digit_string.length()!=13)
    {
        throw "number of digits is not exactly 13\n";
    }
    if (!is_valid_isbn(digit_string))
    {
        throw "not a valid ISBN\n";
    }

    isbn_field1=a;
    isbn_field2=b;
    isbn_field3=c;
    isbn_field4=d;
    isbn_field5=e;
}

std::ostream& operator<<(std::ostream& os, ISBN const& i)
{
    return os << i.isbn_field1 << "-"
    << i.isbn_field2 << "-"
    << i.isbn_field3 << "-"
    << i.isbn_field4 << "-"
    << i.isbn_field5;
}

main.cpp

#include "ISBN.hpp"

#include <iostream>

int main()
{
    try
    {
        ISBN test;
        std::cout << test;
    }
    catch(char const* e)
    {
        std::cout << "Error:" << e;
    }
    catch(...)
    {
        std::cout << "test error";
    }
    return 0;
}


texts: Calculating the font size to fit the width of a website

texts:
I created a function to calculate the font size to fit the width of the website I'm doing. I believe the code is a bit ugly and could use some improvement by creating a more logical function, faster and less heavy.

Can someone look at the code and comment on it for my own improvement?

//Script jquery

$(window).resize(function() {
  newWidthGhost = $('#ghostFontes').width();
  widthFontsResize();
});

$(document).ready(function(){
    $('body').find('*').addClass('wFonte');

$('.wFonte').each(function(i, el){
    fontHeight[i] = $(el).css('font-size');
});

oldWidthGhost = $('#ghostFontes').width(); // TAMANHO WIDTH;

widthFontsReady();

});

function widthFontsResize(){
    $('.wFonte').each(function(i, el){
        nFonte['e'+i] = parseInt((newWidthGhost * nFonte[i]) / oldWidthGhost);
        $(el).css({'font-size': nFonte['e'+i]+'px'});
});

}

function widthFontsReady(){
    $('.wFonte').each(function(i, el){
        nFontHeigth[i] = parseInt(fontHeight[i].substr(0,2));
        nFonte[i] = parseInt((oldWidthGhost * nFontHeigth[i]) / 1586);
        $(el).css({'font-size': nFonte[i]+'px'});
});

}


texts: Using a singleton class to get and set program wide settings

texts:
The following code works and does what I want, but I'd like to confirm I'm using this OOP concept correctly. I'm using the following class to get and set some configuration parameters for my program. It used $GLOBALS for this before, but I'm trying to use a singleton pattern for this instead.

Below is the Config class. Does anything jump out as aggressively stupid? Seeing as how I'm going to be including this in most files any way I figured it would make sense to throw the autoload function in there too- is this bad design?

<?php

  //This class will be included for every file
  //needing access to global settings and or
  //the class library

  spl_autoload_register(function($class){
      require_once 'classes/' . $class . '.php';
  });

  final class Config {

      private static $inst = null;

      //Array to hold global settings
      private static $config = array(
          'mysql' => array(
              'host' => '127.0.0.1',
              'username' => 'root',
              'password' => '123456',
              'db' => NULL
          ),
          'shell' => array(
              'exe' => 'powershell.exe',
              'args' => array(
                  '-NonInteractive',
                  '-NoProfile',
                  '-NoLogo',
                  '-Command'
              )
          )
      );

      public static function getInstance() {
              if (static::$inst === null) {
                  static::$inst = new Config();
              }
              return static::$inst;
      }

      public function get($path=NULL) {

          if($path) {
              //parse path to return config
              $path = explode('/', $path);

              foreach($path as $element) {
                  if(isset(static::$config[$element])) {
                      static::$config = static::$config[$element];
                  } else {
                      //If specified path not exist
                      static::$config = false;
                  }
              }
          }

          //return all configs if path NULL
          return static::$config;
      }

      public function set($path=NULL,$value=NULL) {

          if($path) {
              //parse path to return config
              $path = explode('/', $path);
              //Modify global settings
              $setting =& static::$config;

              foreach($path as $element) {
                      $setting =& $setting[$element];
              }

              $setting = $value;
          }
      }

          //Override to prevent duplicate instance
          private function __construct() {}
          private function __clone() {}
          private function __wakeup() {}
  }

I access it like so:

$aaa = Config::getInstance();
var_dump($aaa->get());
$aaa->set('mysql/host','zzzzzzzzzzzz');
var_dump($aaa->get());

I read a little bit about how singletons are less useful in php. I will research that further at some point, but for the time being I just want to make sure I'm doing this right.


texts: Build Excel formulas with string replacements

texts:
for (long i = 2; i <= numberOfRows; i++)
{
    string quarry =
        "=IF(J"+i+"<10000,J"+i+"*0.05,IF(J"+i+ "<30000,(J" + i + "-10000)*0.1+500,IF(J" + i + "<70000,(J" + i + "-30000)*0.15+2500,IF(J" + i + "<140000,(J" + i + "-70000)*0.2+8500,IF(J" + i + "<250000,(J" + i + "-140000)*0.25+22500,IF(J" + i + "<500000,(J" + i + "-250000)*0.3+50000,IF(J" + i + ">500000,(J" + i + "-500000)*0.32+125000)))))))";
    WS.Cells[i, 11].Formula = quarry;
}

I had originally intended to make this alot neater by adding the base string into a StringBuilder and then doing a string.Replace call on the column value with the long variable i, but it did not work saying i cannot be converted to char.

Not limited to a string builder, how else can I improve this statement where I could easily change the value of a very long string by replacing the concerned elements?

(i.e: this is a pretty long Excel formula C# query that gets inserted into the worksheet as the for loop rolls)


texts:
One thing I realized while going through code yesterday at my internship is that I run sql queries quite often. So I decided to write a function  to keep all of the calls in one place and reduce the number of lines of code. It doesn't cover all possible sql calls but it does cover the basic calls I believe.

So my question is, are there any coding practices I could improve upon or have violated while writing this?

EDIT: I broke the function up into four separate functions. When it comes to PDO my bosses said they did that behind the scenes with each $db_function(there is a different sequence for each server they access) that is called. I'm simply preparing the string that they manipulate. Also I've always viewed associative arrays as field value pairs so I welcome any suggestions in alternative names.

    <?
     *  INPUT:
     *  (string) Db_function: Which sql function to call
     *  (string) Table: The table to use
     *  (string/array) Fields: The values to be manipulated along with valid sql statements/modifiers(e.g DISTINCT or aliases) ,
     *                         its a string for SELECT/DELETE or an array for INSERT/UPDATE.
     *  (string) Conditional: Statements that go at the end of the query such as WHERE, ORDER BY, JOIN etc.
     *
     *  OUTPUT:
     *          TRUE for SELECT/DELETE or the query results for INSERT/UPDATE */

    function sql_Select($Db_Function,$Table, $Fields, $Conditional = NULL){

        $sql = "SELECT $Fields FROM $Table";

          if(!is_null($Conditional)){
                $sql .= $Conditional;
                return $Db_Function($sql,1,1,1);
            }
            return $Db_Function($sql,1,1,1);
    }

    function sql_Update($Db_Function,$Table, $Fields, $Conditional = NULL){

        $sql = "UPDATE $Table SET";

             foreach($Fields as $field => $value){
                $sql .= is_numeric($value) ? " $field = $value , " : " $field = '$value' , " ;
                }
                $sql = preg_replace('/,$/', '', trim($sql)); //Removes the extra ','

         if(!is_null($Conditional)){
            $sql .= $Conditional;
            return $Db_Function($sql,0,0,0);
            }
        return $Db_Function($sql,0,0,0);
    }

    function sql_Insert($Db_Function,$Table, $Fields, $Conditional = NULL){

        $Field_Name = implode(',',array_keys($Fields));
        $sql = "INSERT INTO $Table ($Field_Name) VALUES ( ";

        foreach($Fields as $field => $value){
                        $sql .= is_numeric($value) ? " $value, " : " '$value', " ;
                    }
                    $sql = preg_replace('/,$/', '', trim($sql)); //Removes the extra ','
                    $sql .= ')';

         if(!is_null($Conditional)){
            $sql .= $Conditional;
            return $Db_Function($sql,0,0,0);
            }
        return $Db_Function($sql,0,0,0);
    }

    function sql_delete($Db_Function,$Table, $Fields, $Conditional = NULL){

        $sql = "DELETE FROM $Table";

          if(!is_null($Conditional)){
                $sql .= $Conditional;
                return $Db_Function($sql,0,0,0)
            }
            return $Db_Function($sql,0,0,0)
    }

    ?>


texts: Stable radix sort in-place using O(1) space

texts:
I am trying to implement a stable radix sort in place with O(1) space. I've seen Wikipedia, and I notice the C implementation is using a temporary variable to hold the sorted value for each pass, and the section of "in-place" MSD radix sort implementation is quite confusing.

I took the C code and tried to implement it in C++ for the stable in-place radix sort version:

#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

void radix_sort(vector<int>& v) {
    //search for maximum number
    int max_number = v[0];
    for(int i = 1;i<v.size();i++) {
        if(max_number < v[i])
            max_number = v[i];
    }

    int bucket[10]; // store first index for that digit
    int bucket_max_index[10]; // store maximum index for that digit
    int exp = 1;

    while(max_number / exp > 0) {
        memset(bucket, 0, 10 * sizeof(int));
        memset(bucket_max_index, 0, 10 * sizeof(int));
        for(int i=0;i<v.size();i++) {
            bucket[(v[i] / exp) % 10]++;
        }

        int index = v.size();
        for(int i=9;i>=0;i--) {
            index -= bucket[i];
            bucket_max_index[i] = index + bucket[i];
            bucket[i] = index;
        }

        index = 0;
        vector<int> temp(v.size());
        for(int i=0;i<v.size();i++) {
            int digit = (v[i] / exp) % 10;
            temp[bucket[digit]] = v[i];
            bucket[digit]++;
        }

        for(int i=0;i<v.size();i++) {
            v[i] = temp[i];
        }

        exp *= 10;
    }
}

EDIT:

Thanks to the comments, I checked and found out that I made a mistake. The original idea of the question is that I want to implement a stable in-place radix sort.

I thought I succeeded in implementing it when I tested it with a several test cases (one of them is this test case: {1, 3, 2, 5, 8, 2, 3, 1}) .

I changed the code to a stable radix sort with O(n) space and changed my questions to:

Is this O(kn) time ?  (with k as the maximum number of digits)
Can we improve the above code to be a stable radix sort with O(1) space ?


texts: Merge a new interval into given array of intervals

texts:
This is Merge Intervals problem from www.interviewbit.com

  Problem : Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that
  the intervals were initially sorted according to their start times.

  Example 1:

Given intervals [1,3],[6,9] insert and merge [2,5] :
result [1,5],[6,9].

  Example 2:

Given intervals [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9]
result in [1,2],[3,10],[12,16]

My Approach:

def insert( intervals, new_interval):
    """returns list of intervals after merging"""
    count = 0
    status = False
    final_interval = []
    k = len(intervals)
    new_interval =  (min(new_interval),max(new_interval))
    for i in range(k):

        ## if new interval lesser than given interval
        if min(new_interval) < min(intervals[i]) and max(new_interval) < min(intervals[i]):
            status = False
            break

        ## if new interval falls under given interval
        elif min(new_interval) >= min(intervals[i]) and max(new_interval)<= max(intervals[i]):
            status = True
            break

        ## if given interval falls under new interval
        elif min(new_interval) <= min(intervals[i]) and max(new_interval)>= max(intervals[i]):
            intervals.remove(intervals[i])
            status = True
            intervals.insert(i, new_interval)

        ## part of new interval overlaps with left part of given interval
        elif min(new_interval) <= max(intervals[i]) and min(new_interval) >= min(intervals[i]):
            intervals[i][1]  = max(new_interval)
            new_interval = intervals[i]
            status = True

        ## part of new interval overlaps with right part of given interval
        elif max(new_interval) > min(intervals[i])and max(new_interval) <= max(intervals[i]):

            new_interval[1]  = max(intervals[i])
            intervals.remove(intervals[i])
            status = True
            intervals.insert(i, new_interval)
        count+= 1
    if not status:
        intervals.insert(count,new_interval)

    for elem in intervals:
        if elem not in final_interval:
            final_interval.append(elem)

    return final_interval

Test Cases:

print insert([[1,2],[3,6]],[8,10])
print insert([[3,5],[7,9]],[1,10])
print insert([[3,6],[8,10]],[1,2])
print insert([[1,2],[8,10]],[3,6])
print insert([[1,2],[3,5],[6,7],[8,10],[12,16]],[4,9])
print insert([[1,3],[6,9]],[2,5])

How can this problem be solved in a better way?


texts: Pandas calculations per columns and per rows for very big datasets

texts:
I am using a panda's dataframe and I am doing filtering and some calculations per column and per row.

The dataframe looks this:

   100  200  300  400
0    1    1    0    1
1    1    1    1    0

Each header of the dataframe represents a company ID (x) and the rows represent specific users (y). If the user has accessed that firm, then the in the cell x*y the value is equal with 1 or 0 otherwise. What I want to do is see how searched are 2 firms are in comparison with the other firms. If it is necessary I can go into more detail about the general formula.

for base in list_of_companies:
    counter = 0
    for peer in list2_of_companies:
        counter += 1
        if base == peer:
            "do nothing"
        else:

            # Calculate first the denominator since we slice the big matrix
            # In dataframes that only have accessed the base firm
            denominator_df = df_matrix.loc[(df_matrix[base] == 1)]
            denominator = denominator_df.sum(axis=1).values.tolist()
            denominator = sum(denominator)-len(denominator)

            # Calculate the numerator. This is done later because
            # We slice up more the dataframe above by
            # Filtering records which have been accessed by both the base and the peer firm
            numerator_df = denominator_df.loc[(denominator_df[base] == 1) & (denominator_df[peer] == 1)]
            numerator = len(numerator_df.index)

            annual_search_fraction = numerator/denominator
            print("Base: {} and Peer: {} ==> {}".format(base, peer, annual_search_fraction))

In total I have data for 13 years. I have a ryzen 2700x and it only managed to do 2 days in about 12 hours.

Edit 1 (added example input):

The metric is the following:

1) The metric that I am trying to calculate is going to tell me how many times 2 companies are searched together in comparison with all the other searches.

2) The code is first selecting all the users which have accessed the base firm (denominator_df = df_matrix.loc[(df_matrix[base] == 1)])line. Then it calculates the denominator which counts how many unique combinations between the base firm and any other searched firm by the user are there and since I can count the number of firms accessed (by the user), I can subtract 1 to get the number of unique links between the base firm and the other firms.

3) Next, the code filters the previous denominator_df to select only the rows which accessed the base and the peer firm. Since I need to count the number of users which accessed the base and the peer firm, I use the command:  numerator = len(numerator_df.index) to count the number of rows and that will give me the numerator.

The expected output from the dataframe at the top is the following:

Base: 100 and Peer: 200 ==> 0.5
Base: 100 and Peer: 300 ==> 0.25
Base: 100 and Peer: 400 ==> 0.25
Base: 200 and Peer: 100 ==> 0.5
Base: 200 and Peer: 300 ==> 0.25
Base: 200 and Peer: 400 ==> 0.25
Base: 300 and Peer: 100 ==> 0.5
Base: 300 and Peer: 200 ==> 0.5
Base: 300 and Peer: 400 ==> 0.0
Base: 400 and Peer: 100 ==> 0.5
Base: 400 and Peer: 200 ==> 0.5
Base: 400 and Peer: 300 ==> 0.0

4) The sanity check to see if the code gives the correct solution: all the metrics between 1 base firm and all the other peer firms have to sum up to 1 (all the metrics between base 100 and peer[200,300,400] summed together give 1.


texts:
I have about 5 of these but I can't figure out how to consolidate them.

$('#togglemass').toggle(function () {
    $("#plusmass").attr("src", "minus.png");
  },

  function () {
    $(".plusmass").attr("src", "plus.png");

  });

$('#togglestar').toggle(function () {
    $(".plusstar").attr("src", "minus.png");
  },

  function () {
    $(".plusstar").attr("src", "plus.png");
  });


texts:
I am currently developing a game for Android. One of the things I am working on is moving the map by touch.

This is the code that handles getting speed, which is then added to the screens position and the next update draws the corresponding portion of the map.

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        if (released) {
            touchX = event.getX();
            touchY = event.getY();
            released = false;
        }
        else {
            float newX = event.getX();
            float newY = event.getY();
            speedX = (int) (newX - touchX);
            speedY = (int) (newY - touchY);
            touchX = newX;
            touchY = newY;
        }
        return true;
    case MotionEvent.ACTION_UP:
        released = true;
        return true;
    }
    return false;
}

It works fine, it does. But it seems like it is not enough of a fluid movement.

Does anyone have any idea of how I can make it more like a seamless motion?

EDIT:

And just for info, my fps is currently 80. So I do not believe it is caused by the bitmap drawing itself.


texts: Class library for processing credit cards

texts:
I am developing a class library for processing credit cards. There is a thought in management in the short-term future to look for a new credit card processor. So I want to write once and use everywhere (I should be anyway, right?).

We are currently using First Data's Global Gateway Web Service API. I need a separate web reference setup for live and test.

I am trying to do the following:

//using ProcessCreditCard.WebReference;
using ProcessCreditCard.WebReferenceTest;

public class ProcessCreditCard
{
    private FDGGWSApiOrderService oFDGGWSApiOrderService = null;

    #region Intialize the object
    /// <summary>
    /// Initializes a new instance of the <see cref="ProcessCreditCard"/> class.
    /// </summary>
    public ProcessCreditCard()
    {
        ServicePointManager.Expect100Continue = false;
        // Initialize Service Object
        oFDGGWSApiOrderService = new FDGGWSApiOrderService();
        // Set the WSDL URL
        oFDGGWSApiOrderService.Url = @Properties.Settings.Default.CcApiUrl;
        // Configure Client Certificate
        oFDGGWSApiOrderService.ClientCertificates.Add(X509Certificate.CreateFromCertFile(Properties.Settings.Default.CertFile));
        // Set the Authentication Credentials
        NetworkCredential nc = new NetworkCredential(Properties.Settings.Default.CertUser, Properties.Settings.Default.CertPass);
        oFDGGWSApiOrderService.Credentials = nc;
    }

    /// <summary>
    /// Initializes a new instance of the test version of the <see cref="ProcessCreditCard"/> class.
    /// </summary>
    /// <param name="test">if set to <c>true</c> [test].</param>
    public ProcessCreditCard(bool test)
    {
        ServicePointManager.Expect100Continue = false;
        // Initialize Service Object
        oFDGGWSApiOrderService = new FDGGWSApiOrderService();
        // Set the WSDL URL
        oFDGGWSApiOrderService.Url = @Properties.Settings.Default.CcApiUrl_Test;
        // Configure Client Certificate
        oFDGGWSApiOrderService.ClientCertificates.Add(X509Certificate.CreateFromCertFile(Properties.Settings.Default.CertFile_Test));
        // Set the Authentication Credentials
        NetworkCredential nc = new NetworkCredential(Properties.Settings.Default.CertUser_Test, Properties.Settings.Default.CertPass_Test);
        oFDGGWSApiOrderService.Credentials = nc;
    }
    #endregion

    /// <summary>
    /// Charges the credit card.
    /// </summary>
    /// <returns></returns>
    public MktoResponse ChargeCreditCard()
    {
        /// Code here for setting up the transaction
        return BuildResponse(oFDGGWSApiOrderService.FDGGWSApiOrder(oOrderRequest));
    }

So in my calling code, I can create the right environment based on the boolean:

ProcessCreditCard.ProcessCreditCard pcc = new ProcessCreditCard.ProcessCreditCard(true);

How can I get this so that when I reference the oFDGGWSApiOrderService object that I am using the right environment?


texts:
I drafted a method that I intend to use to convert integers to strings. Is there a way to make it faster? Are there any "simple" changes I could make to improve its performance? This cannot be done with C++11.

std::string to_string(int val) {
    static std::string str;
    static std::stringstream ss;
    ss << val;
    ss >> str;
    ss.clear();
    return str;
}


texts: Insertion of a node in M-way search tree

texts:
I am currently studying data structures and i am looking to see if my implementation of the insertion method in an M-way search tree is good and i am looking forward to improving my coding approach.

There are some basic cases in inserting a node in an M-way search tree:-

Basic Case: If there is still space in the node for new key.

Otherwise,

Case 1: If the data is smaller than the first key of the node then we move towards the first child.

Case 2: If the data is greater than the last node then we move towards the last child.

Case 3: According to the property we check accordingly if the value ranges between the values of two keys.

Code:

#include<iostream>
using namespace std;

struct mWay{
    int index=-1;
    static const int m=3;
    int k[m-1];
    mWay *child[m]={NULL};
};

mWay* createNode(int value){
    mWay *node=new mWay;
    (node->index)++;
    node->k[node->index]=value;
    return node;
}

void sorting(mWay *s){      //using bubble sort..
    int temp;
    for(int i=0;i<(s->index);i++){
        for(int j=0;j<(s->index);j++){
            if((s->k[j])>(s->k[j+1])){
                temp=(s->k[j]);
                (s->k[j])=(s->k[j+1]);
                (s->k[j+1])=temp;
            }
        }
    }
}

mWay* Insert(int data,mWay *root){
    if(root==NULL){         //creating a new mWay tree...
        root=createNode(data);
        return root;
    }
    else{                   //updating the mWay tree...
        mWay *ptr=root;
        mWay *par=NULL;
        int store;          //we will store the index of next child node in this variable (in the last case)...
        while(ptr!=NULL){
            par=ptr;
            if((ptr->index)<(ptr->m)-2){    //checking to see if we can insert more keys in the current node...
                (ptr->index)++;
                ptr->k[ptr->index]=data;
                sorting(ptr);               //sorting keys..
                return root;
            }
            else{       //we have to move to the next node..
                if(data<ptr->k[0]){     //if the data is smaller than the first key of the node then we move towards the first child...
                    ptr=ptr->child[0];
                }
                else if(data>ptr->k[(ptr->m)-2]){       //if the data is greater than the last node then we move towards the last child...
                    ptr=ptr->child[(ptr->m)-1];
                }
                else{       //according to the property we check accordingly if the value ranges between the values of two keys ...
                    for(int i=1;i<(ptr->m)-1;i++){
                        if(data>(ptr->k[i-1]) && data<(ptr->k[i])){
                            store=i;
                            ptr=ptr->child[i];
                            break;
                        }
                    }
                }
            }
        }   //end of while loop which means we just have to insert the node now...
        if(data<(par->k[0])){
            par->child[0]=createNode(data);
        }
        else if(data>(par->k[(par->m)-2])){
            par->child[(par->m)-1]=createNode(data);
        }
        else{
            par->child[store]=createNode(data);
        }
        return root;
    }
}


texts:
Yet another interview question:

  Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.

First off, did I understand the question correctly? In other words, we are looking for a subtree in a tree (or rotation of it) that looks like:

     root
    /    \
 leaf_1  leaf_2
  /
leaf1_1

My initial idea was to count the depth of the tree and check if maxDepth - minDepth < 2 (which requires 2 traversal) . But I think I found a more efficient solution. The trade-off is that we should keep the ref to the root. I assume n-ary tree.

Is this correct?

import java.util.LinkedList;

public class Trees {

    Node threeRoot;
    private boolean isBalanced = true;

    Trees(Node threeRoot){
        this.threeRoot = threeRoot;
    }

    static class  Node{
        public Node root;
        public LinkedList<Node> children = new LinkedList<>();
    }

     boolean isBalanced(Node node){
       if (threeRoot == null) {
            isBalanced = true;
        }
        if (threeRoot.children == null || threeRoot.children.isEmpty()) {
            isBalanced = true;
        }

        isBalancedRed(node);
        return isBalanced;
    }

     void isBalancedRed(Node node) {
        if (node.children.isEmpty()) {
            if (node.root != null && node.root.children.size() == 1) {
                isBalanced = false;
            }
        }
        for(Node nodeEl : node.children)
        {
            isBalancedRed(nodeEl);
        }
    }

    public static void main(String[] args){
        Trees tree = new Trees(new Node());
        Node root = tree.threeRoot;
        Node leaf1 = new Node();
        Node leaf2 = new Node();
        Node leaf11 = new Node();

        root.children.add(leaf1);
        leaf1.root = root;
        root.children.add(leaf2);
        leaf2.root = root;

        leaf2.children.add(leaf11);
        leaf11.root = leaf2;

        System.out.println(tree.isBalanced(root));
    }
}


texts:
Here is my code:

#include <iostream>
#include <type_traits>
#include <functional>
#include <tuple>

namespace meta {

template <bool B, bool... Bs>
struct all_true {
   enum : bool { value = B && all_true<Bs...>::value };
};

template <bool B>
struct all_true<B> {
    enum : bool { value = B };
};

template <typename Fn, typename... Args>
struct is_partial_t_nothrow_ctor {
    enum : bool {
        a = std::is_nothrow_constructible<Fn, Fn&&>::value,
        b = all_true<std::is_nothrow_constructible<Args, Args&&>::value...>::value,
        value = a && b
    };
};

}

template <typename Fn, typename... Args>
class partial_t {
private:
    Fn fn_;
    std::tuple<Args...> args_;

    template <std::size_t... Is, typename... ExArgs>
    decltype(auto) op_parens_impl(std::index_sequence<Is...>, ExArgs&&... ex_args) {
        fn_(std::forward<Args>(std::get<Is>(args_))...,
            std::forward<ExArgs>(ex_args)...);
    }

    template <typename... ExArgs>
    decltype(auto) op_parens_impl(ExArgs&&... ex_args) {
        return op_parens_impl(
            std::index_sequence_for<Args...>(), std::forward<ExArgs>(ex_args)...);
    }

public:
    partial_t(Fn&& fn, Args&&... args)
        noexcept(meta::is_partial_t_nothrow_ctor<Fn, Args...>::value)
        : fn_(std::forward<Fn>(fn)), args_(std::forward_as_tuple(args...))
    {}

    template <typename... ExArgs>
    decltype(auto) operator()(ExArgs&&... ex_args)
        // noexcept(?)
    {
        return op_parens_impl(std::forward<ExArgs>(ex_args)...);
    }
};

template <typename Fn, typename... Args>
auto partial(Fn&& fn, Args&&... args)
    noexcept(meta::is_partial_t_nothrow_ctor<Fn, Args...>::value)
{
    return partial_t<Fn, Args...>(std::forward<Fn>(fn), std::forward<Args>(args)...);
}

Test code:

void test(int x, int y, int z) {
    std::cout << "my first number is " << x << std::endl;
    std::cout << "my second number is " << y << std::endl;
    std::cout << "my favorite number is " << z << std::endl;
}

int main() {
    auto f = partial(test, 5, 3);
    f(7);
}

which outputs:

my first number is 5
my second number is 3
my favorite number is 7

The function partial takes a function object as its first parameter and then a number of arguments. It returns a function object which binds these arguments to the input function as its first parameters, then the rest of the arguments are provided later when this partial function is invoked.


texts:
Is is possible to make this function more efficient and possibly more readable?

In addition, Am I doing this right? I mean, it works, but would it be better to do a complex query (with annotations) or a simple query and then process the result with a "pure python" code-block?

Here is the snippet:

def save_model(self, request, obj, form, change):
        #Creates a list of dictionaries with the group name and role name
        roles = [{'group': group.name, 'role': role.name} for group in form.cleaned_data['groups'] for role in group.groupextended.role.all()]
        roles = sorted(roles, key=lambda k: k['role'])
        #Groups by the role name
        for role, group in itertools.groupby(roles, key=lambda k: k['role']):
            group_list = list(group)
            #Check if the role is in more of one group associated to the user
            if len(group_list) > 1:
                raise Exception('Exception test: {0}, {1}, {2}'.format(role, obj.username, group_list))

        super(UserExtendedAdmin, self).save_model(request, obj, form, change)

Another question is: how many db access I'll have with a method instead another one?


texts: Determine if 2 javascript objects have strictly the same properties

texts:
I need to compare 2 objects to determine if they have strictly the same properties.

This is what I came up with so far:

import isEmpty from 'lodash/isEmpty';

const shallowPropertiesMatch = (firstObject, secondObject) => {
  if (isEmpty(firstObject) || isEmpty(secondObject)) return false;

  const firstObjectKeys = Object.keys(firstObject);
  const secondObjectKeys = Object.keys(secondObject);

  if (firstObjectKeys.length !== secondObjectKeys.length) return false;
  if (!firstObjectKeys.every(value => secondObjectKeys.includes(value))) return false;

  return true;
};

I was wondering if there is a more efficient, elegant or simpler way of doing this?


texts: callback function with no dynamic memory allocation

texts:
I tried to make a callback type for embedded, I know std::function and lambda but I know that there is some dynamic memory allocation that I want to avoid, I came to this implementation:

#pragma once
namespace interfaces
{
    template <class returnType, class ... parameterType>
    class ICallable
   {
       public:
       virtual returnType execute(parameterType ... args) = 0;
   };
}

static callback :

#pragma once

#include "ICallable.hpp"

template <class ReturnType, class ... ParameterType>
class StaticCallback : public interfaces::ICallable <ReturnType,ParameterType...>
{
   public:
      typedef ReturnType (*CallbackFunction)(ParameterType ...);

      constexpr StaticCallback(CallbackFunction function) : m_function(function)
      {
      }

   virtual ReturnType execute(ParameterType ... args) override final
   {
       return m_function(args...);
   }

 private:
    CallbackFunction m_function;
};

and callback with an object

#pragma once
#include "volund/interfaces/system/ICallable.hpp"

 template <class objectType,class returnType,class ... parameterType>
 class ObjectCallback : public interfaces::ICallable<returnType, parameterType ...>
 {
    public:
      typedef returnType (objectType::*Callbackfunction)(parameterType ... args);
      constexpr ObjectCallback(objectType& self, Callbackfunction function) : m_object(&self), m_functionToCall(function)
      {
      }
      constexpr ObjectCallback(objectType *self, Callbackfunction function) : m_object(self), m_functionToCall(function)
      {
      }
      virtual returnType execute(parameterType ... params) override final
      {
          return (*m_object.*m_functionToCall)(params...);
      }

    private:
       objectType* m_object;
       Callbackfunction m_functionToCall;
  };

I'm not sure about the reason of dynamic allocation in std::function, so I'm wondering if there is no pitfall I didn't see in my solution.
If someone have any tips or advice that would be great =)

EDIT :

This is how i use it, typically from a driver that trigger an interrupt and user code register a callback to define some code to be executed on interrupt :

class driver
{
    public:
      void setCallback(ICallable* callback)
      {
         m_callback = callback;
      }

      driver& get()
      {
         return s_self;
      }

     private:
       static s_self;

       Icallable* m_callback;

       static void interrupt()
       {
          s_self.m_callback->execute();
       }
  }

  class user
  {
      public:
        void task()
        {
            driver::get().setCallback(&m_callFromDriver);
            while(true)
            {
               //do something
            }
        }
       private:
         ObjectCallback m_callFromDriver = ObjectCallback(this, &user::onEvent);

        void onEvent()
        {
            //do something
        }
  }


texts: Given a string, find the length of the longest substring without repeating characters

texts:
I wrote an algorithm that solves this problem but I would love to get some feedback on it (especially since I'm not so confident in my Big \$O\$ skills).

Do you think this is a good quality algorithm? Is it efficient? What would be your impression if you were an interviewer? I really want to improve as a programmer so any help is appreciated!

def lengthOfLongestSubstring(self, word):
    longest =0
    currentLength = 0

    if(len(word) > 0):
        currentLength = 1
        longest = 1
        dict = {word[0] : 0}
        i = 1

        while i < len(word):
            if (dict.has_key(word[i])):
                i = dict[word[i]]+1
                dict.clear()
                if (longest < currentLength):
                    longest= currentLength
                currentLength = 0
            else:
                dict[word[i]] = i
                currentLength = currentLength + 1
                i = i + 1

        if (longest < currentLength):
            longest= currentLength

    return longest


texts:
I'm fetching some data by using bs4, and want to know why access speed gets slower as my program progresses.

I'm using thread, and I know threading isn't so fast because of GIL.

My problem is that my program gets slower gradually.
When the number of word is over 300,it become much slower than that of word is about 100 words.

GIL causes this?

(Multiprocessing can solve GIL problem,however,I want to find other causes,if any.)

What is the better web-scraping code to download at once?

Thanks.

import os,gc,queue
import requests, bs4
from threading import Thread, BoundedSemaphore
class add_line:
    def __init__(self,semaphore,q):
        self.q = q # queue
        self.semaphore = semaphore

    def put_queue(self,li): #insert
        self.q.put(li)

    def fetch_word(self,w_list):
        fetched_text = ""# targeted text
        path = "https://ejje.weblio.jp/content/"+ w_list[1]
        res = requests.get(path)
        res.raise_for_status()
        no_starch_soup = bs4.BeautifulSoup(res.text)
        fetched_text = no_starch_soup.select('.conjugateRowR > table > tr > td')
        if len(fetched_text)== 0: #if get nothing
            fetched_text = no_starch_soup.select('.conjugateRowR > a')
            if len(fetched_text) ==0:# if get nothing too
                self.put_queue(w_list)# return original conjurate
            else :
                li_ = list(map(lambda x:x.contents[0], fetched_text))
                li_.insert(0,w_list[0])
                self.put_queue(li_)
        else:
            li_=list(map(lambda x:x.contents[0], fetched_text))
            li_.insert(0,w_list[0])
            self.put_queue(li_)
        gc.collect()
        self.semaphore.release()
if __name__ == "__main__":
    # creating thread
    maxconnections = 5
    path = "./target_index1900.txt"
    """
    the part of this text data is below(the number of words is over 1000)

    510 abandon
    510 abandonment
    1807 abide
    1318 abolish
    1318 abolition
    1167 abortion
    1167 abortive
    1096 abound
    1683 abrupt
    1683 abruptly
    1199 absolute
    1199 absolutely
    507 absorb
    507 absorption
    899 abstract
    899 abstraction

    """
    #set semaphore
    pool_sema = BoundedSemaphore(value=maxconnections)
    q = queue.Queue()# put word  in queue
    al = add_line(pool_sema,q)
    path_w = "./threading_test_result.txt"
    with open(path) as f:
        while True:
            lines = f.readline()
            if not lines:
                break
            pool_sema.acquire()
            Thread(target=al.fetch_word, args=(lines.split(" "),)).start()
    with open(path_w, mode='a') as f:
        while not q.empty():
            for x in q.get():
                f.write(x)
                f.write(" ")
            f.write("\n")
        f.close()
        gc.collect()
    print("Done!")


texts: Using readonly input fields to persist data between views

texts:
I'm building a multi-screen Ajax form in an ASP.NET MVC solution.  The first screen displays some user details.  If the user clicks 'edit', they are taken to the next screen where they can edit the fields.  The call to retrieve the user info is quite slow so I don't want to repeat it for every Ajax request, so I'm thinking of displaying the information on the first screen using @Html.TextBoxFor(m=>m.FieldName, new {@readonly="readonly"}) (styled so it doesn't look like an ordinary readonly input). Then simply posting this information back and re-using it when I show the edit screen.

My initial screen to show existing info (Index.cshtml) is something like this (note that there are more fields, I just showed one to demonstrate the idea):

@using(Ajax.BeginForm("StartEdit", "UserDetails", new AjaxOptions{...})
{

        @Html.LabelFor(m=>m.FirstName)
        @Html.TextBoxFor(m=>m.FirstName, new { @readonly = "readonly" })

    <input type="submit" value="Edit"/>
}

and the edit screen (Edit.cshtml) is something like this:

@using(Ajax.BeginForm("SubmitChanges", "UserDetails", new AjaxOptions{...})
{

        @Html.LabelFor(m=>m.FirstName)
        @Html.TextBoxFor(m=>m.FirstName)

}

The controller is as follows:

public class UserDetailsController
{
    public PartialViewResult Index()
    {
        var viewModel = new MyViewModel(); //populated from web service, slow operation
        return PartialView("Index", viewModel);
    }

    public PartialViewResult(MyViewModel viewModel)
    {
        return PartialView("Edit", viewModel); //returning posted viewModel back to next view
    }

}

Is there anything wrong with doing this, or should I just use hidden fields to persist the information and render that same information to the user using @Html.DisplayFor(m=>m.FieldName) etc?


texts: Traverse all switch branches without goto

texts:
I'm wondering wether there is a way to walk through every branch of this switch without using goto

    public static List<KpiGroup> GetKpiGroups(int siteId, int topLevelProjectId, SiteDetailsModel.KpiCategory category, bool applyMapFilters)
    {
        var kpiGroups = new List<KpiGroup>();

        switch (category)
        {
            case SiteDetailsModel.KpiCategory.Any:
            case SiteDetailsModel.KpiCategory.Wbs:
                kpiGroups.Add(KPIGetActiveSite(siteId, topLevelProjectId));
                if (category == SiteDetailsModel.KpiCategory.Any)
                    goto task;
                break;

            case SiteDetailsModel.KpiCategory.Task:
        task:
                kpiGroups.Add(KPIGetTicketStatus(siteId, topLevelProjectId));
                kpiGroups.Add(KPIGetTicketSeverityClosed(siteId, topLevelProjectId));
                kpiGroups.Add(KPIGetTicketSeverityOpen(siteId, topLevelProjectId));
                kpiGroups.Add(KPIGetTicketOwnerOpen(siteId, topLevelProjectId));
                kpiGroups.Add(KPIGetTicketOwnerClosed(siteId, topLevelProjectId));
                kpiGroups.Add(KPIGetTicketActivity(siteId, topLevelProjectId));
                if (category == SiteDetailsModel.KpiCategory.Any)
                    goto sysConfig;
                break;

            case SiteDetailsModel.KpiCategory.SysConfig:
        sysConfig:
                kpiGroups.Add(KPIGetSysConfigOverview(siteId, topLevelProjectId));
                kpiGroups.Add(KPIGetSysConfigDeviceTypes(siteId, topLevelProjectId));
                kpiGroups.Add(KPIGetSysConfigLevel(siteId, topLevelProjectId));
                break;

            default:
                throw new ArgumentOutOfRangeException(String.Format("GetKpiGroups {0}", category.ToString()));
        }

        return kpiGroups;
    }