Class to Return Single Integer I have a class used to return a single integer, but think there is room for improvement. The class should only return a single row every time and if no row is found it might be a good idea to throw an error from the class rather than from the calling code which will break when the integer comes back as zero.

The function below is called from a sync application that is returning a primary key in order to make an update.

    public static int GetCommuteDataID(CommuteData commuteData)
    {
        int commuteDataID = 0;
        using (var db = new CarbonContext())
        {
            var returnCommuteData = from e in db.CommuteDatas
                              where e.id == commuteData.id &&
                                    e.SurveyID == commuteData.SurveyID &&
                                    e.SurveyYear == commuteData.SurveyYear
                              select e.CommuteDataID;

            foreach (var item in returnCommuteData)
                commuteDataID = Convert.ToInt32(item.ToString());
        }
        return commuteDataID;
    }

Here is the code that calls GetCommuteDataID:

//Make sure the record does not exist
if (!CommuteDataRepository.CommuteDataExists(localCommuteData))
    db.CommuteDatas.Add(localCommuteData);
else
{
    localCommuteData.CommuteDataID = CommuteDataRepository.GetCommuteDataID(localCommuteData);
    db.Entry(localCommuteData).State = System.Data.EntityState.Modified;
}

Here is the new function:

public static int GetCommuteDataID(int? id, int surveyID, int surveyYear)
{
    using (var db = new CarbonContext())
    {
        return db.CommuteDatas
                 .Where(cd => cd.id == id &&
                              cd.SurveyID == surveyID &&
                              cd.SurveyYear == surveyYear)
                 .Select(cd => (int)cd.CommuteDataID)
                 .SingleOrDefault();
    }
}

I see a number of things wrong with this implementation:

First, You already have a CommuteData entity. Why are you using it to go back to the database to retrieve a property that's already on it (ie: commuteData.CommuteDataId)? This makes me very suspicious of any calling code (you may want to post a use case for clarity).

That point aside, if there's a possibility that the method will be unable to return, it should throw an exception if an invalid state is encountered, or not return a number that is invalid (ie: 0).

To combat this, you could go with one of these patterns:

// Throw an exception if there is no applicable CommuteDataId but one
// is always expected to be available when calling this method:
public static int GetCommuteDataId(CommuteData commuteData)
{
    ...
    // Tell EF that you only expect one and only one result.
    return something.Single()
}

// Return null if there is no applicable CommuteDataId...
public static int? GetCommuteDataId(CommuteData commuteData)

// Return true if commuteDataId contains a valid Id.
public static bool TryGetCommuteDataId(CommuteData commuteData, out commuteDataId)

The property names you're using are also very confusing. What's the difference between CommuteData.id and CommuteData.CommuteDataID? Furthermore, the casing of your properties are not consistent: id, CommuteDataID, SurveyId.

This code is also very suspicious:

commuteDataID = Convert.ToInt32(item.ToString());

It would appear that you are converting an int to a string, then back to an int. If it's not an int, the method should return it in it's true form instead of doing any misleading conversion that the caller has no idea about.

Lastly, you're pulling back too much information from the database. SQL (and thus EF) can return exactly what you want in a single call.

public static int? GetCommuteDataID(int commuteDataId)
{
    using (var db = new CarbonContext())
    {
        return db.CommuteDatas
                 .Where(cd => cd.id == commuteDataId)
                 .Select(cd => (int?)cd.CommuteDataID)
                 .SingleOrDefault();
    }
}

The updated example above still has several problems with it, but hopefully it illustrates some of the points I was trying to make.

UPDATE:

Your updated function is almost there, but there are still some things wrong/misleading about it:

public static int GetCommuteDataID(int? id, int surveyID, int surveyYear)

Why is id nullable here? This implies that either:

If id isn't provided, surveyId and surveyYear are enough to produce a unique result (otherwise you wouldn't be returning a single int).
id can be used along with surveyId and surveyYear to produce a unique result even when it's null (unlikely).

Next:

.Where(cd => cd.id == id &&
    cd.SurveyID == surveyID &&
    cd.SurveyYear == surveyYear)

Again, are you sure this is the criteria you want to use to ensure uniqueness? Why would id exist if it wasn't unique?

.Select(cd => (int)cd.CommuteDataID)
.SingleOrDefault();

Lastly, if CommuteDataID is already an int there's no need to cast it to one. SingleOrDefault has three outcomes:

The query produces no result: The default value for the type of query is returned. When you Select an int, the default value is 0 because that's the default value for an int. I was casting to int? in my example so it would return null (the default for int?) when no value was found.
The query produces one result: The result is used.
The query produces multiple results: An exception is thrown because it was expected that only 0 or 1 results would be returned based on the filters you provided.

If your inputs should produce one and only one result, then you should use Single(), which will throw an exception if 0 or multiple results are returned by the query. All of this would imply that your method arguments were enough to produce a single result which doesn't seem to be the case.


Sending an email every half hour if a certain condition is met This will be called every minute from the background thread. If my unauthorizedCount and badRequestCount is not equal to zero, then I send out an email.

private void callMetrics() {

    // .. some other code

    // send an email for unauthorized count
    if (Integer.parseInt(unauthorizedCount) != 0) {
        // send an email here
    }

    // send an email for bad request count
    if (Integer.parseInt(badRequestCount) != 0) {
        // send an email here
    }
}

For example, if my unauthorizedCount is non-zero, then it will be non-zero at least for an hour. That means it will keep on sending out an email every minute for an hour, so our email will get flooded up with this. That's what I don't want to have, same thing with badRequestCount.

Now what I want to do is, as soon as unauthorizedCount is non-zero, it will send out its first email. If it is non-zero again continuously for half an hour, then I would like to send another email after half an hour. If it is non-zero continuously, but suppose if the first time it was non-zero, I will send out an email. Next time it is non-zero, I won't send another email, but if the third time it was zero, then I will reset the counter so that it sends out an email instantly.

I basically want to send out my first email whenever unauthorizedCount is non-zero but if it is non zero again in the next minute, then I don't want to send out another email and will send out another email if unauthorizedCount is non-zero after half an hour.

private static long lastUnauthorizedSent = -1;
private static long lastBadRequestSent = -1;

private void callMetrics() {

    // .. some other code

    long now = new Date().getTime();

    // send an email for unauthorized count
    if (Integer.parseInt(unauthorizedCount) != 0 && satisfiesUnauthorizedSinceLast(now)) {
        // send an email here
        lastUnauthorizedSent = now;
    } else {
        lastUnauthorizedSent = -1;
    }

    // send an email for bad request count
    if (Integer.parseInt(badRequestCount) != 0 && satisfiesBadRequestSinceLast(now)) {
        // send an email here
        lastBadRequestSent = now;
    } else {
        lastBadRequestSent = -1;
    }
}

private void satisfiesUnauthorizedSinceLast(long now) {
    return lastUnauthorizedSent == -1 || now - lastUnauthorizedSent > 30*60*1000;
}

private void satisfiesBadRequestSinceLast(long now) {
    return lastBadRequestSent == -1 || now - lastBadRequestSent > 30*60*1000;
}

We know what this is 30*60*1000 but you should put that into a variable instead of just letting it lay around out there naked like that.

public long waitTime = 30*60*1000;

and you can put it in whatever scope that you want to and use it as often as you like, just make sure that if you change it you know what it will affect.


Calculating a pattern-match score on a ten-element array I have a method in Python that is extremely slow:

def patternRecognition(self):
    patRecStartTime = time.time()
    plotPatAr = []
    patFound = 0

    for eachPattern in self.patternAr:
        sim1 = 100.00 - abs(self.percentChange(eachPattern[0], self.patForRec[0]))

        if sim1 > 50:
            sim2 = 100.00 - abs(self.percentChange(eachPattern[1], self.patForRec[1]))
            if sim2 > 50:
                sim3 = 100.00 - abs(self.percentChange(eachPattern[2], self.patForRec[2]))
                if sim3 > 50 :
                    sim4 = 100.00 - abs(self.percentChange(eachPattern[3], self.patForRec[3]))
                    if sim4 > 50 :
                        sim5 = 100.00 - abs(self.percentChange(eachPattern[4], self.patForRec[4]))
                        if sim5 > 50:
                            sim6 = 100.00 - abs(self.percentChange(eachPattern[5], self.patForRec[5]))
                            if sim6 > 50 :
                                sim7 = 100.00 - abs(self.percentChange(eachPattern[6], self.patForRec[6]))
                                if sim7 > 50 :
                                    sim8 = 100.00 - abs(self.percentChange(eachPattern[7], self.patForRec[7]))
                                    if sim8 > 50:
                                        sim9 = 100.00 - abs(self.percentChange(eachPattern[8], self.patForRec[8]))
                                        if sim9>50:
                                            sim10 = 100.00 - abs(self.percentChange(eachPattern[9], self.patForRec[9]))

                                            howSim = (sim1+sim2+sim3+sim4+sim5+sim6+sim7+sim8+sim9+sim10)/10.00

                                            if howSim > 70:
                                                patFound = 1
                                                plotPatAr.append(eachPattern)

    if patFound == 1:
        for eachPatt in plotPatAr:
            futurePoints = self.patternAr.index(eachPatt)

            if self.performanceAr[futurePoints] > self.patForRec[29]:
                #do something
            else:
                #do something

Does anyone have any suggestions on making this method execute quicker? When the array gets to 50,000 elements, it takes about 1 second to execute and increases as the array patternAr grows. I read that converting the for loop into a map would make it quicker, however, I have not been able to figure it out.

I should mention that percentChange is very simple:

def percentChange(self, startPoint,currentPoint):
    try:
        x = ((float(currentPoint)-startPoint)/abs(startPoint))*100.00
        if x == 0.0:
            return 0.000000001
        else:
            return x
    except:
        return 0.0001

Initial code with sample data here.

This whole approach is completely bogus and not worth your time.

A "pattern" is simply an array of percentage changes. For simplicity let's use a pattern size of 5. So a pattern might look like:

pat1 = [ 1%, 3%, -2%, 1.6%, 2.1% ]

meaning that the price difference (from the price at time 0) at time 1 was 1%, at time 2 was 3%, at time 3 was -2%, etc.

Given another pattern we want to compute how "similar" they are. This is done componentwise using a similarity function for percentages whose definition is:

sim(p,q) = 100 - abs (percentageChange(p,q))

where percentageChange is the percent change between p and q with an absolute value in the denominator:

percentChange(p,q) = 100 * (p-q)/abs(q)

So in python, sim is:

def sim(p,q):
  """Compute the similarity between two percentage changes."""
  pc = 100 * (p-q) / abs(q)
  return 100 - abs(pc)

Note since we are multiplying everything by 100 that the 1% value in pat1 is just the value 1, not the conventional 0.01.

Given two patterns, pat1 and pat2, we say they are close if

sim( pat1[i], pat2[i] ) >= 70   for each i in 0..4

The big idea

The idea behind these patterns and similarity measures is that given historical data we compute a pattern and a future price change with the idea that the pattern implies the future price change.

Then given current data we compute the current pattern and search for a similar pattern in our database from which we can deduce the corresponding price change.

The main problem is that the sim function is not symmetrical in its arguments, i.e. sim(p,q) and sim(q,p) may have wildly different values.
Consider these examples:

sim(1.200, 2.000)   = 60.000000
sim(2.000, 1.200)   = 33.333333

sim(-1.000, 2.000)  = -50.000000
sim(2.000, -1.000)  = -200.000000

sim(-1.000, -2.000) = 50.000000
sim(-2.000, -1.000) = 0.000000

sim(-1.000, 1.000)  = -100.000000  # guess these are actually the same!
sim(1.000, -1.000)  = -100.000000

sim(-1.000, -0.100) = -800.000000
sim(-0.100, -1.000) = 10.000000

sim(-1.000, 0.100) = -1000.000000
sim(0.100, -1.000) = -10.000000

A better definition for sim(p,q) would simply be:

sim(p,q) = abs(p-q)

and then to define two patterns to be close if

sum of sim(pat1[i], pat2[i]) for i in 0..4
  is LESS THAN a certain number

The prediction algorithm then boils down to a nearest neighbor search in a high number of dimensions (e.g. the length of the pattern array.)


Chain nesting XML elements I have a scenario where I need to chain nest XmlElements, and I got a working solution using a recursive function, but  I can't help but feel that it can be made better.

Here's my code so far:

function AppendChild
{
    param
    (
        [string[]]$string,
        $obj,
        [System.Xml.XmlDocument]$XML
    )
    if ($string.Length -gt 0)
    {
        $child = $XML.CreateElement($string[0])
        $child.InnerText = ""
        AppendChild -string ($string | Select -Skip 1) -obj $child -XML $XML
        $obj.AppendChild($child)
    }
}

$string = "this is a somewhat long string" -split " "

$XML = New-Object System.Xml.XmlDocument
$root = $XML.CreateElement($string[0])

AppendChild -string ($string | Select -Skip 1) -obj $root -XML $XML

$root.OuterXml # <this><is><somewhat><long><string></string></long></somewhat></is></this>

Any suggestions?

I don't think you need recursion. Just a simple loop will do. We can just keep a reference to the last element in the document, which we update every time we append a new element, and we keep appending to that.

$tagNames = "this     is a somewhat long string" -split "\s+"
$XML = New-Object System.Xml.XmlDocument

$lastElt = $XML

$tagNames | % {
    $elt = $XML.CreateElement($_)
    $lastElt = $lastElt.AppendChild($elt)
}

$xml.OuterXml # <this><is><somewhat><long><string /></long></somewhat></is></this>

I also changed it to split the string on \s+, which is a regular expression meaning "one or whitespace characters", so that multiple consecutive spaces (or tabs or whatever) will be counted as a single thing as far as -split is concerned.

I change $string to $tagNames because it is important to name variables accurately otherwise you will confuse yourself.


Module pattern callback implementation I'm rewriting a simple app using HTML/CSS/JavaScript that creates animations with images using intervals, and there's a bunch of buttons that controls these animations.

It's scaling and becoming really messed up, with logic mixed with DOM manipulations via jQuery all through one JavaScript script file.

I've decided to use the Module design pattern.  Based on my description of the app, is there a problem with this callback implementation for a module, or with the module implementation?

In this example, what is the best approach to declare private variables and give access to them through the public API? Getters and setters? Are they really necessary? I want to write readable code but I don't want to over-architect things.

(function($) {

  $.Module = function(options){
    var module = {
      options: $.extend({
        callbacks: {
          start: false
        }
      }, options),
      start: function(callback){
        //console.log('private start method');
        if(typeof callback === "function") {
            callback();
        }
      }
    }

    // public api
    return {
      start: function(){
        //console.log('public start method');
        module.start(module.options.callbacks.start);
      }
    }
  }

}($));

var myModule = $.Module({
  callbacks: {
    start: function(){
      console.log('start callback!');
    }
  }
})

myModule.start();

Here is a sample.

this next issue is actually just for the sake of learning

That seems to work to me so far. But I've seen other implementations that have some code that look like this:

callback: function(method) {
    if(typeof method === "function") {
        var args = [];

        for(var x = 1; x <= arguments.length; x++) {
            if(arguments[x]) {
                args.push(arguments[x]);
            }
        }

        method.apply(this, args);
    }
},

I'm not sure what this last code is supposed to do. Is it intended to return data to the callback function I registered when instantiating the module?

The last piece is: Whoever is calling that callback: function itself may be passing params to it, which need to be repackaged into a genuine array from their source in the (implementation deficient) arguments array, before they can be passed to method via apply which is essentially tacking on the method method to this and calling it.


Basic Bill of Materials schema I've been working on Bill of Materials mini schema for a while. At first I had single Part table where I've referenced itself. I was told it would be better to have separate table because we'd need to have info like quantity and that quantity is not part of Part itself. Here's the script...

CREATE TABLE Part
(
    ID INT NOT NULL PRIMARY KEY IDENTITY,
    PartNumber NVARCHAR(50) NULL,
    [Description] NVARCHAR(MAX) NULL,
    ListPrice DECIMAL(12,2) NULL
)

CREATE TABLE BOM
(
    ID INT NOT NULL PRIMARY KEY IDENTITY,
    PartId INT NOT NULL,
    ParentId INT NULL,
    Quantity INT NULL
)

ALTER TABLE BOM ADD CONSTRAINT BOM_PartId_FK
FOREIGN KEY (PartId) REFERENCES Part(ID)

ALTER TABLE BOM ADD CONSTRAINT BOM_ParentId_FK
FOREIGN KEY (ParentId) REFERENCES Part(ID)

insert into Part (PartNumber, Description, ListPrice) values ('AAA', 'A', 250.00)
insert into Part (PartNumber, Description, ListPrice) values ('AA', 'A', 100.00)
insert into Part (PartNumber, Description, ListPrice) values ('BBB', 'B', 250.00)
insert into Part (PartNumber, Description, ListPrice) values ('BB', 'B', 90.00)
insert into Part (PartNumber, Description, ListPrice) values ('B', 'B', 40.00)

insert into BOM (PartId) values (1)
insert into BOM (PartId, ParentId, Quantity) values (2, 1, 5)
insert into BOM (PartId, ParentId, Quantity) values (4, 3, 10)
insert into BOM (PartId, ParentId, Quantity) values (5, 4, 50)
insert into BOM (PartId, ParentId, Quantity) values (4, 1, 50)

Would this be ok as beginner BOM schema?

I've tested with the below query, this gets immediate children of BOM with ID of 1.

select e.*
from BOM b
join BOM e on b.PartId = e.ParentId
where b.ID = 1

I will recursively call this from c# to populate children from any level in the BOM, but usually top most level.

It's ok, but there's room for improvement.

Don't use BOM. Use BillOfMaterials.
It won't matter to you, but the next guy will thank me.
You're missing indexes on the items you defined foreign keys for. They're not free, you have to create them yourself.
I find it really odd that the BOM.Quantity can be null. If a part is on the BoM, shouldn't there be at least one of them required as part of the "kit"? I may even consider using a default value of one.


There are some obvious items, and then some not-so-obvious ones, that should be addressed.

The most obvious, is this line here:

sum = sum * i;

Really? That's a sum. Don't you mean product?

The next obvious item is that the function should take the number of digits, and the input sequence, as parameters. I would expect a function like:

function eulerProblem8(span, digits) {
    ....

and then the function returns the largest value.

Now, about the algorithm, this is more complicated. There is a way to do it in \$O(n)\$ time complexity. You can scan all the data just once, with a zero-counter, and multiplication and division.

scan each position in the input
if your sequence will be longer than the span, remove the unneeded digit using division (if the value is non-zero - or decreasing the zero-counter if the value is zero).
if the next value in the sequence is zero, increment the zero counter, otherwise include the digit by mutiplying the product.
if the new product is larger than previous products, then remember this new maximum
report the maximum.

Consider the following....

function eulerProblem8(span, sequence) {

    var follow = -1;
    var zeroes = 0;
    var maxprod = 0;
    var prod = 1;
    var digit;

    for (var lead = 0; lead < sequence.length; lead++) {

      // determine the least digit
      if (lead - follow > span) {
        follow = lead - span;
      }

      if (follow >= 0) {
        // remove least digit
        digit = Number(sequence[follow]);
        if (digit == 0) {
          zeroes--;
        } else {
          prod /= digit;
        }
      }

      // include the next digit
      digit = Number(sequence[lead]);
      if (digit == 0) {
        zeroes++;
      } else {
        prod *= digit;
      }

      // if there are no zeros in the sequence, and it exceeds previous...
      if (zeroes == 0 && prod > maxprod) {
        maxprod = prod;
      }
    }

    return maxprod;
}

var amountOfDigits = 13;
var sequence = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"

document.getElementById('result').innerHTML = "Max: " + eulerProblem8(amountOfDigits, sequence);

result

unused


Haskell Either Applicative where the Left is a Monoid I'm currently learning Haskell and are starting to understand applicatives.

I wanted an Either Applicative where the left side is a monoid, so I created this as a learning exercise:

module EitherLeftMonoid where

data Error = InvalidName | UnderAge deriving (Eq, Show)

data Person = Person { name :: String, age :: Int } deriving (Eq, Ord, Show)

data EitherLeftMonoid a b = Lefty a
                          | Righty b
                          deriving (Eq, Show)

instance Monoid a => Functor (EitherLeftMonoid a) where
  fmap _ (Lefty a)  = Lefty a
  fmap f (Righty b) = Righty (f b)

instance Monoid a => Applicative (EitherLeftMonoid a) where
  pure                  = Righty
  Lefty a <*> Lefty a'  = Lefty (a `mappend` a')
  Lefty a <*> _         = Lefty a
  _ <*> (Lefty a)       = Lefty a
  Righty f <*> Righty x = Righty (f x)

mkName :: String -> EitherLeftMonoid [Error] String
mkName "" = Lefty [InvalidName]
mkName s  = Righty s

mkAge :: Int -> EitherLeftMonoid [Error] Int
mkAge n | n < 13    = Lefty [UnderAge]
        | otherwise = Righty n

mkPerson :: String -> Int -> EitherLeftMonoid [Error] Person
mkPerson n a = Person <$> mkName n <*> mkAge a

Output:

Prelude> mkPerson "" 12
Lefty [InvalidName,UnderAge]
Prelude> mkPerson "" 13
Lefty [InvalidName]
Prelude> mkPerson "Gerd" 13
Righty (Person {name = "Gerd", age = 13})

What could I have done different to make the code better?

Your Functor instance doesn't need a to be a Monoid. We can remove that constraint to make fmap on EitherLeftMonoid more general.

Your Applicative instance could be made a little bit more readable if you provide a fromLefty :: Monoid a => EitherLeftMonoid a b -> a function:

instance Functor (EitherLeftMonoid a) where
  fmap _ (Lefty a)  = Lefty a
  fmap f (Righty b) = Righty (f b)

instance Monoid a => Applicative (EitherLeftMonoid a) where
  pure                  = Righty
  Righty f <*> Righty x = Righty (f x)
  x        <*> y        = Lefty $ fromLefty x `mappend` fromLefty y

fromLefty :: Monoid a => EitherLeftMonoid a b -> a
fromLefty (Left x) = x
fromLefty _        = mempty

With fromLefty we can take advantage of mappend mempty x = x = mappend x mempty.

In this case everything is in a single module and everything gets exported. This enables a user to use the Person constructor immediately. If you want to prevent that you need to make sure that only the type, but neither the records nor the data constructor get exported. Otherwise mkPerson can get circumvented.


Using Dynamic to create and then flatten an arbitrarily-nested array I have some code that I posted as a possible answer on StackOverflow (and the code I post here is almost an exact duplicate of that, but I'd rather include complete information in this post as well so people don't have to jump back and forth between posts to understand the question). I truthfully haven't quite decided whether it's terrible, really clever, or something in between (which is why I'm asking for reviews here).

I'm perfectly aware that the use of dynamic in C# is somewhat controversial. That aside, though, I'll freely admit that I rarely use it and am curious as to whether this is what would normally be considered a "valid" use of it.

Basically, the problem is to create and then "flatten" an arbitrarily-nested array. At any given index, the array could contain either an integer or another array of integers, so you could have something like this:

[ 1 2 3 4 5
  [6 7
      [8 9
         [10 11 12]
       13 14 15]
  16 17]
18 19 20]

The resulting "flattened" array would be 1, 2, 3, 4, 5, 6, 7...20.

I use the following code to create the array:

Random random = new Random();
        dynamic array = new dynamic[random.Next(3, 10)];
        for (int i = 0; i < array.Length; i++)
        {
            if (random.NextBool())
            {
                array[i] = new dynamic[random.Next(3, 10)];

                for (int j = 0; j < array[i].Length; j++)
                {
                    if (random.NextBool())
                    {
                        array[i][j] = random.Next(1, 100);
                    }
                    else
                    {
                        array[i][j] = new int[random.Next(3, 10)];

                        for (int k = 0; k < array[i][j].Length; k++)
                        {
                            array[i][j][k] = random.Next(1000);
                        }
                    }
                }
            }
            else
            {
                array[i] = random.Next(1, 100);
            }
        }

where NextBool is an extension method on the Random class:

public static bool NextBool(this Random random)
    {
        return random.Next(0, 1) == 0;
    }

Once I've created this, I can use recursion to "flatten" the list. Essentially, at any point I determine if this is a "base" case (it's just an integer) or if it's a (potentially arbitrarily-nested) array. If it's an array, I just loop over it, add the integers to the final result, and do a recursive call on any arrays I find.

private void Flatten(dynamic item, List<int> flattened)
{
    // This is the base case - the item's just an integer
    if (item.GetType() == typeof(int))
    {
        flattened.Add((int)item);
    }
    else
    {
        foreach (dynamic itm in item)
        {
            // Handle the case where the current item's an int
            if (itm.GetType() == typeof(int))
            {
                flattened.Add(itm);
            }
            // If it's not an int, it must be an array - recursively process it
            else
            {
                Flatten(itm, flattened);
            }
        }
    }
}

I could probably simply this a little by simply making everything arrays - i.e. instead of "plain" integers I have an array of length 1 - but I'm not sure that this is a dramatic improvement.

Anyone have opinions on whether this is a good solution or not? (I honestly won't be offended if people think it's a terrible idea, I'd rather have the honest feedback). Are there ways I could improve this or solve it in a better way?

Edit: I'm using arrays here (rather than some kind of a Tree structure, which I think would be preferable for data structured like this) because of constraints in the post I was responding to on SO.

There's never any reason to use dynamic here at all.  You never use any of its features.  You could literally copy-paste all instances of it with object and the code would function identically.

Now, that's not a particularly good design for storing data like this.  If you actually want to store a tree of data you're better off with a more traditional tree setup.  Create a Node type, and let those nodes have both values and child nodes, which can themselves have child nodes, and so on.  You can then traverse that tree structure.  That makes it much clearer what's going on, rather than just seeing an object that you happen to just know is a tree structure where it contains either a sequence of other objects, or a value, and where each object in the sequence may itself be a sequence or a value.  It also means that when you create operations that work with these trees they can accept instances of those types, so people don't do weird things like pass in a string to your method here, only to have it crash, instead of just failing to compile.

As for the actual Flatten method, personally I'd prefer a non-recursive implementation.  Most significantly because the stack in C# just isn't that big, and it's not really all that uncommon to have tree structures that are deeper than the stack can support, resulting in you getting stack overflow exceptions.  It's a little bit easier code to write the recursive version for many people, but you're constraining yourself to only working with shallow trees by using it.

I'd also suggest making the Flatten method an iterator block.  There's no sense computing the entire value right from the start, when the underlying algorithm itself is inherently computing one value at the time.  Using an iterator block lets the consumer use each value as you compute it, and removes the need for you to do the work of computing values that may not be needed, and also prevents the entire result set from needing to be in memory all at once, assuming the resulting values can be processed one at a time (a common enough situation).


Converting from POS tagged word-tokens to POS tagged Phrases I have sentences expressed as Parts of speech (POS) tagged words.
I want to have all the short phrases in them to be joined up with underscores.
I want them to have the Part of speech tag of the final word in the phrase -- not because this is necessarily linguistically correct, but because it will perform correctly in my system later when it has to "Unstem"/"Unlemmaize" derived words/phrases.

For example, if I had the following sentence, (based off of the first sentence in the Microsoft research paraphrase corpus):

  PCCW's chief operating officer, Mike Butcher, and the Arena brothers, the chief financial officers, will report directly to the police officer.

Then the POS tagged text is:

[('PCCW', 'NNP'), ("'s", 'POS'), ('chief', 'NN'),('operating', 'VBG'), ('officer', 'NN'),(',', ','),('Mike', 'NNP'),('Butcher', 'NNP'), (',', ','),('and', 'CC'),('the', 'DT'),('Arena', 'NNP'),('brothers', 'NNS'),(',', ','),('the', 'DT'),('chief', 'JJ'), ('financial', 'JJ'),('officers', 'NNS'),(',', ','),('will', 'MD'),('report', 'VB'),('directly','RB'),('to', 'TO'),('the', 'DT'), ('police', 'NN'),('officer', 'NN'), ('.', '.')]

And the POS tagged phrases (ie the output of my function) is:

[('PCCW', 'NNP'), ("'s", 'POS'), ('chief_operating_officer', 'NN'), (',', ','), ('Mike', 'NNP'), ('Butcher', 'NNP'), (',', ','), ('and', 'CC'), ('the', 'DT'), ('Arena', 'NNP'), ('brothers', 'NNS'), (',', ','), ('the', 'DT'), ('chief_financial_officers', 'NNS'), (',', ','), ('will', 'MD'), ('report', 'VB'), ('directly', 'RB'), ('to', 'TO'), ('the', 'DT'), ('police_officer', 'NN'), ('.', '.')]

I am prepared to accept WordNet as the ground truth as to the existence or not of a phrase.

from nltk.corpus import wordnet as wn
def get_tagged_phrases(tagged_sent, max_phrase_length):

    tagged_phrase_sent = list(tagged_sent)
    for phrase_len in range(max_phrase_length,1,-1): #Go from largest to smallest to keep information
        for indexes in n_wise(phrase_len, range(len(tagged_sent))):
            tagged_words = [tagged_phrase_sent[index] for index in indexes]
            if not(any([tagged_word is None for tagged_word in tagged_words])):
                words, tags = zip(*tagged_words)
                possible_phrase = "_".join(words)
                if wn.synsets(possible_phrase): #If there are any, then it is a phrase
                    for index in indexes:
                        tagged_phrase_sent[index] = None #Blank them out with Nones which we will remove later
                    pos = tags[-1] #Use final tag, it will be the one we need for handling plurals
                    tagged_phrase_sent[indexes[0]] = (possible_phrase, pos)
    return [tagged_phrase for tagged_phrase in tagged_phrase_sent if not tagged_phrase is None]

The obvious code smell is that it is nested about 5 deep.
That is too much state to remember, perhaps.

This is in Python 2

Apart from choosing more optimal functions (xrange, in), this looks okay I think; a bit more nesting can be removed by inverting the conditions and use continue instead; it also looks like the last return statement could be faster if the intermediate results from the inner loops were collected in a separate result, but I may read that wrong.

from nltk.corpus import wordnet as wn

def get_tagged_phrases(tagged_sent, max_phrase_length):
    tagged_sent = list(tagged_sent)

    for phrase_len in xrange(max_phrase_length, 1, -1): #Go from largest to smallest to keep information
        for indexes in n_wise(phrase_len, xrange(len(tagged_sent))):
            tagged_words = [tagged_sent[index] for index in indexes]

            if None in tagged_words:
                continue

            words, tags = zip(*tagged_words)
            possible_phrase = "_".join(words)

            if not wn.synsets(possible_phrase): #If there are any, then it is a phrase
                continue

            for index in indexes:
                tagged_sent[index] = None #Blank them out with Nones which we will remove later

            pos = tags[-1] #Use final tag, it will be the one we need for handling plurals
            tagged_sent[indexes[0]] = (possible_phrase, pos)

    return [tagged_phrase for tagged_phrase in tagged_sent if not tagged_phrase is None]


Making an array whose elements are defined by a struct This might be a basic question for C. I'm making a struct called check_t and I want to make an array whose elements are of type check_t. This array is called enqueued. The struct check_t contains an integer x and a lock (for multi-threading).

typedef struct _check_t{
  int x;
  pthread_mutex_t lock;
} check_t;

void *check_init(check_t *c)
  c->x = 0;
  pthread_mutex_init(&c->lock,NULL);
}

check_t **enqueued;
for(i=0;i<w*h;i++){
  enqueued[i] = (check_t *)malloc(sizeof(check_t));
  check_init(&enqueued[i]);
}

Mostly, I'm wondering if this is the correct way to make/allocate space for an array of check_ts.

1D array:

check_t *enqueued = malloc(N * sizeof(*enqueued));
enqueued[0].x = 5;
enqueued[N - 1].x = 2;

2D array:

check_t **enqueued = malloc(N * sizeof(*enqueued));
for(int i = 0; i < N; i++)
    enqueued[i] = malloc(M * sizeof(**enqueued));
enqueued[0][0].x = 5;
enqueued[N - 1][M - 1].x = 2;


Combine and minimize all .js files in parent folder I'd appreciate some feedback on my latest PHP script. It is supposed to work like this:

When obtained, it checks whether the cache is still up-to-date
IF YES, return the cache; IF NOT, reset the cache
Get all JS scripts in the parent directory
Minimize the code
Add it to the cache
Return the cache

// Script combines & minimizes all .js files in the parent folder
// Result is cached until a change to the files is dealt

header('Content-type: application/x-javascript');

$cache_path = 'cache.txt';
$index_path = 'cache-index.txt';

function getScriptsInDirectory(){
    $array = Array();
    $scripts_in_directory = scandir('.');
    foreach ($scripts_in_directory as $script_name) {
        if (preg_match('/(.+)\.js/', $script_name))
        {
            array_push($array, $script_name);
        }
    }
    return $array;
}

function compilingRequired(){
    global $cache_path;
    global $index_path;
    if (file_exists($cache_path) && file_exists($index_path))
    {
        $cache_time = filemtime($cache_path);
        $files = getScriptsInDirectory();
        foreach ($files as $script_name) {
            if(filemtime($script_name) > $cache_time)
            {
                return true;
            }
        }

        $array = explode(PHP_EOL, file_get_contents($index_path));
        foreach($array as $name)
        {
            if (!file_exists($name))
            {
                return true;
            }
        }

        return false;
    }
    return true;
}

function compressScript($buffer) {
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    $buffer = str_replace(array("\r\n","\r","\n","\t",'  ','    ','     '), '', $buffer);
    $buffer = preg_replace(array('(( )+{)','({( )+)'), '{', $buffer);
    $buffer = preg_replace(array('(( )+})','(}( )+)','(;( )*})'), '}', $buffer);
    $buffer = preg_replace(array('(;( )+)','(( )+;)'), ';', $buffer);
    return $buffer;
}

if (compilingRequired())
{
    if (file_exists($cache_path)){
        unlink($cache_path);
        unlink($index_path);
    }

    $scripts_in_directory = getScriptsInDirectory();
    $file_handler = fopen($cache_path, 'w+');
    $cache_handler = fopen($index_path, 'w+');

    foreach ($scripts_in_directory as $name)
    {
        if (strlen(file_get_contents($cache_path)) > 0){
            fwrite($file_handler, str_repeat(PHP_EOL, 2));
        }

        fwrite($file_handler, '/**** ' . $name . ' ****/' . str_repeat(PHP_EOL, 2));
        fwrite($file_handler, compressScript(file_get_contents($name)));
        fwrite($cache_handler, $name . PHP_EOL);
    }

    echo file_get_contents($cache_path);
}
else
{
    echo file_get_contents($cache_path);
}

This snippet at the end...

if (compilingRequired())
{
    if (file_exists($cache_path)){
        unlink($cache_path);
        unlink($index_path);
    }

    $scripts_in_directory = getScriptsInDirectory();
    $file_handler = fopen($cache_path, 'w+');
    $cache_handler = fopen($index_path, 'w+');

    foreach ($scripts_in_directory as $name)
    {
        if (strlen(file_get_contents($cache_path)) > 0){
            fwrite($file_handler, str_repeat(PHP_EOL, 2));
        }

        fwrite($file_handler, '/**** ' . $name . ' ****/' . str_repeat(PHP_EOL, 2));
        fwrite($file_handler, compressScript(file_get_contents($name)));
        fwrite($cache_handler, $name . PHP_EOL);
    }

    echo file_get_contents($cache_path);
}
else
{
    echo file_get_contents($cache_path);
}

If they both end the same, there's really no need for an else case, you can just put the statement after the if statement.

if (compilingRequired())
{
    if (file_exists($cache_path)){
        unlink($cache_path);
        unlink($index_path);
    }

    $scripts_in_directory = getScriptsInDirectory();
    $file_handler = fopen($cache_path, 'w+');
    $cache_handler = fopen($index_path, 'w+');

    foreach ($scripts_in_directory as $name)
    {
        if (strlen(file_get_contents($cache_path)) > 0){
            fwrite($file_handler, str_repeat(PHP_EOL, 2));
        }

        fwrite($file_handler, '/**** ' . $name . ' ****/' . str_repeat(PHP_EOL, 2));
        fwrite($file_handler, compressScript(file_get_contents($name)));
        fwrite($cache_handler, $name . PHP_EOL);
    }
}
echo file_get_contents($cache_path);

Ideally, though, it'd read something like

if (compilingRequired())
{
    compile();
}
printCompressedFiles();

Because you want to program on the same level of abstraction - high level code is in "programmer english", describing the actions that need to be done (basically that list of 6 steps of yours, maybe compressed a bit). Low level code is pretty much regular code - code actually doing the work.


Plotting a rectangular prism I'm creating a rectangular prism function, whose output looks like this:

I think that this code can be improved by optimizing the use of np.meshgrid with a Python iterator, but I can't wrap my head around it. It might also be possible to do this with fewer plotting calls, but I can't figure that out either. Ideally, I would change the line drawing to use a Line3DCollection and the areas to use a Patch3DCollection for plotting speed, but I'm still not comfortable enough with the 3D api.

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# draw cube
def rect_prism(x_range, y_range, z_range):
    # TODO: refactor this to use an iterator
    xx, yy = np.meshgrid(x_range, y_range)
    ax.plot_wireframe(xx, yy, z_range[0], color="r")
    ax.plot_surface(xx, yy, z_range[0], color="r", alpha=0.2)
    ax.plot_wireframe(xx, yy, z_range[1], color="r")
    ax.plot_surface(xx, yy, z_range[1], color="r", alpha=0.2)

    yy, zz = np.meshgrid(y_range, z_range)
    ax.plot_wireframe(x_range[0], yy, zz, color="r")
    ax.plot_surface(x_range[0], yy, zz, color="r", alpha=0.2)
    ax.plot_wireframe(x_range[1], yy, zz, color="r")
    ax.plot_surface(x_range[1], yy, zz, color="r", alpha=0.2)

    xx, zz = np.meshgrid(x_range, z_range)
    ax.plot_wireframe(xx, y_range[0], zz, color="r")
    ax.plot_surface(xx, y_range[0], zz, color="r", alpha=0.2)
    ax.plot_wireframe(xx, y_range[1], zz, color="r")
    ax.plot_surface(xx, y_range[1], zz, color="r", alpha=0.2)

rect_prism(np.array([-1, 1]), np.array([-1, 1]), np.array([-0.5, 0.5]))
plt.show()

Well, unfortunately you can't get any better than this (as far as I have read). And why would you use an iterator in this case ?

I'd however change a bit of the structure of your code, which allows one to easily change the code if there's any need. I didn't changed too many things, just separated the logic into three different functions and added a for loop to get rid of some repetition in your code.

As for the plotting calls, you kinda' can't change the number of calls. Those are the perks of plotting things (in Python at least).

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

def x_y_edge(x_range, y_range, z_range):
    xx, yy = np.meshgrid(x_range, y_range)

    for value in [0, 1]:
        ax.plot_wireframe(xx, yy, z_range[value], color="r")
        ax.plot_surface(xx, yy, z_range[value], color="r", alpha=0.2)

def y_z_edge(x_range, y_range, z_range):
    yy, zz = np.meshgrid(y_range, z_range)

    for value in [0, 1]:
        ax.plot_wireframe(x_range[value], yy, zz, color="r")
        ax.plot_surface(x_range[value], yy, zz, color="r", alpha=0.2)

def x_z_edge(x_range, y_range, z_range):
    xx, zz = np.meshgrid(x_range, z_range)

    for value in [0, 1]:
        ax.plot_wireframe(xx, y_range[value], zz, color="r")
        ax.plot_surface(xx, y_range[value], zz, color="r", alpha=0.2)

def rect_prism(x_range, y_range, z_range):
    x_y_edge(x_range, y_range, z_range)
    y_z_edge(x_range, y_range, z_range)
    x_z_edge(x_range, y_range, z_range)

def main():
    rect_prism(np.array([-1, 1]),
               np.array([-1, 1]),
               np.array([-0.5, 0.5]))
    plt.show()

if __name__ == '__main__':
    main()

NOTE: I've also added if __name__ == '__main__'. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.


Google Analytics tracking for HTML 5 video player The jQuery code is for html5 video event GA tracking and I want to make it a little bit more shorter and cleaner. The code works: I am getting all the events, but would like to make it more simple.

function videoEnd() {
    console.log("Finished");
    ga('send', 'event', 'Videos', 'Finished', 'omegavideo');
}
$(document).ready(function() {
    var a = 0;
    var b = 0;
    var c = 0;
    var j = 0;

    /* Video Watched */
    $("#videoplayer").bind("timeupdate", function() {
        var currentTime = this.currentTime;
        if (currentTime > 0.25 * (this.duration)) {
            if (i < 1) {
                console.log("watched 25%");
                ga('send', 'event', 'Videos', 'Watched 25%', 'Video     1');
            }
            a = a + 1;
        }
    });

    $("#videoplayer").bind("timeupdate", function() {
        var currentTime = this.currentTime;
        if (currentTime > 0.50 * (this.duration)) {
            if (w < 1) {
                console.log("watched 50%");
                ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
            }
            b = b + 1;
        }
    });

    $("#videoplayer").bind("timeupdate", function() {
        var currentTime = this.currentTime;
        if (currentTime > 0.75 * (this.duration)) {
            if (z < 1) {
                console.log("watched 75%");
                ga('send', 'event', 'Videos', 'Watched 75%', 'Video 1');
            }
            c = c + 1;
        }
    });

    /* Video Finished, Thanks */
    $("#videoplayer").bind("ended", function() {
        if (j < 1) {
            console.log("Finished 100%");
            ga('send', 'event', 'Videos', 'Finished 100%', 'Video 1');
        }
        j = j + 1;
    });

})

I would use a single bind:

$("#videoplayer").bind("timeupdate", function() {
    var currentTime = this.currentTime;
    if (currentTime > 0.75 * (this.duration)) {
        a = a + 1;
        console.log("watched 75%");
        ga('send', 'event', 'Videos', 'Watched 25%', 'Video 1');
    } else if (currentTime > 0.50 * (this.duration)) {
        b = b + 1;
        console.log("watched 50%");
        ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
    } else if (currentTime > 0.25 * (this.duration)) {
        c = c + 1;
        console.log("watched 25%");
        ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
    }
});

Unless there's a specific reason for you not to?


RPG User File (Stats Holder) This is my Player file. It is mainly for saving purposes. Is it easy to understand and read? Anything I should add or change for improvements?

#Programmer: DeliriousSyntax
#Player.py
#Date: November 22, 2015

import math

class User:
    def __init__(self, user, class_type):
        self.user = user
        self.level = 1
        self.xp = 1
        self.Class = class_type
        self.dex_attr = 0
        self.tech_attr = 0
        self.strength_attr = 0
        self.health_attr = 0
        self.energy_attr = 0
        self.boss_kills = 0
        self.ordinary_kills = 0
        self.towns_visited = 0
        self.money_earned = 0
        self.money = 0
        self.black_jack_wins = 0
        self.beers = 0
        self.houses = 0
        self.rent = 0
        self.shops = 0

    @property
    def drinking_class(self):
        if self.beers <= 25:
            return "Teetotaler"
        elif self.beers <= 250 and self.beers > 25:
            return "Light Drinker"
        elif self.beers > 250:
            return "Alcoholic"

    @property
    def health(self):
        return 110 + (self.health_attr * 4)

    @property
    def energy(self):
        return 50 + (self.energy_attr * 4)

    @property
    def strength(self):
        return 15 + self.strength_attr

    @property
    def tech(self):
        return 15 + self.tech_attr

    @property
    def dex(self):
        return 15 + self.dex_attr

    @property
    def lvl_xp(self):
        return int(math.sqrt(float(self.level) * 999) * self.level)

    def update_level(self):
        while self.xp >= self.lvl_xp:
            self.level+=1
            print("Level Up! \nLevel {} reached! {}xp to next level.".format(lvl, lvl_xp))

    def stats(self):
        return('\n\n==============Player Stats===============\n' +
            '|-{:<17}-|-{:^17}-|\n'.format(' Name', self.user)   +
            '|-{:<17}-|-{:^17}-|\n'.format(' Class', self.Class) +
            '|-{:<17}-|-{:^17}-|\n'.format(' Level', self.level) +
            '|-{:<17}-|-{:>8}/{:<8}-|\n'.format(' XP', self.xp, self.lvl_xp)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Boss Kills', self.boss_kills)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Normal Kills', self.ordinary_kills)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Towns Visited', self.towns_visited)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Drinking Class', self.drinking_class)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Gambling Wins', self.black_jack_wins)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Houses', self.houses)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Houses Sold', self.houses)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Rent Collected', self.rent)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Shops', self.shops)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Money', self.money)+
            '|-{:<17}-|-{:^17}-|\n'.format(' Total Money', self.money_earned))

##This is for testing
p = User(' Arse Face', 'Assassin')
def stats():
    Stats = p.stats()
    print(Stats)

You seem to have a lot of counts of things. towns_visited is a good example. This implies to me that in your game, you would have a variety of towns to be visited. Perhaps, having an empty set for which towns you have visited, and instead of towns_visited, just use a count of that set. Every time you visit a town, add it to the set. The same would apply to houses. Every time you buy a house, add the specific house object to a list and that would take care of houses and what you do with them. I'm assuming you know the difference between a list and a set.


Assembly Nasm Bootloader x86 I just started with deep learning of x86 architecture and assembly so i decided to go from bare metal and write my own bootloader. To add some "functionality" i decided to make quine (from binary perspective) and i have some questions:

Could this be considered as valid quine ?
Is mechanic and design of my code acceptable?
Is there some asm patterns that generally should be followed (i come from
Java background where patterns are everywhere)
How to properly format asm code ?

  My code :

start:
mov si, 7F00h   ;; set stack pointer after our bootloader
mov ax, 0h
mov ds, ax      ;; set DS to 0;
mov di, 7C00h   ;; set Data pointer to memory location where is our bootloader loaded

.printMemoryValue:
mov al, 0          ;;  Using int15 to simulate pause for real time output, ax,ah,cx,dx dictate pause length
mov ah, 86h
mov cx, 0006H
mov dx, 8480H
int 15h
mov ah, 0Eh     ;; Ah to 0eh setting for teletype output ( int 10h)
mov dx, [ds:di]     ;; moving content of first memory location in dx (7c00h)
push dx             ;; save dx in our stack
xor  cx, cx        ;; for (int i = 0; ;; for loop used to output 16 bit string (0 & 1)

.loopstart:
cmp  cx, 00010h     ;; i < 16;
je  .loopend    ;; break if i >= 16
pop dx
rol dx, 1           ;; rotating left 1 bit so we can extract MSF bit with our mask. because we write on screen from right to left
push dx             ;; save our curent dx to stack
and dx, 0000000000000001   ;; mask
add dx, 30h         ;; adding (30h) for ASCII ( 0 or 1)
push cx             ;; saving our counter in stack because cx is volotile register
mov al, dl          ;; moving low 8 bits from dx (dl) to our teletype output register Al for calling int 10h
int 10h         ;; int 10h ( al = character to output if ah = 0eH, teletype )
pop cx
add cx, 1       ;; i++
jmp .loopstart

.loopend:
mov al, 000Ah   ;; new Row
int 10h
mov al, 000Dh       ;; carriage return
int 10h
add di, 2h          ;; adding 2 to our di pointer ( because we are in 16bit mode)
cmp di, 7E00h       ;; are we at the end of our bootloader (7c00h + 200h )?
je .hlt             ;; if yes halt
jmp .printMemoryValue   ;; print next memory location ( di is increased by 2 )
.hlt:
hlt             ;; ende

times 510-($-$$) db 0
dw 0xAA55           ; => 0x55 0xAA (little endian byte order)

U can try code with mountable image available here

Any suggestions are welcome.

Since cx is not used other than a loop counter, you may consider making a countdown loop. That would spare 2 instructions:

    move cx, 16
.loopstart:
    pop dx
    ....
    dec cx
    jnz .loopstart

The MSB operations can also be shortened:

    xor al,al    # Clear al
    sal dx,1     # MSB lands in CF
    adc al,30h   # Add with carry. al becomes 30h + MSB

Yet another jump could be spared by jne printMemoryValue.


Function to check if folder path is valid It is a function that validates a string is a correct windows path to a directory.
It returns negative numbers if it isn't, 0 if it is correct and 1 if it also exists:

int path_is_correct_directory (char *path)
{
    size_t  szPath          = 0U;

    if(path == NULL)
        return -1;
    if(*path == '\0')
        return -2;

    szPath = strlen(path);

    if(szPath < 3 || szPath > MAX_PATH)
        return -3;

    char    driveLetter[3]      = { path[0], path[1], '\0' };
    BOOL    validDriveLetter    = PathIsDirectory(driveLetter);

    if(validDriveLetter == 0)
        return -4;

    if(path[2] != '\\')
        return -5;

    int i;
    for(i = 3; i < szPath; i++)
    {
        if(path[i] == '/')  return -6;
        if(path[i] == ':')  return -7;
        if(path[i] == '*')  return -8;
        if(path[i] == '"')  return -9;
        if(path[i] == '<')  return -10;
        if(path[i] == '>')  return -11;
        if(path[i] == '|')  return -12;
        if(path[i] == '?')  return -13;
    }

    if(PathIsDirectory(path))
        return 1;

    return 0;
}

Magic numbers

All error codes are magic numbers. It's hard to keep numbers in mind, though. If I use

path_is_correct_directory(some_path)

and get -6, what exactly did I do wrong? I have to look into the documentation, check the error values and add that to my own code:

if(path_is_correct_directory(some_path) == -6) {
    yell_at_user("Path may not contain slash!");
}

But that's still opaque. Instead, use an enum:

enum RESULTS {
    PATH_IS_VALID     = 0,
    PATH_IS_DIRECTORY = 1,
    /*   ---   */
    PATH_IS_NULL   = -1,
    PATH_IS_EMPTY  = -2,
    PATH_TOO_SHORT = -3,
    /*   ---   */
    INVALID_DRIVE           = -4,
    INVALID_DRIVE_DELIMITER = -5,
    /*   ---   */
    PATH_CONTAINS_SLASH         = -6,
    PATH_CONTAINS_COLON         = -7,
    PATH_CONTAINS_ASTERISK      = -8,
    PATH_CONTAINS_QUOTE         = -9,
    PATH_CONTAINS_LT            = -10,
    PATH_CONTAINS_GT            = -11,
    PATH_CONTAINS_PIPE          = -12,
    PATH_CONTAINS_QUESTION_MARK = -13
};

Instead of magic numbers, I can now confidently compare against a nice name:

if(path_is_correc_directory(some_path) == PATH_IS_DIRECTORY) {
    list_directory_contents(some_path);
}

Keep scope of variables short

Since you use C99, you can keep the scope of your variables shorter. For example i should only be valid in the for loop, but not outside. szPath can get initialized with strlen right away (after the NULL check).

Variables that shouldn't change can be const

All szPath, path driveLetter and validDriveLetter should not change and can therefore get changed to const.

sz is a prefix for strings, not numbers

In Hungarian notation sz is a prefix for "string terminated by zero". Since Hungarian notation is used throughout Windows APIs, that can be a source of confusion. path_size is fine on the other hand.

All at once

int path_is_correct_directory (const char *path)
{
    if(path == NULL)
        return PATH_IS_NULL;
    if(*path == '\0')
        return PATH_IS_EMPTY;

    const size_t path_size = strlen(path);

    if(path_size < 3 || path_size> MAX_PATH)
        return PATH_TOO_SHORT;

    const char    driveLetter[3]      = { path[0], path[1], '\0' };
    const BOOL    validDriveLetter    = PathIsDirectory(driveLetter);

    if(validDriveLetter == 0)
        return INVALID_DRIVE;

    if(path[2] != '\\')
        return INVALID_DRIVE_DELIMITER;

    for(int i = 3; i < path_size; i++)
    {
        if(path[i] == '/')  return PATH_CONTAINS_SLASH;
        if(path[i] == ':')  return PATH_CONTAINS_COLON;
        if(path[i] == '*')  return PATH_CONTAINS_ASTERISK;
        if(path[i] == '"')  return PATH_CONTAINS_QUOTE;
        if(path[i] == '<')  return PATH_CONTAINS_LT;
        if(path[i] == '>')  return PATH_CONTAINS_GT;
        if(path[i] == '|')  return PATH_CONTAINS_PIPE;
        if(path[i] == '?')  return PATH_CONTAINS_QUESTION_MARK;
    }

    if(PathIsDirectory(path))
        return PATH_IS_DIRECTORY;

    return PATH_IS_VALID;
}

By the way, Windows also supports network directories, which start with \\.


One dimension cellular automation in Python Here is my implementation for one dimensional cellular automation in Python. Any suggestions for more efficiency - other strategies?

ncells = ['111','110','101','100','011','010','001','000']

def next_state (state, rule):
    newstate = ''
    binrule = bin(rule)[2:]
    binrule = (8-len(binrule))*'0' + binrule
    for i in range(len(state)):
        cells = state[i-1] + state[i] + state[(i+1)%len(state)]
        newstate += binrule[ncells.index(cells)]
    return newstate

def wolfram (init_state, generations, rule):
    state = init_state
    for i in range(generations):
        yield state
        state = next_state(state, rule)

for i in wolfram('000000000010000000000', 30, 30):
    print i

ncells.index(cells) is linear. You could treat cells as a binary number and use it as an index in a code array. Not sure whether the access in constant time compensates the cost of the conversion with an 8-rule though.


"Remember me" functionality for a website I have read a few SO threads to implement remember_me functionality.

Steps I have followed:

User clicks on login button and if passes client side validation, it goes to php Login page.

First time

 function storeCookie($row,$connection)
 {
        $user_id = $row['UserID'];
        $token = uniqid($user_id,TRUE);
        $salt = md5(mt_rand());
        $cookie_id = hash_hmac('SHA512',$token,$salt);
        $expiry = strval(time() + (7 * 24 * 60 * 60));
        $cookie_name = "GETIN";
        $sql_store_cookie = "INSERT INTO pcookies(cookie_id,user_id,expiry,salt,cookie_name) values('$cookie_id','$user_id','$expiry','$salt','$cookie_name')";
        mysqli_query($connection,$sql_store_cookie) or die(mysqli_error($connection));//die('{"l":"mysqli_error(`$connection`)"}');
        setcookie("GETIN",$token,$expiry);
}

It reads user id from database[already user registered].
Creates a unique id and salt, hashed value. Sets expiration date for 7 days and store it in the database

cookie is [cookie_name=token]

All the times but not the first

Checks for cookie_name in the browser and if it is present reads the corresponding value
Using that name, gets the salt from database
Calculates has and checks with db
If success, go to the home page.

  if(isset($_COOKIE['GETIN']))
  {
    $cookie_name = 'GETIN';
    $salt = getSalt($cookie_name,$connection);
    $cookie_id = getCookieID($cookie_name,$connection);
    echo "      cookieid=".$cookie_id ;
    echo "      salt=".$salt;
    if($cookie_id == (hash_hmac('SHA512',$_COOKIE['GETIN'],$salt)))
    {
        die('{"status":"success"}');
    }
  }

It works fine. My doubts are

Is this method ok or need to modify something or everything. If so, please guide me
I didn't update the salt and hash once user successfully logged in. Do I need to update?
I am doing everything with PHP.

My site doesn't conatain any sensitive data like payments. It's just like tutorial site. Please share your few experiences with this functionality.

 function getSalt($cookie_name,$connection)
 {
    $sql_token_query = "select salt from pcookies where cookie_name = '$cookie_name'";
    $sql_token = mysqli_fetch_array(mysqli_query($connection,$sql_token_query));
    echo "   getSalt=".$sql_token['salt'];
    return $sql_token['salt'];
  }

  function getCookieID($cookie_name,$connection)
  {
    $sql_cookieid_query = "select cookie_id from pcookies where cookie_name = '$cookie_name'";
    $sql_cookieid = mysqli_fetch_array(mysqli_query($connection,$sql_cookieid_query));
    echo "   getCookie=".$sql_cookieid['cookie_id'];
    return $sql_cookieid['cookie_id'];
   }

Performance

As your code is executed on every request, it's best to optimize it. First of all, you perform two queries when one would be enough. You could join your getSalt and getCookieID method to a getSaltAndCookie method which returns both values in an array.

It's not all that clear, but how I understand it, you do not use a session for login check at all. It would be better to add code that handles the normal session checking, and only use the cookie based authentication if no session is set, and then set a session (so All the times but not the first would become Only the first time, and you would not have any queries on subsequent requests).

Security

If UserID is user controller, you have a second order SQL injection in storeCookie. Either way, I would use prepared statements for all variable content just to make sure.

Even if there isn't an injection at the time, I could imagine that you will extend your code in the future. For example, currently, there can only ever be one login cookie, so I'm assuming you only allow one user. But this might change in the future, in which case $cookie_name will not be the static string GETIN, but some kind of identifier send via cookie. These changes would not be made in getSalt and getCookieID, so it would be very easy to forget to secure the queries.

The documentation of uniqid says: Warning: This function does not create random nor unpredictable strings. This function must not be used for security purposes, this is because it's based on the time it is created. It's not so bad because your salt is actually random, but still. If you are afraid of collisions for the token, you could generate a truly random string and prefix it with the username.

Misc

If you store this: 7 * 24 * 60 * 60 in a named variable, it would be immediately obvious that it is 7 days.
use more spaces, eg around . to increase readability.
all your SQL keywords should be all uppercase to increase readability (eg values -> VALUES, and all the keywords in the insert queries).


Abstract Interface for managing Init/Shutdown In a small game project I'm using 'Init' and 'Shutdown' functions on Systems/Managers/Components to make resetting them easier without having to call the constructor/destructor.

For example when reloading a level you can just call Shutdown and Init to reset to the starting state.

A potential problem however I noticed is that I have to be careful when I call Init and Shutdown, and unless I track the init, or 'active', state of the object and explicitly check for it, undefined behavior could creep in. For example, if I ever accidentally shutdown without init first, etc.

If for no reason other than curiosity, I wanted to see if I could make an abstract interface that would make tracking and maintaining the active state easier. It would be included in any class that uses the 'Init' 'Shutdown' format and with minimal other work from the user would help prevent some of the potential issues. Here is the behavior I wanted to achieve:

Calling Init when not active makes the object active
Calling Shutdown when active makes the object inactive
Calling Shutdown when inactive is ignored
Calling Init when already active calls Shutdown, then Init.

The interface I came up with is as follows:

class InitInterface
{
public:
    InitInterface() : IsActive(IsActive_), IsActive_(false) {}

    // 1. If we are not active, set us to active
    // 2. If we are active, run shutdown (virtually)
    void PreInit()
    {
        if(IsActive) this->Shutdown(); // virtual shutdown call
        IsActive_ = true;
    }

    // return value represents if a shutdown is necessary given our current active state.
    // 1. If we are not active then we can't shut down, so return true (skip shutting down in the derived class)
    // 2. If we are active, set us to not active and return false      (we do need to shut down and not skip it in the derived class)
    bool PreShutdown()
    {
        if(!IsActive) return true;
        IsActive_ = false;
        return false;
    }

    // pure virtual functions we need to implement
    virtual void Init()     = 0;
    virtual void Shutdown() = 0;

    const bool &IsActive; // read-only
private:
    bool IsActive_;
};

And to use it the minimum user implementation I've come up with would be:

class B : public A, public InitInterface
{
public:
    // REQUIRED 1: Shutdown in Destructor
    ~B() { Shutdown(); }

    // REQUIRED 2: Implement Init and call PreInit() as first line
    void Init()
    {
        PreInit(); // calls shutdown virtually
        // INIT CODE HERE
    }

    // REQUIRED 3: Implement Shutdown and check if PreShutdown() indicates a shutdown is necessary
    void Shutdown()
    {
        if(PreShutdown()) return;
        // SHUT DOWN CODE HERE
    }
};

Basically when the user writes a class that should support Init/Shutdown, they include it as a base class and must include the three sections marked as REQUIRED.

Here's an example program to test.

My question is, Is there any way to simplify what the user is required to write even further?

For example I initially wanted to virtually call Shutdown in the destructor of InitInterface to eliminate requirement #1, but realized that this wouldn't work since class B would be destructed before InitInterface.

I'm afraid to say I don't like this design. You seem to have put quite a lot of thought into it, but you really don't gain much with it.

This is not an interface in the usual sense: it has state. Interfaces are collections of (usually) pure-virtual functions (with perhaps a non-pure virtual destructor) with no non-static data members. Multiple inheritance is tricky, picking up state from multiple bases just makes it trickier.
Implementing your interface forces every user to add a bunch of boiler-plate code for your design to work. That doesn't scale, leads to copy-pasta bugs (or forgetting to copy/paste bugs).
Your goal: "make resetting [the components] easier". Your interface reads like "provide a way of initializing and shutting down things". Minor semantic nitpick but a reset interface should have only one method: reset. This ties into the next point:
"unless I track the [...] state of the object [...], undefined behavior could creep in." - this is not good C++ design. Your objects should be responsible for their invariants, not some third-party addon to their class structure. Constructors should establish the invariants, destructors should to whatever cleanup is required. In between, i.e. when the object is alive, all its public members should maintain a consistent state. That you're worried about undefined behavior if you call a method "out of sequence" seems to indicate that you're not (sure of) following this rule. If that's the case, then you should fix your classes to follow it rather than try to tack on something artificial from outside, with its accompanying boilerplate.

So if you want to stick with this resetting interface, I'd go with something much simpler:

struct Resetable {
  virtual void reset() = 0;
  /* or, if passing in the "new state of the world" is needed */
  virtual void reset(GameState &) = 0;
};

Your classes must know if they need to release resources or not when reset is called (you can't write a correct destructor if they don't). For some of your classes that reset member will be trivial, for some others it might need to call into several helpers to get the job done - that's fine. Its the class's job to know how it needs to be reset, the public interface shouldn't expose that complexity.

You might also want to take a second look at your class hierarchies and figure out whether this actually should be an independent interface or if reset should be directly in the base class(es).

Or you could drop that interface completely and just use the C++ builtin stuff to create shiny fresh objects and get rid of them: constructors and destructors.

Random thoughts:

Your classes, methods and data members all start with capital letters. That seems a bit strange to me. But if you apply it consistently, well, that's your choice.
Init and Shutdown don't return anything, so the only way for them to signal failure is exceptions (or just terminating the program). That's fine if you use (and handle) exceptions, otherwise you should make them return some sort of status or error code (same for reset if you go that route).
Careful if you run multiple threads, the posted code isn't thread-safe.
const bool &IsActive; seems like a pessimisation to me. I don't think compilers will optimize that reference member out, so you're adding something like a pointer on top of the bool overhead to each and every implementer of the interface. bool isActive() const { return IsActive_; } would almost certainly be inlined and has no per-object overhead.


Basic functions (sum, len, etc.) with recursively-flattened arguments Based on the excellent answers provided for my previous question, I've thoroughly revised my attempt at "deep" versions of all, any, etc. It uses the recommended encapsulated flattening function, and streamlines some unnecessary stuff.

def flatten(*sequence, preserve=False):
    for item in sequence:
        try:
            assert hasattr(item, '__iter__') and not isinstance(item, str)
            if preserve:
                next(iter(item))
        except (AssertionError, StopIteration):
            yield item
        else:
            for i in item:
                yield from flatten(i, preserve=preserve)

def dsum(*args, preserve=False, s=''):
    if any(isinstance(item, str) for item in flatten(args)):
        return s.join(map(str, flatten(args, preserve=preserve)))
    iter_ = flatten(args, preserve=preserve)
    first = next(iter_)
    return sum(iter_, first)

def dlen(*args, preserve=False, s=False):
    return sum(len(arg) if s and isinstance(arg, str) else 1 for arg in flatten(args, preserve=preserve))

The flatten() function is "public" and intended to be accessed from outside the module. It handles an arbitrary number of arguments and generates each non-iterable element (strings are treated as non-iterable). If the keyword argument preserve is set to True, empty iterables are preserved.

I am not aware of any way to use if to test whether a generator/iterable has any items to yield - is there such a way? If not, is my use of assert an acceptable way of turning the if statements into exceptions, or is it better to use if... raise, or something else entirely?

The dsum() function adds together all the items yielded by flatten(). If preserve is True, empty iterables are preserved. If at least one item is a string, everything is converted into a string and joined, connected by the optional s argument. If there are no strings, all items after the first are added onto the first item. If there aren't any strings and there are items that can't be added, the function fails, which I find acceptable.

The dlen() function finds the total length of all the items yielded by flatten(). If preserve is True, empty iterables are preserved and counted as a length of 1. Strings are counted as objects of length 1 unless the optional keyword argument s is True, in which case their actual lengths (number of characters) are counted.

I have removed dany(), dall(), etc. because they were just wrappers around flatten() with zero additional logic.

Test suite (passes):

from deep import *
import datetime as dt

assert dsum([1,2], 3, '1','2','3','456', []) == '123123456'
assert dsum([1,2], 3, '1','2','3','456', [], preserve=True) == '123123456[]'
assert dsum('a', 'b') == 'ab'
assert dsum(1, [2,[3,[4,[5],[]]]]) == 15
# dsum(1, [2,[3,[4,[5],[]]]], preserve=True) # can't sum int with preserved list
assert all(flatten(1, 1, [1, []]))
assert not all(flatten(1, 1, [1, []], preserve=True))
assert all(flatten(1, 1, set()))
assert not all(flatten(1, 1, set(), preserve=True))
assert list(flatten((1, 1, []))) == [1,1]
assert list(flatten((1, 1, []), preserve=True)) == [1,1,[]]
assert dsum(dt.timedelta(3), dt.timedelta(4), s=dt.timedelta()) == dt.timedelta(7)

That is an inappropriate use of an assertion. You should only assert conditions that you know must be true. Furthermore, you must not rely on assertions for correct execution of your program, since assertions can be disabled.

I would also add that I find the execution flow in flatten() difficult to follow.


Creating formatted "[time] [unit] ago" messages from a seconds value I have this function which calculates how many seconds, mins, hours etc ago a specific time string was.
However, the way I have done it consists of a massive if statement block, and it goes through each specific time that it can reach.
Is there a better way of writing this code where it's more efficient and doesn't have a massive if statement block?
define('SECS_IN_MIN', 60);
define('SECS_IN_HR', 3600);
define('SECS_IN_DAY', 86400);
define('SECS_IN_WEEK', 604800);   // 7 days
define('SECS_IN_MONTH', 2592000); // 30 days
define('SECS_IN_YEAR', 31536000); // 365 days

// Determines if a number is a plural
// Input: Takes in a number
// Output: Outputs a string which is either "s", if plural
//         OR "" if not plural
function is_plural($num) {
    if ($num != 1) return "s";
    else return "";
}

// Gets a string line x minutes ago
// Input a date
// Output: a string which matches its time ago
function date_to_str($time) {
    $currTime = time();
    $pastTime = strtotime($time);
    $diff = $currTime - $pastTime;

    // Seconds Ago
    if ($diff < SECS_IN_MIN) {
        $plural = is_plural($diff);
        return "$ans few second$plural ago";

    // Minutes Ago
    } else if($diff < SECS_IN_HR) {
        $ans = floor($diff / SECS_IN_MIN);
        $plural = is_plural($ans);
        return "$ans minute$plural ago";

    // Hours Ago
    } else if ($diff < SECS_IN_DAY) {
        $ans = floor($diff / SECS_IN_HR);
        $plural = is_plural($ans);
        return "$ans hour$plural ago";

    // Days Ago
    } else if ($diff < SECS_IN_WEEK) {
        $ans = floor($diff / SECS_IN_DAY);
        $plural = is_plural($ans);
        return "$ans day$plural ago";

    // Weeks ago
    } else if ($diff < SECS_IN_MONTH) {
        $ans = floor($diff / SECS_IN_WEEK);
        $plural = is_plural($ans);
        return "$ans week$plural ago";

    // Months Ago
    } else if ($diff < SECS_IN_YEAR) {
        $ans = floor($diff / SECS_IN_MONTH);
        $plural = is_plural($ans);
        return "$ans month$plural ago";

    // Years Ago
    } else if ($diff > SECS_IN_YEAR * 10) {
        $ans = floor($diff / SECS_IN_YEAR);
        $plural = is_plural($ans);
        return "$ans year$plural ago";
    }

    return "-1";
}

$time = "2020-08-25 13:02:32"
echo( date_to_str($time) );
// Outputs 4 days ago

First, here is my recommended replacement for your script (inspired by this SO post) and some test cases:
Code: (Demo)
function secondsToTime($seconds) {
    $dtF = new DateTime('@0');
    $dtT = new DateTime("@$seconds");
    $diff = $dtF->diff($dtT);
    $units = [
        'y' => 'year',
        'm' => 'month',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second'
    ];
    foreach ($units as $char => $unit) {
        if ($diff->$char) {
            if ($char === 'd' && $diff->$char >= 7) {
                $diff->$char = floor($diff->$char / 7);
                $unit = 'week';
            }
            return sprintf(
                '%d %s%s ago',
                $diff->$char,
                $unit,
                $diff->$char !== 1 ? 's' : ''
            );
        }
    }
}

$tests = [
    53 =>  53,           // y=0, m=0, d=0,  h=0, i=0,  s=53
    365 => 365,          // y=0, m=0, d=0,  h=0, i=6,  s=5
    7200 => 7200,        // y=0, m=0, d=0,  h=2, i=0,  s=0
    176455 => 176455,    // y=0, m=0, d=2,  h=1, i=0,  s=55
    2002000 => 2002000,  // y=0, m=0, d=23, h=4, i=6,  s=40
    4592000 => 4592000,  // y=0, m=1, d=22, h=3, i=33, s=20
    66536000 => 66536000 // y=2, m=1, d=9,  h=2, i=13, s=20
];

var_export(
    array_map('secondsToTime', $tests)
);

Output:
array (
  53 => '53 seconds ago',
  365 => '6 minutes ago',
  7200 => '2 hours ago',
  176455 => '2 days ago',
  2002000 => '3 weeks ago',
  4592000 => '1 month ago',
  66536000 => '2 years ago',
)

By leveraging the beauty of a PHP DateTime object, you can pick out the largest non-zero unit from the diff() evaluation and do a quick return from the loop/function.  As a bonus, you won't need to worry about daylight savings or leap years or anything -- trust the diff() method.
If you call var_export($diff), you will see that there are additional properties populated, but you only need 6 of them.
I don't think I'd bother with the overhead of a pluralizing function, just write the condition as an inline condition (ternary).
If you want to make $unit a constant, okay, because it won't be mutated.
The only special handling that is necessary is the week calculation because that is not an instantly available property in the object.  Do the simple arithmetic and change the unit to be presented and proceed with returning the desired string.

As for critiquing your code:

$ans is always returned but it is not always declared; I assuming this is a typo that you overlooked.
Your is_plural() condition block is missing its curly braces.
else if as two words in php is a violation of PSR-12 coding standards.  You should form one word as elseif.
I hope that your -1 return is never reached, but if it does then that would suggest that you need to validate your incoming seconds value.


Handling Excel column letter index as struct I've designed a little struct that should help me deal with Excel columns in terms when the letter index is used. The idea is to use the struct implicitly most of the time for iterations over Excel columns etc.

The struct works in the cases i've intended it to. However, on the one hand, I'm not sure if it isn't a little over the top for a struct and i should rather use a class. On the other hand I was a little surprised why the struct did actually work implicitly when combining it with an integer and assigning it to a string value like this

int rowIndex = 1;
ExcelColumn column = 1;
string cellId = column + rowIndex.ToString();

results in the string being assigned to

  A1

So my questions are:

Why is that the case?
Is the struct properly designed for its purpose?

Below is the code for the struct:

public struct ExcelColumn
{
    #region Constants
    private const int MAX_COLUMN_COUNT = 16384;
    #endregion

    #region Fields
    private readonly int _value;
    #endregion

    #region Constructors
    public ExcelColumn(int columnIndex)
    {
        if (columnIndex < 1)
            throw new IndexOutOfRangeException("Index below 1 not allowed.");
        if (columnIndex > MAX_COLUMN_COUNT)
            throw new OverflowException("Max Column number exceeded");

        _value = columnIndex;
    }
    #endregion

    #region Methods
    private string GetValue()
    {
        string value = "";
        int val = _value - 1;
        do
        {
            value = Convert.ToChar(65 + val % 26) + value;
            val = (val - val % 26) / 26 - 1;
        }
        while (val >= 0);
        return value;
    }
    public override string ToString()
    {
        return GetValue();
    }
    #endregion

    #region Operators
    public static ExcelColumn operator +(ExcelColumn x, ExcelColumn y)
    {
        return new ExcelColumn(x._value + y._value);
    }
    public static ExcelColumn operator +(ExcelColumn x, int y)
    {
        return new ExcelColumn(x._value + y);
    }
    public static ExcelColumn operator +(int x, ExcelColumn y)
    {
        return new ExcelColumn(x + y._value);
    }
    public static ExcelColumn operator ++(ExcelColumn x)
    {
        return new ExcelColumn(x._value + 1);
    }

    public static ExcelColumn operator -(ExcelColumn x, ExcelColumn y)
    {
        return new ExcelColumn(x._value - y._value);
    }
    public static ExcelColumn operator -(ExcelColumn x, int y)
    {
        return new ExcelColumn(x._value - y);
    }
    public static ExcelColumn operator -(int x, ExcelColumn y)
    {
        return new ExcelColumn(x - y._value);
    }
    public static ExcelColumn operator --(ExcelColumn x)
    {
        return new ExcelColumn(x._value - 1);
    }

    public static implicit operator ExcelColumn(int x)
    {
        return new ExcelColumn(x);
    }
    public static explicit operator int(ExcelColumn x)
    {
        return x._value;
    }
    #endregion

    #region Properties
    public string Value { get { return GetValue(); } }
    public int Index { get { return _value; } }
    #endregion
}

Why is that the case?

You need to know what the string + operator does under the covers - it calls String.Concat.

So when you do this:

var someString = aString + anObject;

We get this:

var someString = string.Concat(aString, anObject);

Let's look at the IL for your example:

C#

void Main()
{
    int rowIndex = 1;
    ExcelColumn column = new ExcelColumn(1);
    string cellId = column + rowIndex.ToString();
}

IL

IL_0000:  nop
IL_0001:  ldc.i4.1
IL_0002:  stloc.0     // rowIndex
IL_0003:  ldloca.s    01 // column
IL_0005:  ldc.i4.1
IL_0006:  call        UserQuery+ExcelColumn..ctor
IL_000B:  ldloc.1     // column
IL_000C:  box         UserQuery.ExcelColumn
IL_0011:  ldloca.s    00 // rowIndex
IL_0013:  call        System.Int32.ToString
IL_0018:  call        System.String.Concat
IL_001D:  stloc.2     // cellId
IL_001E:  ret

You can see that your ExcelColumn (column) is being boxed to an object and passed to String.Concat.

So your question is really: why does this work?

string cellId = string.Concat(column, rowIndex.ToString());

Answer: because column.ToString() is being called in string.Concat.

Hmmm... I hope that makes sense.

Time to review your code.

Get rid of the regions. They're almost always pointless and you certainly don't need a region around a single constant.

Constants are named PascalCase in C#. MAX_COLUMN_COUNT should be MaxColumnCount.

I think it would be better to store the string representation at creation rather than computing it each time it's needed.

Structs always have a default constructor which means you have a bug.

new ExcelColumn().ToString() // @


Roamfree official website If it is possible, could someone please revise my code to see if any improvements can be made?

  <title>Roamfree - Official Website</title>
  <link rel="stylesheet" href="index.css">

Welcome to the Roamfree Homepage!

About Roamfree

    Roamfree is a small company that wants to be recognised by the internet and we
    decided to make a website to hold ALL our future products, apps and games!
      This is a Prototype website (not even alpha) so I need support from
      the online community so my coding skills will progress further and this company
      will (eventually) grow!

Relyr

Well Relyr is the measuring app that I am currently developing
  and it is optimised for iOS 8 and is targeted at the Iphone 5s (sorry Ipad users)
  and you press Start then you walk with your Iphone with you and afterwards you press
  Stop then using GPS it approximately calculates how far you walked, this is mainly for
  architects and builders but perfectionists can also use it as well :)

Updates

So, my first update for this newly founded company as I am VERY happy to have
 a opportunity to get some of the profits and of course the fans and supporters as well
 and here's to a (hopefully) HUGE future for this company because of the support
 and help from you guys.

Navigation

Where do you want to go?

Home

Shop

News

About

Contact Us

Your HTML seems to be correct, except you do not have a doctype in there, which goes at the top of the document:

Doctype for HTML5:

<!doctype html>

Your CSS has one error:

li {
    float: center;
}

center is not a possible value for float - only left and right are.

Otherwise, your code has no errors according to the official W3C validators:

  HTML Validator
  CSS Validator

Your HTML markup is, however, very difficult to read due to your wild indentation.  For example, you have this:

Your ending </style> tag should have the same level of indentation as the beginning tag, and I was taught to use 4 spaces as the indentation level.  Part of the problem is you are mixing tabs and spaces as your indentation level - only use one.

You also have this:

About Roamfree

        Roamfree is a small company that wants to be recognised by the internet and we
        decided to make a website to hold ALL our future products, apps and games!
        This is a Prototype website (not even alpha) so I need support from
        the online community so my coding skills will progress further and this company
        will (eventually) grow!

Relyr

Well Relyr is the measuring app that I am currently developing
    and it is optimised for iOS 8 and is targeted at the Iphone 5s (sorry Ipad users)
    and you press Start then you walk with your Iphone with you and afterwards you press
    Stop then using GPS it approximately calculates how far you walked, this is mainly for
    architects and builders but perfectionists can also use it as well :)

Again, the indentation is wild.

Your indentation on the CSS is very good.  However, as your webpage grows, you may find it easier to have the CSS in a different file than the HTML and link to it like this:

<link rel="stylesheet" type="text/css" href="Styles.css">

If you have multiple designs for different types of media, such as phones, printers, and regular computers, you can set the media tag like this:

<link rel="stylesheet" type="text/css" href="PrintStyles.css" media="print">


Implementation of exp function in C using Taylor Series expansion I am trying to write code to calcultate ex using:

$$e^x = \sum_{n=0}^\infty \frac{x^n}{n!} = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \cdots $$

This is the code I have, which works for small values of x.
Please do not pay attention to the variable e, specifically to the fact that user enters it.

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

int main(void) {
    double x0,x1,e,x,sum=0.0;
    int n=0;
    scanf("%lf %lf",&x,&e);
    x1=1;
    do{
        sum+=x1;
        x0=x1;
        x1=(x/++n)*x0;
    }
    while(x1/x0>e);

    printf("sum=%lf, \nexp=%lf",sum,exp(x));
    return 0;
}

For input 50 0.00001 number of decimal places for e doesn't matter.
it generates:

sum=5184705528587076239360.000000,
exp=5184705528587072045056.000000

For input 21 0.00000001:

sum=1318815734.483214,
exp=1318815734.483215

The difference only increases as x increases.
I assume that condition is wrong but see no other way of doing it.

Termination condition not correct

To get the precision you request, you should stop the loop when x1 <= e, not when x1 / x0 <= e.  If you do that, you can now get rid of x0 because it no longer serves a purpose.  I adjusted your program to use the new termination condition and it gave me the results I believe you are looking for.  I also renamed e to precision because it was confusing for a variable to be named e when it didn't actually hold the value of the constant \$e\$.

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

int main(void) {
    double x1,precision,x,sum=0.0;
    int n=0;
    scanf("%lf %lf",&x,&precision);

    // Sums: 1 + x + x^2/2! + x^3/3! + x^4/4! + x^5/5! + ...
    //
    // To get an approximation of e^x.
    //
    // Stops when the next term to add becomes smaller than precision.
    x1=1;
    do {
        sum += x1;
        x1  *= (x/++n);
    } while (x1 > precision);

    printf("sum=%lf,\nexp=%lf\n",sum,exp(x));
    return 0;
}


Copy arbitrary number of bits at arbitrary offset from buffer to another buffer I have just written a function copy_lowbits_off to copy any number of bits (not bytes) from a source buffer to a destination buffer. The function also supports arbitrary offset (expressed in bits) in the source and the destination buffer.

Could you have a look at it and let me know if anything can be improved in style, design or best practices? Specifically, I find my code too complicated for what it does and I am rather unhappy by the naming of functions and variables.

I compile in C++11 but I don't use much of the C++ features here.

#define BITMASKU8(x) ((1U << (x)) - 1)
/**
 * Select low_sel bits from src starting from the lower bit and
 * copy the selected bits to dst at offset msb_off, starting from the most
 * significant bit.
 * The caller must ensure that low_sel + msb_off <= 8
 *
 * @param dst: Destination byte
 * @param src: Source byte
 * @param low_sel: Number of low bits to select from src
 * @param msb_off: Offset from msb in dst
 */
void offset_bitcpy(std::uint8_t& dst, const std::uint8_t src,
        std::uint8_t low_sel, std::uint8_t msb_off) {
    const std::uint8_t sel_src = src & BITMASKU8(low_sel);
    std::uint8_t shift = 8 - (msb_off + low_sel);
    const std::uint8_t shift_src = sel_src << shift;
    dst |= shift_src;
}

/**
 * Copy an arbitrary number of *bits* from an arbitrary position (expressed
 * in bits) in the src buffer, to an abitrary position (expressed in *bits*) in
 * the dst buffer.
 * The caller must ensure that dst_offbits < 8 && src_offbits < 8. If you need
 * to have a bit offset > 8, set dst += bit offset / 8 and
 * dst_offbits = bit offset % 8 (respectively for src). low_sel may be >= 8.
 *
 * @param dst: Destination buffer
 * @param src: Source buffer
 * @param low_sel: Number of bits to copy from src to dst
 * @params src_offbits: [0,7] Offset in the first byte of the source buffer
 * @params dst_offbits: [0,7] Offset in the second byte of the destination
 *      buffer
 */
void copy_lowbits_off(std::uint8_t* dst, const std::uint8_t* src,
        unsigned low_sel, std::uint8_t dst_offbits, std::uint8_t src_offbits) {
    while(low_sel != 0) {
        // Number of bits to select from the first byte of src, and write
        // to the first byte of dst
        const std::uint8_t sel_byte  = std::min(low_sel, 8U - dst_offbits);
        const std::uint8_t off_src = *src >> src_offbits;
        offset_bitcpy(*dst, off_src, sel_byte, dst_offbits);
        // Update dst offsets
        const std::uint8_t add_dst_off = sel_byte + dst_offbits;
        dst += add_dst_off / 8;
        dst_offbits = add_dst_off % 8;
        // Update src offsets
        src_offbits += sel_byte;
        src += src_offbits / 8;
        src_offbits = src_offbits % 8;
        low_sel -= sel_byte;
    }
}

I don't know how you could make it shorter or less complicated, hopefully someone else will provide you a few insights on that. I can comment on a few minor points that you might be interested in changing:

BITMASKU8 should preferably be a function. Such a short function would certainly to be inlined by the compiler, producing the same results as the macro you currently have. If you can't afford the chance of overhead, or your compiler is not capable of inlining, then you should at least #undef the macro name at the end of the file to clear the namespace.
In offset_bitcpy(), I see that you've nicely marked the variables that are initialized only once with const, this is a good practice, even for small functions/blocks, you never know how big they might grow in the future, after a few refactorings. But you did forget to mark std::uint8_t shift as const too, since it is never modified after being set.
Decide how you are going to handle invalid inputs. The only thing that can break your code is an ill-formed input in copy_lowbits_off(), such as a null pointer or a zero count. Decide which course of action should be taken in such cases. Just doing nothing is hardly a good choice. At least assert to facilitate debugging, or throw and exception if the caller should be responsible for handling the error.
Overall, I find your code too tightly packed. Blank lines before each comment inside copy_lowbits_off() would visually separate stuff in a more natural way, IMHO.