texts: Chain Responsibility Pattern to filtering messages

texts:
Is this a good implementation of a Chain Responsibility Pattern? This code attempts to filter a message received (for instance, in a chat application).

import urlmarker
import re

bad_words = []
with open("bad-words.txt") as file:
    for entry in file:
        entry = entry.strip()
        bad_words.append(entry)

class Message(object):

    def __init__(self, content):
        self.content = content.split()
        self.can_broadcast = True
        self.construct_word()

    def construct_word(self):
        self.content = ' '.join(self.content)

class Filter():

    def __init__(self, successor = None):
        self.successor = successor

    def has_successor(self):
        if self.successor is not None:
            return True
        return False

    def filter_message(self, message):
        if self.has_successor():
            self.successor.filter_message(message)

class Slang_Filter(Filter):

    def filter_message(self, message):
        has_bad_words = False

        for word in message.content:
                for bad_word in bad_words:
                    if bad_word == word.lower():
                        has_bad_words = True
                        break

        if has_bad_words == False:
            if self.has_successor():
                self.successor.filter_message(message)
        else:
            message.can_broadcast = False

class Website_Filter(Filter):

    def filter_message(self, message):
        has_websites = False

        if re.findall(urlmarker.URL_REGEX, message.content) is None:
            if self.has_successor():
                self.successor.filter_message(message)
        else:
            message.can_broadcast = False

def main():
    new_message = Message("This is full of fucking shit www.google.com")
    slang_filter = Slang_Filter()
    website_filter = Website_Filter(slang_filter)
    website_filter.filter_message(new_message)
    print new_message.can_broadcast

if __name__ == '__main__':
    main()


texts:
I've got an Excel file from which I have to read out data to an object to serialize. So far I came up with this solution, and I'm curious if there are any clearer solutions.

public myClassFromXsd excelToMyClassFromXsd(String excelFile)
            {
                Excel.Application excelApp = new Excel.Application();
                Excel.Workbook workBook = excelApp.Workbooks.Open(excelFile);
                Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets[1];

                myClassFromXsd spec = new myClassFromXsd();
                UserHeader user = new UserHeader();
                ResultHeader header = new ResultHeader();
                anotherClassFromXsd specOp = new anotherClassFromXsd();
                List<anotherClassFromXsd> specOpList = new List<anotherClassFromXsd>();
                thisIsAClassToo tcd = new thisIsAClassToo();

                excelApp.Visible = false;

                tcd.orderNumber = Convert.ToString(workSheet.get_Range("B3").Value);
                switch (((String)workSheet.get_Range("B4").Value).ToUpper())
                {
                    case "I":
                        tcd.typeOfThis = EnumFromXsd.I;
                        break;
                    case "E":
                        tcd.typeOfThis = EnumFromXsd.E;
                        break;
                    case "D":
                        tcd.typeOfThis = EnumFromXsd.D;
                        break;
                    default:
                        break;
                }
                switch (((String)workSheet.get_Range("B5").Value).ToUpper())
                {
                    case "I":
                        tcd.othersCanAlter = true;
                        break;
                    case "N":
                        tcd.othersCanAlter = false;
                        break;
                    default:
                        break;
                }
                tcd.oneProperty = Convert.ToString(workSheet.get_Range("B6").Value);
                tcd.onePropertyText = Convert.ToString(workSheet.get_Range("B7").Value);
                tcd.Name = Convert.ToString(workSheet.get_Range("B10").Value);
                tcd.vatNum = Convert.ToString(workSheet.get_Range("B11").Value);
                tcd.city = Convert.ToString(workSheet.get_Range("B12").Value);

                specOp.index = 1;
                specOp.operation = Operation.create;
                specOp.Item = tcd;
                specOpList.Add(specOp);

                header.requestId = Guid.NewGuid().ToString();
                header.timestamp = DateTime.Now.ToString("yyyy-mm-ddTH:mm:sszzz");

                user.user = "TestUser";
                user.passwordHash = "BA32521232AED23798735C78739273GDHS238238723";

                spec.header = header;
                spec.user = user;
                spec.specOps = specOpList;

                excelApp.Quit();
                return spec;
            }

And the serializer and deserializer methods:

public void serializeXml(myClassFromXsd mcfx)
        {
            using (StreamWriter writer = new StreamWriter("e:\\test.xml", false))
            {

                XmlSerializer serializer = new XmlSerializer(typeof(myClassFromXsd));
                serializer.Serialize(writer, mcfx);
            }
        }

        public myClassFromXsd deserializeXml(String xmlFile)
        {
            myClassFromXsd mcfx = new myClassFromXsd();
            XmlSerializer serializer = new XmlSerializer(typeof(myClassFromXsd));
            StreamReader reader = new StreamReader(xmlFile);
            mcfx = (myClassFromXsd)serializer.Deserialize(reader);
            reader.Close();
            return mcfx;
        }


texts:
I need a hoverable transparent animation for a website, so that it glows when the mouse is over it. I could use two gifs or svgs one on top of another, but (as far as I know) there's no control of the current frame so I tried spritesheets with JavaScript and an if/else inside of every image in order to show the hovered, glowing version or the non-glowing depending on the users's mouse position.

However, there is yet another thing I tried: instead of a single spritesheet, why not cut it and put it all in the same position within a container div? They all start in display:none and they appear at the rate JavaScript tells them to. It works quite nicely. Here is my HTML:

There are many more frames, of course. This is the JavaScript controller (for two frames):

var animation_hovered = false;

animation.onmouseover = function(){animation_hovered = true;}
animation.onmouseout = function(){animation_hovered = false;}

window.setInterval(function(){
  if(animation_hovered == false){
  document.querySelector('#animation img:nth-child(1)').style.display = "initial";
  document.querySelector('#animation img:nth-child(4)').style.display = "none";
  document.querySelector('#animation img:nth-child(3)').style.display = "none";
  }
else{
  document.querySelector('#animation img:nth-child(2)').style.display = "initial";
  document.querySelector('#animation img:nth-child(4)').style.display = "none";
  document.querySelector('#animation img:nth-child(3)').style.display = "none";
  }
window.setTimeout(function(){
  if(animation_hovered == false){
    document.querySelector('#animation img:nth-child(3)').style.display = "initial";
    document.querySelector('#animation img:nth-child(1)').style.display = "none";
    document.querySelector('#animation img:nth-child(2)').style.display = "none";
    }
  else{
    document.querySelector('#animation img:nth-child(4)').style.display = "initial";
    document.querySelector('#animation img:nth-child(1)').style.display = "none";
    document.querySelector('#animation img:nth-child(2)').style.display = "none";
   }
  }, 300);
}, 600);

It seems bulky, but this approach gives you absolute control over your frames and it works nicely. Also, by not using a spritesheet, you can keep your layout pretty simple (or at least a big spritesheet seems to me a bit difficult to hide in my web interface; cut it seems simpler).

Does anyone think I am doing something wrong or could be enhanced in any way?


texts:
Many conditions need to be scanned for the first one that matches a set of tests. If there is a matching condition, that conditions ConfigId should be returned.

I have a way to do the matching of conditions, but there are too many continue statements. Is there a better way to perform these checks?

private Integer match(List<ConfitionEntity> conditions, ActualDto actualDto) {

    if (CollectionUtils.isEmpty(conditions)) {
        return null;
    }
    Integer configId = null;
    for (ConfitionEntity condition : conditions) {
        boolean match = matchState(condition, actualDto);
        if (!match) {
            continue;
        }
        match = matchStatus(condition, actualDto);
        if (!match) {
            continue;
        }
        match = matchType(condition, actualDto);
        if (!match) {
            continue;
        }
        match = matchPre(condition, actualDto);
        if (!match) {
            continue;
        }
        match = matchMobile(condition, actualDto);
        if (!match) {
            continue;
        }
        match = matchAge(condition, actualDto);
        if (!match) {
            continue;
        }
        match = matchNumber(condition, actualDto);
        if (!match) {
            continue;
        }
        match = matchPassed(condition, actualDto);
        if (!match) {
            continue;
        }
        match = matchName(condition, actualDto);
        if (match) {
            configId = condition.getConfigId();
            break;
        }

    }
    return configId;
}


texts:
I have written the following C code to parse a configuration file for settings to my program. I denote comments with a # and blank lines are allowed. e.g.:

# Total bytes per line
TBPL 70

# bar minimum
NUMIN 10.
# bar maximum
NUMAX 30000.

# input filename
LLIST_NAME foo.txt

Is there anything badly wrong here? I'm used to Python so finding this a bit of a chore...

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

#define MAX_CONFIG_VARIABLE_LEN 20
#define CONFIG_LINE_BUFFER_SIZE 100
#define MAX_LLIST_NAME_LEN 256
#define MAX_OUT_NAME_LEN 256

struct config_struct {
    int bytes_per_line;
    char llist_name[MAX_LLIST_NAME_LEN];
    double numin, numax;
} config;

int read_int_from_config_line(char* config_line) {
    char prm_name[MAX_CONFIG_VARIABLE_LEN];
    int val;
    sscanf(config_line, "%s %d\n", prm_name, &val);
    return val;
}
void read_double_from_config_line(char* config_line, double* val) {
    char prm_name[MAX_CONFIG_VARIABLE_LEN];
    sscanf(config_line, "%s %lf\n", prm_name, val);
}
void read_str_from_config_line(char* config_line, char* val) {
    char prm_name[MAX_CONFIG_VARIABLE_LEN];
    sscanf(config_line, "%s %s\n", prm_name, val);
}

void read_config_file(char* config_filename, struct config_struct config) {
    FILE *fp;
    char buf[CONFIG_LINE_BUFFER_SIZE];

    if ((fp=fopen(config_filename, "r")) == NULL) {
        fprintf(stderr, "Failed to open config file %s", config_filename);
        exit(EXIT_FAILURE);
    }
    while(! feof(fp)) {
        fgets(buf, CONFIG_LINE_BUFFER_SIZE, fp);
        if (buf[0] == '#' || strlen(buf) < 4) {
            continue;
        }
        if (strstr(buf, "TBPL ")) {
            config.bytes_per_line = read_int_from_config_line(buf);
        }
        if (strstr(buf, "NUMIN ")) {
            read_double_from_config_line(buf, &config.numin);
        }
        if (strstr(buf, "NUMAX ")) {
            read_double_from_config_line(buf, &config.numax);
        }
        if (strstr(buf, "LLIST_NAME ")) {
            read_str_from_config_line(buf, config.llist_name);
        }
    }
    printf("TBPL = %d\n", config.bytes_per_line);
    printf("NUMIN = %f\nNUMAX = %f\n", config.numin, config.numax);
    printf("LLIST_NAME = %s\n", config.llist_name);
}

int main(int argc, char *argv[]) {
    read_config_file(argv[1], config);
    return EXIT_SUCCESS;
}


texts:
Input is  1,2,3,4,5,6,7,8

  If rotateOrder = 2

  Output should be  7,8,1,2,3,4,5,6

  If rotateOrder = 3

  Output should be  6,7,8,1,2,3,4,5

Here is my program to do it:

int [] unOrderedArr = {1,2,3,4,5,6,7,8};
        int  orderToRotate =2;

       for(int i = 0; i<orderToRotate; i++){

           for(int j = unOrderedArr.length-1; j>0; j--){
               int temp = unOrderedArr[j];
               unOrderedArr[j] = unOrderedArr[j-1];
               unOrderedArr[j-1] = temp;

           }

        }

       for(int j = 0; j<unOrderedArr.length; j++){
         System.out.println("element is " + unOrderedArr[j]);

           }

How can it be optimized?


texts: The right way to get formatted node's body field in Drupal 7

texts:
I am wondering am I doing the right "Drupal" way in getting formatted value of node's body field. Here is my code:

$field = field_get_items('node', $node, 'body');
$body = '';
if (isset($field[0]['value'])) {
  $body = check_markup($field[0]['value'], $field[0]['format']);
}


texts:
There is an e-commerce site that I'm working on that has thousands of pages in it (mostly product pages). I've got some jQuery that I'm running on about 1300 of these products. Only specific products need the code to run so what I've done is set up the product codes (which display in the URL of the product) in a JSON data sheet and I'm looping through the JSON data like this:

$(document).ready(function(){

$.getJSON('js/round.js', function(data) {

    var location_var = "location.pathname.indexOf('/product-p/main-product.htm')"

    for(i=0; i<data.records.length-1; i++){
        var location_var = location_var + " || location.pathname.indexOf('" + data.records[i].productcode + "')";
    }

    if (location_var != -1){
        //DO SOMETHING TO THESE SPECIFIC PAGES
    }

});
});

Now this functions but obviously it has to handle the 1300 hundred rows, check and then run my code. This causes a slight lag and unfortunately that lag will run on all of the pages because it has to determine if the page is correct for every page that it goes through.

This is the only way I could think of doing this (my Javascript is a bit limited at this point) so I'm curious if anybody knows of a way to do this more efficiently and to make the query faster.

Thanks for your help!


texts: Firebase many to many relationship structure

texts:
I'm trying to create a logical and scalable many to many relationship data structure in Firebase. A user can authenticate with Facebook/Google, upload 3 photos, and a video. Users can also "star" another user's profile.

I've created the following JSON schema, but I'm struggling with keeping flexibility with photos and videos associated with a user's profile. I'm trying not to nest too much. Does the following seem over-coupled?

{
  "users": {
    "fb_id": "{{objectId()}}",
    "name": "{{firstName()}} {{surname()}}",
    "updated_at": "{{date()}}",
    "picture": "http://lorempixel.com/32/32/",

    "car_profiles": {
      "car_profile_1": true
    },

    "car_photos": {
      "car_photos_1": true
    },

    "car_videos": {
      "car_videos": true
    },

    "uid": "user-guid"
  },

  "likes": {
    "car_profile_1": {
      "count": "{{integer(0, 1540)}}",
      "users": {
        "user-guid": "{{date()}}"
      }
    }
  },

  "car_profiles": {
    "car_profile_1": {
      "user": {
        "name": "{{firstName()}} {{surname()}}",
        "picture": "http://lorempixel.com/32/32/",
        "timestamp": "{{date()}}"
      },
      "title": "{{lorem(1, "words")}}",
      "flags": 0,
      "removed": "{{random(true, false)}}",
      "car_specs": {
        year: "1975",
        make: "ford",
        model: "mustang",
        engine: "hemi",
        horsePower: "a lot",
        supercharged: '{{random("yes", "no")}}',
        "description": 'repeat(5)': '{{lorem(1, "paragraphs")}}'
      },
      "tags": []
    }
  },

  "car_photos": {
    "car_photos_1": {
      "user": {
        "name": "{{firstName()}} {{surname()}}",
        "picture": "http://lorempixel.com/32/32/",
        "timestamp": "{{date()}}"
      },
      "photos": [{
        "photo1": "http://lorempixel.com/400/200/",
        "photo2": "http://lorempixel.com/400/200/",
        "photo3": "http://lorempixel.com/400/200/",
      }]
    }
  },

  "car_videos": {
    "car_videos_1": {
      "user": {
        "name": "{{firstName()}} {{surname()}}",
        "picture": "http://lorempixel.com/32/32/",
        "timestamp": "{{date()}}"
      },
      "title": "{{lorem(1, "words")}}}}",
      "videos": ["some-url", "another-url"],
    }
  }

}


texts:
I am a machine learning newbie and recently I implemented (or at least tried to implement) a linear regression model in tensorflow. I would love to know how I can improve my code:

import tensorflow as tf
import numpy as np

# parameters
learning_rate = 0.001
training_epochs = 10000
# training data
train_X = np.linspace(-1, 1, 100)
train_Y = train_X * 3 + np.random.randn(train_X.shape[0]) * 0.5
# create placeholders for X and Y
x = tf.placeholder(tf.float32, name="X")
y = tf.placeholder(tf.float32, name="Y")
# create weight and bias, initialized to 0
W = tf.Variable(0.0, name="weight")
b = tf.Variable(0.0, name="bias")
# linear model
linear_model = W * x + b
# square error as the loss function
loss = tf.square(y - linear_model)
# gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
# global variables initializer
init = tf.global_variables_initializer()
# training the model
with tf.Session() as sess:
    sess.run(init)
    for i in range(training_epochs):
        sess.run(optimizer, feed_dict={x: train_X, y: train_Y})
    W_value, b_value = sess.run([W, b])
    # print the values of w and b
    print(W_value)
print(b_value)

EDIT
And one more thing - if I have more than just one variable, for example two, can I change my code simply in this way?

import tensorflow as tf
import numpy as np

# parameters
learning_rate = 0.001
training_epochs = 10000

# training data
train_X1 = np.linspace(-1, 1, 100)
train_X2 = np.linspace(2, 3, 100)
train_Y = train_X1 * 3 + train_X2* 2 + np.random.randn(train_X1.shape[0]) *
0.5

# create placeholders for X and Y
x1 = tf.placeholder(tf.float32, name = "X1")
x2 = tf.placeholder(tf.float32, name = "X2")
y = tf.placeholder(tf.float32, name = "Y")

# weight and bias, initialized to 0
W1 = tf.Variable(0.0, name = "weight1")
W2 = tf.Variable(0.0, name = "weight2")
b = tf.Variable(0.0, name = "bias")

# linear model
linear_model = W1 * x1 + W2 * x2 + b

# square error as the loss function
loss = tf.square(y - linear_model)

# gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

# global variables initializer
init = tf.global_variables_initializer()

# training the model
with tf.Session() as sess:
    writer = tf.summary.FileWriter("output", sess.graph)
    sess.run(init)
    for i in range(training_epochs):
        for (X1, X2, Y) in zip(train_X1, train_X2, train_Y):
            sess.run(optimizer, feed_dict={x1: X1, x2: X2, y: Y})
    W1_value, W2_value, b_value = sess.run([W1, W2, b])
    writer.close()

# print the values of w and b
print(W1_value)
print(W2_value)
print(b_value)


texts: Filtering visible map layers based on multiple conditions

texts:
I am working on a webapp using OpenLayers. I have written a filter function that I can use to tell whether a given layer is visible.

Since there are a bunch of conditions for a layer to be visible, I condensed them all into a single switch (true) block, and I was wondering if it was a good thing, since:

switch (boolean) has obviously only two branches
I think Java forbids switch (true) so it must be really bad somehow
A case "falling through" is most of the time an error (forgot to break), so as a rule of thumb we forbid such case statements
The language structure whose purpose is conditions is the if statement, which can be made shorter (less bytes of code) than the switch equivalent

But here I wrote a switch (true) version and I think this pattern is powerful since it's really easy to add/remove conditions, keep track of them, describe them, etc. After playing around with this method, I also wrote a version which uses an array of expressions instead of the switch.

So now I have three versions of the method. Which one do you think is the best and why?

/*global map */
// Sample usage
var visibleLayers = map.getLayers().getArray().filter(isVisible);

/*global map */
function isVisible(layer) {
    // Layer is not visible if it is hidden, has no data, or is transparent
    if (!layer || !layer.getVisible() || !layer.getSource() ||
            !layer.getOpacity()) {
        return false;
    }
    // Resolution limits
    var minRes = layer.getMinResolution() || 0;
    var maxRes = layer.getMaxResolution() || Infinity;
    var curRes = map.getView().getResolution();

    // Layer is not visible if the current resolution is too low or high
    if (curRes < minRes || maxRes < curRes) {
        return false;
    }
    // Layer is visible in our app only if its type matches
    if (['WMS', 'Vector'].indexOf(layer.getType()) !== -1) {
        return true;
    }
    return false;
}

/*global map */
function isVisible(layer) {
    if (!layer) {
        return false;
    }
    // Resolution limits
    var minRes = layer.getMinResolution() || 0;
    var maxRes = layer.getMaxResolution() || Infinity;
    var curRes = map.getView().getResolution();

    switch (true) {
    // Layer is hidden when any of these is true:
    case !layer.getVisible():  // - is hidden
    case !layer.getSource():   // - has no data
    case !layer.getOpacity():  // - is completely transparent
    case curRes < minRes:      // - too low resolution
    case maxRes < curRes:      // - too high resolution
        return false;
    // Layer is hidden *in our app* if none of these is true:
    case layer.getType() === 'WMS':
    case layer.getType() === 'Vector':
        return true;
    }
    return false;
}

/*global map */
function isVisible(layer) {
    if (!layer) {
        return false;
    }
    // Resolution limits
    var minRes = layer.getMinResolution() || 0;
    var maxRes = layer.getMaxResolution() || Infinity;
    var curRes = map.getView().getResolution();

    // Layer is hidden when any of these is true:
    var hideOn = [
        !layer.getVisible(),  // - is hidden
        !layer.getSource(),   // - has no data
        !layer.getOpacity(),  // - is completely transparent
        curRes < minRes,      // - too low resolution
        maxRes < curRes,      // - too high resolution
    ];

    // Layer type must match
    var typeMatch = ['WMS', 'Vector'].indexOf(layer.getType()) !== -1;

    return typeMatch && !hideOn.some(Boolean);
}

(PS: layer.getType() is not an OpenLayers method.)


texts: Compressing and encrypting file systems for backups

texts:
I am currently backing up remote OS' while preserving the permissions using rsync:

rsync -aAX --numeric-ids --delete ... root@X.X.X.X:/ /backup/server/

Now I want to backup the backup to a third party. I currently have:

tar --xattrs -czpf - "/backup/server/" | openssl enc -aes-256-cbc -a -salt -pass pass:"$KEY" -out "/backup/server.encr"

Which will compress and encrypt while preserving permissions.

I would eventually like to write this in Go but it seems a bit complicated the preserving of permissions are there some alternative all in one libraries to do this?


texts: Haskell MultiWayIf extension: When is it considered useful syntactic sugar?

texts:
The new MultiWayIf extension (available with GHC 7.6) allows guard syntax in an if:

{-# LANGUAGE MultiWayIf #-}
fn :: Int -> String
fn x y = if | x == 1    -> "a"
            | y <  2    -> "b"
            | otherwise -> "c"

But I don't find it better than the old way:

fn :: Int -> String
fn x y | x == 1    = "a"
       | y <  2    = "b"
       | otherwise = "c"

Has it sense in other cases?


texts:
I'm working on a program to handle simplifying square roots (radicals). My biggest issue is, in order to stay precise, I can't have input any longer than 15 digits. Whenever a number is longer than 15 digits, it loses precision when converted to double when I try to determine if the square is actually a factor. I realize I can just use an int and call it a day, but I'd really like to be able to use bigger numbers. Is there a better way I can do this to handle numbers longer than 15 digits? Also, any other optimization or readability ideas would be greatly appreciated! This is the best algorithm I could come up with for finding square roots.

import java.util.Scanner;

public class SimpRad
{
    public static final String SQUARE_ROOT_SYMBOL = "\u221A";
    public static final int INPUT_FAILURE = -1;

    static long[] simplify( long square )
    {
        double outside = 1;
        double inside = square;
        long[] simplified = { 1, square };

        // Check if it's already a perfect square
        outside = Math.sqrt(square);
        if (outside == Math.floor(outside))
        {
            simplified[0] = (long)outside;
            simplified[1] = 1;
            return simplified;
        }

        // Find all the squares that could be factors and see if they are
        for (long factor = 2, sqr = 4; sqr <= (square / 2); factor++, sqr = (factor * factor))
        {
            // Is this square a factor?
            double in = (double)square / sqr;
            if (in == Math.floor(in))
            {
                simplified[0] = factor;
                simplified[1] = (long)in;
            }
        }

        // Otherwise, since it hasn't simplified, return the original radical
        return simplified;
    }

    public static String display( long radicand, long multiplier, long newRad, boolean negative )
    {
        String i = negative ? "i" : "";
        String negativeStr = negative ? "-" : "";

        // If it's already simplified
        if (multiplier == 1)
        {
            return (SQUARE_ROOT_SYMBOL + negativeStr + radicand + " = " + i
                        + SQUARE_ROOT_SYMBOL + newRad);
        }
        // If it's a perfect square
        else if (newRad == 1)
        {
            return (SQUARE_ROOT_SYMBOL + negativeStr + radicand + " = " + multiplier + i);
        }
        else
        {
            return (SQUARE_ROOT_SYMBOL + negativeStr + radicand + " = " + multiplier + i
                        + SQUARE_ROOT_SYMBOL + newRad);
        }
    }

    public static void main( String[] args )
    {
        Scanner userInput = new Scanner(System.in);
        long radicand;
        long[] rads;
        String radStr;
        boolean isNegative = false;

        do
        {
            System.out.print("Please enter the current radicand:  ");
            radStr = userInput.next();

            try {
                radicand = Long.parseLong(radStr);
            } catch (NumberFormatException e) {
                System.out.print("That's not an integer! ");
                radicand = INPUT_FAILURE;
                continue;
            }

            if (radicand < 0)
            {
                radicand = -radicand;
                isNegative = true;
            }

            if (radicand > 999999999999999l)
            {
                System.out.print("Please enter a radicand that is 15 digits or less. ");
                radicand = INPUT_FAILURE;
            }
        } while (radicand < 0);

        rads = simplify(radicand);
        System.out.println(display(radicand, rads[0], rads[1], isNegative));
    }
}


texts: Solving for the zero of an arbitrary function

texts:
This methods solves for the zero of an arbitrary function using the Bisection Method. It works as desired, but I want to know if the code can be improved or made more readable and if I'm properly dealing with the various error conditions that might arise.

/// <summary>
/// Finds the input value of a function such that the output is zero within the range of min and max
/// </summary>
/// <param name="function">The function to zero</param>
/// <param name="min">The lower bound of the "zero search"</param>
/// <param name="max">The upper bound of the "zero search"</param>
/// <param name="counter">The amount of iterations to convergence</param>
/// <param name="eps">Desired precision</param>
/// <returns>An input value such that 'function' returns 0 zero within the desired precision eps</returns>
public static double Zero(this Func<double, double> function, double min, double max, out int counter, double eps = .001) {
    double lowerBound = min,
        upperBound = max;
    counter = 0;
    double range = double.MaxValue;
    double tryIndex = double.MinValue;
    double tryEval = double.MinValue;
    while (Math.Abs(tryEval) > eps && counter < 10000) {
        counter++;
        range = upperBound - lowerBound;
        double maxEval = function(upperBound);
        double minEval = function(lowerBound);
        bool signMax = (maxEval > 0);
        bool signMin = (minEval > 0);
        if (signMax == signMin) {
            throw new Exception("Failed to converge");
        }
        tryIndex = lowerBound + (range / 2);
        tryEval = function(tryIndex);
        bool trySign = tryEval > 0;
        if (trySign == signMax) {
            upperBound = tryIndex;
        } else lowerBound = tryIndex;
    }
    return tryIndex;
}


texts:
The task is to create a website which allows the admin to create classes, students and teachers. He/She should be able to assign students to classes and one teacher. The admin should also be able to register students attendance using a register. Classes should have specified dates as to when they are running.

The teachers that have been provided a login should be able to login, see the classes assigned to them and take the register. Any feedback would be appreciated!

CREATE TABLE IF NOT EXISTS admin_login (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_name VARCHAR(20) NOT NULL,
    password VARCHAR(40) NOT NULL
);

INSERT INTO admin_login (user_name, password) VALUES
('admin', SHA1('password')) ;

CREATE TABLE IF NOT EXISTS classes (
    class_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    class_name VARCHAR(30) NOT NULL,
    subject_name VARCHAR(30) NOT NULL,
    meeting_dates VARCHAR(900) NOT NULL,
    student_ids VARCHAR(900) NOT NULL,
    teacher_id VARCHAR(50) NOT NULL,
    completed BOOL,
    FOREIGN KEY (teacher_id)
        REFERENCES teachers (teacher_id)
);

CREATE TABLE IF NOT EXISTS students (
    student_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    first_name CHAR(30) NOT NULL,
    last_name CHAR(30) NOT NULL,
    profile_picture LONGBLOB NOT NULL
);

CREATE TABLE IF NOT EXISTS teachers (
    teacher_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    first_name CHAR(30) NOT NULL,
    last_name CHAR(30) NOT NULL,
    profile_picture LONGBLOB NOT NULL,
    username VARCHAR(20) NOT NULL,
    password VARCHAR(40) NOT NULL
);

CREATE TABLE IF NOT EXISTS attendance (
    id INT PRIMARY KEY AUTO_INCREMENT,
    student_id INT REFERENCES students (student_id),
    class_id INT,
    attendence_outcome CHAR,
    date CHAR
);


texts: Make sequential fadeIn() promises more manageable

texts:
I've two versions of promise code. The page is a simple one - an unordered list with a few items. I am trying to make the items show up (fadeIn) one-after-another sequentially. This exercise is done to sort of explain people what promises are...

Version 1:

$('li').hide();

var fadeInFunc = function (obj) {
    var deferred = $.Deferred();
    obj.fadeIn('slow', function () {
        deferred.resolve();
    });
    return deferred.promise();
};

var funcWrapper = function (obj) {
    return function(){
        return fadeInFunc(obj);
    };
};

$('input').click(function () {
    fadeInFunc($('#li1'))
        .then(funcWrapper($('#li2')))
        .then(funcWrapper($('#li3')));
});

Version 2:

$('li').hide();

var fadeInFunc = function (obj) {
    var deferred = $.Deferred();
    obj.fadeIn('slow', function () {
        deferred.resolve();
    });
    return deferred;
};

var execute = function () {
    return fadeInFunc(this);
};

$('input').click(function () {
    fadeInFunc($('#li1'))
        .then(execute.bind($('#li2')))
        .then(execute.bind($('#li3')));
});

Both work fine. However, I want someone to dive in and try to understand the code better. Moreover, this code becomes unmanageable when you have variable number of li elements.

Here is the version for variable number of li elements:

var liCount = Math.floor(Math.random() * 6) + 1;
$('p').html('liCount: ' + liCount);
var ul = $('ul');
for(var i = 0; i< liCount; i++){
    ul.append('
Item ' + (i+1) + '
');
}
var liArray = $('li').hide();

var fadeInFunc = function (obj) {
    var deferred = $.Deferred();
    obj.fadeIn('slow', function () {
        deferred.resolve();
    });
    return deferred;
};

var funcWrapper = function(o){
    return function() { return fadeInFunc(o); };
};

$('input').click(function () {
    var prev;
    liArray.each(function(idx, obj){
        var o = $(obj);
        if(idx === 0){
            prev = fadeInFunc(o);
        }
        else{
            prev = prev.then(funcWrapper(o));
        }
    });
});


texts: Maximize a traveling employee's vacation over k weeks

texts:
I have following problem statement

A lazy employee works at a multi-national corporation with N offices
spread across the globe.
They want to work as few days over k weeks as possible.
Their company will pay for them to fly up to once per week (on
weekends) to a remote office with a direct flight from their current
office.  Once in an office, they must stay there until the end of the
week.
If an office observes a holiday while the employee is working there,
they get that day off.
Find the path that maximizes the employee's vacation over k weeks.
Assume they start at a home office H on a weekend (so in the first
week, they can be in any office connected to the home office).
For example:
H<--->A (It means there is a flight path from H to A and vice versa)
H<--->B

Here is my solution in Python.
vacation = [
{"H": 1, "A": 0, "B": 2},  # week 1
{"H": 0, "A": 2, "B": 0}
]

flights = [("H", "A"), ("H", "B")]

def get_optimal_path():
    all_possible_paths = []

    for offices in list(itertools.product(*vacation)):
        total_cost = 0
        week_level = 0
        for office in offices:
            vac_level = vacation[week_level]
            total_cost += vac_level[office]
            week_level += 1
        if checkIfValidPath(offices[0], offices[1]):
            all_possible_paths.append((offices, total_cost))

    print(max(all_possible_paths, key=lambda x: x[1]))

def checkIfValidPath(source, destination):
    return any(i for i in flights if i[0] == source and i[1] == destination
or i[0] == destination and i[1] == source)

get_optimal_path()

In this example best answer is for the employee to stay at office H in the first week and then move to office A in the second week so the total vacation days will be (1+2)=3. B and A cannot be the answer here because there is no path between them.
How can I optimize this code to increase its efficiency? Right now its complexity is nk (since we have k weeks).


texts: Fetching of JSON data through an API with AngularJS

texts:
I have been trying out AngularJS and developing a mobile application to test out its features and I wanted to see if I could somehow refactor to make my JSON response hopefully quicker in fetching the data. At the moment I have a search functionality that can display from 10 to 30.000 results and usually the application takes over 2 minutes to fetch large amount of results (which is way slower than I hoped for).

I think the reason might lie somewhere where I have the for loop because I am declaring variables inside it which is probably not a good habit but I can't seem to figure out a way to remove the variables out of the loop without breaking the app.

Here is the function fetch() to get the JSON data:

function fetch(){
$http.get("http://www.APIcall.com/phrase=" + $scope.search + "&perpage=25000")
.success(function(response){
$scope.songs = [];
$scope.details = response;

for(var i=0; i < response.tracks.length; i++){

  var labelName = response.tracks[i].label_fk;
  var labelLow = labelName.toLowerCase();
  var resultUrl = "http://APIcall.com/stream_music_file.php?lbl="+labelLow+"&alb="+response.tracks[i].album_num+"&trk="+response.tracks[i].track_num+"";
  var imgUrl = "http://www.APIcall.com/online/music/display_album_cover/"+labelLow+"/"+response.tracks[i].album_num+"";

  var allTracks = {
    id: response.tracks[i].track_id,
    lbl_fk: response.tracks[i].label_fk,
    alb_num: response.tracks[i].album_num,
    track_num: response.tracks[i].track_num,
    track_descr: response.tracks[i].description,
    track_dur: response.tracks[i].duration,
    title: response.tracks[i].primary_title,
    artist: response.tracks[i].composers,
    img: imgUrl,
    url: resultUrl
  };

  $scope.songs.push(allTracks);
  }
  });
}

I'm pretty sure this code could be cleaned up better but I would really hope that also it might somehow be faster in fetching the data with some modifications to it.


texts: LeetCode: Greatest Common Divisor of Strings C#

texts:
https://leetcode.com/problems/greatest-common-divisor-of-strings/

  For strings S and T, we say "T divides S" if and only if S = T + ... +
  T  (T concatenated with itself 1 or more times)

  Return the largest string X such that X divides str1 and X divides
  str2.

Example 1:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:

Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:

Input: str1 = "LEET", str2 = "CODE"
Output: ""

Note:

1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] and str2[i] are English uppercase letters.

I had 30 minutes to solve this.
please review this as a real interview.

what is a red flag, remember code will not be prefect.

using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace StringQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/greatest-common-divisor-of-strings/
    /// </summary>
    [TestClass]
    public class GreatestCommonDivisorOfStringsTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            string str1 = "ABABAB";
            string str2 = "ABAB";
            string res = GCDOfStringsclass.GcdOfStrings(str1, str2);
            Assert.AreEqual("AB", res);
        }

        [TestMethod]
        public void TestMethod2()
        {
            string str1 = "ABCDEF";
            string str2 = "ABC";
            string res = GCDOfStringsclass.GcdOfStrings(str1, str2);
            Assert.AreEqual(string.Empty, res);
        }
    }

    public class GCDOfStringsclass
    {
        public static string GcdOfStrings(string str1, string str2)
        {
            int min = Math.Min(str1.Length, str2.Length);

            StringBuilder build = new StringBuilder();
            //build largest prefix
            for (int i = 0; i < min; i++)
            {
                if (str1[i] != str2[i])
                {
                    break;
                }

                build.Append(str1[i]);
            }

            // no common prefix
            string prefix = build.ToString();
            if (prefix.Length == 0)
            {
                return string.Empty;
            }

            while (str1.Length % prefix.Length != 0 || str2.Length % prefix.Length != 0)
            {
                prefix = prefix.Remove(prefix.Length - 1);
                if (prefix.Length == 0)
                {
                    return string.Empty;
                }
            }

            for (int i = 0; i < str1.Length / prefix.Length; i++)
            {
                for (int j = 0; j < prefix.Length; j++)
                {
                    if (str1[j + prefix.Length * i] != prefix[j])
                    {
                        return string.Empty;
                    }
                }
            }

            for (int i = 0; i < str2.Length / prefix.Length; i++)
            {
                for (int j = 0; j < prefix.Length; j++)
                {
                    if (str2[j + prefix.Length * i] != prefix[j])
                    {
                        return string.Empty;
                    }
                }
            }

            return prefix;
        }
    }
}


texts:
I created this simple one line calculator for two numbers only where user can input any two numbers and and operator in between

for example 20+45 and computer will return result of 65.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace SimpleCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            ShowOutput();
            string user_input = UserInput();
            int result = PerformCalculation(InputToList(user_input));
            Console.WriteLine($"{user_input}={result}");
            Console.Read();
        }

        static void ShowOutput()
        {
            Console.WriteLine("Enter numbers followed by operation eg. 1+2-4");
        }

        static string UserInput()
        {
            string User_input = Console.ReadLine();
            return User_input;
        }

        static string[] InputToList(string input)
        {
            string number1 = "";
            string number2 = "";
            string Oprt = ""; //Mathematical operator
            string[] Arithmetic = new string[3];
            int n = 0;
            foreach (char charecter in input)
            {
                int num;
                bool isNumerical = int.TryParse(charecter.ToString(), out num);
                n += 1;
                if (isNumerical)
                {
                    number1 += num;
                }
                else
                {
                    Oprt = charecter.ToString();
                    Arithmetic[0] = number1;
                    Arithmetic[1] = Oprt;
                    for(int i = n; i <= input.Length - 1; i++)
                    {
                        number2 += input[i];
                    }
                    Arithmetic[2] = number2;
                }

            }
            return Arithmetic;
        }

        static int PerformCalculation(string[] Input)
        {
            int result = 0;
            switch (Input[1])
            {
                case "+":
                    result = Int32.Parse(Input[0]) + Int32.Parse(Input[2]);
                    break;
                case "-":
                    result = Int32.Parse(Input[0]) - Int32.Parse(Input[2]);
                    break;
                case "*":
                    result = Int32.Parse(Input[0]) * Int32.Parse(Input[2]);
                    break;
                case "/":
                    result = Int32.Parse(Input[0]) / Int32.Parse(Input[2]);
                    break;
            }
            return result;
        }
    }
}


texts:
Should I be using std::move or copy when passing LNode in the LinkedList constructor instead of passing by reference?

template <typename T>
struct LNode {
    T data;
    shared_ptr<LNode<T>> next;
    LNode(T p_data) : data(p_data) {}
    LNode() {}
};

template <typename T>
class LinkedList {
public:

    LinkedList(LNode<T>& node) {
        root = make_shared<LNode<T>>(node);
    }

    LinkedList() {}

    void createAndLinkNodes(vector<T>& elements) {

        shared_ptr<LNode<T>> ptr = root;
        for (auto&& elem : elements) {
            shared_ptr<LNode<T>> node = make_shared<LNode<T>>(elem);
            ptr->next = node;
            ptr = ptr->next;
        }

    }

    void mergeList(LinkedList<T>& list2)
    {
        auto ptr1 = root;
        auto ptr2 = list2.root;
        shared_ptr<LNode<T>> ptr3 = make_shared<LNode<T>>();
        auto tail = ptr3;

        while (ptr1!= nullptr && ptr2 != nullptr)
        {
            if(ptr1->data < ptr2->data) {
             appendNode(ptr1,tail);
            }
            else
            {
                appendNode(ptr2,tail);
            }
        }

        tail->next = ptr1 ? ptr1 : ptr2;
        root = ptr3->next;
    }

    void print() {
        shared_ptr<LNode<T>> ptr = root;
        while (ptr != nullptr)
        {
            cout << ptr->data << " ";
            ptr = ptr->next;
        }
        cout << endl;
    }

private:
    void appendNode(shared_ptr<LNode<T>> &node, shared_ptr<LNode<T>> &tail)
    {
        tail->next = node;
        tail = tail->next;
        node = node->next;
    }

private:
    shared_ptr<LNode<T>> root;
};

int main(int argc, char **argv)
{
    cout << "MERGE SORTED LINKED LISTS" << endl;
    LNode<int> r1(2);
    LNode<int> r2(3);

    LinkedList<int> list1(r1);
    LinkedList<int> list2(r2);

    vector<int> elements1 = {5,7};
    vector<int> elements2 = {11};

    list1.createAndLinkNodes(elements1);
    list2.createAndLinkNodes(elements2);

    list1.print();
    list2.print();

    list1.mergeList(list2);
    list1.print();

    return 0;
}


texts: SQL query where id=… or id=… or id=… etc

texts:
I haven't had much experience with postgresql (none) and I am wondering/hoping that there is a better way for me to do this query.

SELECT * FROM member_copy WHERE id = 17579 OR id = 17580 OR id = 17582 ect.

There are about 800 where clauses in total so this will take a while and I need to run it on a fairly regular basis.


texts: Parsing a C++ function declaration with Perl 6 grammar

texts:
I wrote a Perl 6 grammar to parse a C++ function. My final goal would be to parse an entire header. The aim is not to correct C++ syntax errors, but to parse valid C++.

Do you have some advice or improvements?

#!/usr/bin/env perl6

grammar FUNCTION {
    token TOP       { [ <attr> \s+ ]? <type> [ \s* <type_mod> ]?
                        (\s+) <fname> (\s*) "("
                        (\s*) [<parameter> [ "," (\s*) <parameter> ]* ]? (\s*)
                        ')'(\s*) ';'
                    }

    token name      { \w+ }
    token namespace { [ "::" ]? [ <name> "::" ]* }
    token attr      { <name>  }
    token type      {  <namespace>? <name> }
    token type_mod  { [ \*|\& ]+ }
    token fname     { <name> }
    token variable  { <name> }
    token parameter { <type> [\s* <type_mod> ]? \s+ <variable> }
}

my $str = "const ::one::std::string ** ma1n( int&& i, two::std::string va1e_ );";
my $parsed = FUNCTION.parse($str);
say $parsed;


texts:
I've created the following app in Python 3.5. The app uses pyowm and will take a location and return weather information. I've also built a GUI with tkinter for it.

Keen to find out some tips to improve my coding style.

import tkinter as tk
import pyowm
import datetime, time

class WeatherInfo(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.wm_title('Weather')
        self.temp = tk.StringVar(self,value='')
        self.humid = tk.StringVar(self,value='')
        self.status = tk.StringVar(self,value='')
        self.sunrise = tk.StringVar(self,value='')
        self.sunset = tk.StringVar(self,value='')
        self.ld = tk.StringVar(self,value = '')
        self.ln = tk.StringVar(self,value = '')

        self.ask = tk.LabelFrame(self, text ='Location')
        self.ask.pack(fill='both',expand='yes')
        self.kw_label = tk.Label(self.ask, text ='Get weather in:')
        self.kw_label.pack(side = tk.LEFT)
        self.kw = tk.Entry(self.ask)
        self.kw.pack(side = tk.RIGHT)
        self.rb = tk.Button(self, text='Go', command = self.search)
        self.rb.pack()
        self.owm = pyowm.OWM('*CENSORED*')

        self.output = tk.LabelFrame(self, text ='Information')
        self.output.pack(fill='both',expand='yes')
        tk.Label(self.output, textvariable = self.temp).pack()
        tk.Label(self.output, textvariable=self.humid).pack()
        tk.Label(self.output, textvariable=self.status).pack()
        tk.Label(self.output, textvariable=self.sunrise).pack()
        tk.Label(self.output, textvariable=self.sunset).pack()
        tk.Label(self.output, textvariable=self.ld).pack()
        tk.Label(self.output, textvariable=self.ln).pack()
        button = tk.Button(master=self, text='Quit', command=self._quit)
        button.pack(side=tk.BOTTOM)

    def search(self):
        obs = self.owm.weather_at_place(self.kw.get())
        try:
            w = obs.get_weather()
            self.temp.set('Temperature: ' +str(round(w.get_temperature()['temp'] - 273.15,0))+ ' C')
            self.humid.set('Humidity: '+str(w.get_humidity())+ '%')
            self.status.set('Status: ' + w.get_status())
            self.sunrise.set('Sunrise at '+datetime.datetime.fromtimestamp(w.get_sunrise_time()).strftime('%H:%M:%S'))
            self.sunset.set('Sunset at '+datetime.datetime.fromtimestamp(w.get_sunset_time()).strftime('%H:%M:%S'))
            self.ld.set('Day length: '+str(round((w.get_sunset_time() - w.get_sunrise_time()) / 3600,1))+' h')
            self.ln.set('Night length: '+str(round(24 - (w.get_sunset_time() - w.get_sunrise_time()) / 3600,1))+' h')
        except:
            self.temp.set('Pick a city to display weather.')
    def _quit(self):
        self.quit()
        self.destroy()
app = WeatherInfo()
app.mainloop()


texts:
I have made a program to weigh bags of money, and calculate whether too many/little coins are in the bags, and the difference.

bagWeight = 0
totalCoinsAdd = 0
totalCoinsRemoved = 0
totalBagsChecked = 0

def inputs():
    global bagWeight
    global totalCoinsAdd
    global totalCoinsRemoved
    #The above grabs the global variables for use in the function
    bagWeight = int(input("How much does the bag weigh? "))
    denomination = ""
    denom = ['0.01', '0.02', '0.05', '0.10', '0.20', '0.50', '1', '2']
    while denomination not in denom:
        denomination = input("What denomination is the money? £")

    idealWeight = {    '2' : 120,    '1' : 190,    '0.50' : 160,    '0.20' : 250,   '0.10' : 325,    '0.05' : 325,   '0.02' : 356,    '0.01' : 356,    }
    #This dictionary stores the ideal weight of each bag.
    bagCoins = {    '2' : 10,    '1' : 20,    '0.50' : 20,    '0.20' : 50,   '0.10' : 50,    '0.05' : 100,   '0.02' : 50,    '0.01' : 100,    }
    #This dictionary stores how many coins are in each bag.
    coinWeight = {    '2' : 12,   '1' :  9.5,   '0.50' : 8,  '0.20' : 5,   '0.10' :  6.5,  '0.05' : 3.25,'0.02' : 7.12, '0.01' : 3.56, }
    #This dictionary stores how much the 1 of each coin weighs. The values are in grams.
    AddCoins = True     #This defines a variable for whether to add/remove coins.
    differentWeight = idealWeight[denomination] - bagWeight
    #This calculation works out how the difference in weight between the 'ideal' bag weight and the actual bag weight.
    coinInBag = bagWeight/coinWeight[denomination]
    #This calculation works out how many coins are in each bag. It does this by, dividing the bag weight by how much each coin weighs.
    coinChange = bagCoins[denomination] - coinInBag
    #Calculating the amount of coin difference in the bag

    if differentWeight < 0:
        AddCoins = False
        differentWeight = differentWeight  * -1
        coinChange = coinChange * -1

    if AddCoins == True:
        print('The bag is ',str(differentWeight), 'g less than it should be')
        print('Add ', int(coinChange), ' coin(s)')
        totalCoinsAdd = totalCoinsAdd + coinChange

    if AddCoins == False:
        print('The bag is ',str(differentWeight), 'g more than it should be')
        print('Remove ', int(coinChange), ' coin(s)')
        totalCoinsRemoved = totalCoinsRemoved + coinChange

again = 'yes'
while again != 'no':
    inputs()
    totalBagsChecked = totalBagsChecked + 1
    again = input('Would you like to weight another bag? ("no" to quit)')

print('Total coins added: ', int(totalCoinsAdd))
print('Total coins removed: ', int(totalCoinsRemoved))
print('Total bags checked:', int(totalBagsChecked))


texts: Solution to 90 degree rotation of an NxN matrix

texts:
The idea is picked up from here and the following is my PHP implementation of it. As it mentions, 90 degree matrix rotation basically shifts columns into rows. For example:

|1,2,3|     becomes      |7,4,1|
|4,5,6|   ----------->>  |8,5,2|
|7,8,9|                  |9,6,3|

Notice how row 1,2,3, after rotation has become column.The solution is built on this pattern.

Here's the code:

class MatrixRotator
{
    public static function rotate($matrix)
    {
        $result_arr=[];
        for($i=0; $i<count($matrix); $i++)
        {
            $inner_arr = [];
            for($j=0; $j<count($matrix[$i]); $j++)
            {
                $item = $matrix[$j][$i];
                array_unshift($inner_arr, $item);
            }
            array_push($result_arr, $inner_arr);
        }
        return $result_arr;
    }
}

print_r(MatrixRotator::rotate([[1,2,3],[4,5,6],[7,8,9]]));

Here's the output:

|7,4,1|
|8,5,2|
|9,6,3|


texts: Should I treat direct CFC Calls differently than Page Requests?

texts:
Should I leave in <cfif reFindNoCase( "\.cfc$" , targetPage ) eq 0> or not?

Direct CFC calls are flushed when the method returns. Either way, onRequestEnd will stop debug output from being returned for AJAX requests.

Keep If Statement

Additional regular expression search on every AJAX call. Direct CFC calls return quicker. Direct CFC call may not be trimmed.

Remove If Statement (inner code executes for all AJAX requests)

Direct CFC calls' value is stored in a variable. AJAX calls to pages return quicker. All AJAX responses are trimmed.

I'm using ColdFusion 8.

<cfcomponent output=    "false">

<cfset this.name=   "AJAX Debug Output" />

<cffunction name=   "onRequestEnd"
        returnType= "void"
        hint=       "I run on the end of requests (how clever).">

    <cfargument name=   "targetPage"
                hint=   "Path from the web root to the requested page." />

    <cfif isAJAXRequest()>
        <cfsetting  showDebugOutput=    "false"
                    enableCFOutputOnly= "true" />

        <!--- Response from CFC is already flushed to browser. Skip output. --->
        <cfif reFindNoCase( "\.cfc$" , targetPage ) eq 0>

            <!--- If AJAXResponse is not set, then generated content is response. --->
            <cfparam    name=       "request.AJAXResponse"
                        default=    "#getPageContext().getOut().getString()#" />

            <cfcontent  reset= "true" />
            <cfoutput>#trim( request.AJAXResponse )#</cfoutput>
            <cfabort />

        </cfif>

    </cfif>

</cffunction>

<cffunction name=   "isAJAXRequest"
            output= "false"
            access= "private"
            hint=   "I check to see if the request came across with ajax headers">

    <cfif structKeyExists( getHTTPRequestData().headers , "X-Requested-With" )>
        <cfreturn true />

    </cfif>

    <cfreturn false />

</cffunction>

</cfcomponent>


texts: Best way to use an array that is returned from a function immediately in PHP

texts:
I have a function that returns an array and I want to check that a certain value is not set in the array.

function testFunction() {
    return array('key' => 404)
}

if (testFunction()['key'] < 404) {
    // stay calm and carry on
}
else {
    // uh oh
}

I understand that the above will not work in php 5.3 (or anything below), however, I'd like to know what I should do in the above case. That is - what should I call the temporary array I create for the if statement? Or is there another way of dealing with this situation?

The following is what I would roughly do currently:

function testFunction() {
    return array('key' => 404)
}

$test_array = testFunction();

if ($test_array['key'] < 404) {
    // stay calm and carry on
}
else {
    // uh oh
}

Is this an acceptable thing to do?


texts: Comparing two strings to see if string 2 is inside string 1

texts:
Here is what I have to do:

  Write a function scramble(str1,str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

  For example:

  str1 is 'rkqodlw' and str2 is 'world' the output should return true.
  str1 is 'cedewaraaossoqqyt' and str2 is 'codewars' should return true.
  str1 is 'katas' and str2 is 'steak' should return false.

  Only lower case letters will be used (a-z). No punctuation or digits will be included.
  Performance needs to be considered

public class Scramblies {
    public static boolean scramble(String str1, String str2) {
        String temp = str1;
        int count = 0;
        boolean result = true;
        for(int i=0 ; i<str2.length() ; i++){
            char c = str2.charAt(i);
            if(temp.contains(String.valueOf(c))){
                temp = temp.replaceFirst(String.valueOf(c), "");
                count++;
            }
        }
        if (count == str2.length()){
            result = true;
        } else {
            result = false;
        }
        return result;
    }
 }

My code works perfectly, but the only problem now is efficiency. I am tested against how long it takes to finish the final test class, which times out. I get this:

  Process was terminated. It took longer than 10000ms to complete

How can this code be made more efficient to achieve the same result?


texts:
I'm writing a virtual machine in Python using RPython and the PyPy toolchain. The RPython will still work in the ordinary Python 2 interpreter; it's just a bit slow unless it's compiled to C code with PyPy.

Does anyone have any positive or negative feedback about my VM?

The virtual machine has 4 instructions:

EOP - End of Program
EOI - End of Instruction
PUSH - Push item onto stack
PRINT - Print the item at the top of the stack

bcode = []
stack = []
regs = []
sp = 0
bcd = []

'''
Instructions
'''
OP_EOP = 0
OP_EOI = 1
OP_PUSH = 2
OP_PRINT = 3

def load_program(f2o):
    f = open(f2o, "r")
    f2 = f.read()
    f2 = f2.replace("\n"," ")
    bcode = f2.split(" ")
    i = 0
    for item in bcode:
        item = int(item, 16)
        bcd.append(item)
        i += 1
    return bcd

# VM action functions
def do_EOP():
    print "End of Program"

def do_PUSH(ba, b, ip):
    i = 2
    loop = 1
    cb = len(b)

    stack.insert(0, ba)

def do_PRINT(stack):
    stk = stack[0].split(" ")
    for item in stk:
        print unichr(int(item))

def execute_program(b):
    ip = 0
    sp = 0
    loop = 1
    cb = len(b)
    while (loop):
        if ip < cb:
            bc = b[ip]
            if bc == OP_PUSH:
                if bc != OP_EOI:
                    ba = str(b[ip + 1])
                    do_PUSH(ba, b, ip)
            elif bc == OP_PRINT:
                do_PRINT(stack)
            ip += 1
        else:
            loop = 0

def run_program(f):
    b = load_program(f)
    execute_program(b)

def main(argv):
    run_program(argv[1])
    return 0

def target(*args):
    return main, None

if __name__ == '__main__':
    import sys
    main(sys.argv)

Here's a file that includes the bytecode that prints "Hello World!" to the screen:

0002 0048 0001 0003
0002 0065 0001 0003
0002 006C 0001 0003
0002 006C 0001 0003
0002 006F 0001 0003
0002 0020 0001 0003
0002 0057 0001 0003
0002 006F 0001 0003
0002 0072 0001 0003
0002 006C 0001 0003
0002 0064 0001 0003
0002 0021 0001 0003

You can test the VM like this; it's written in Python 2.7:

  python vm.py


texts: Decorator to convert a function's result into the desired units

texts:
I tried to collect some of my formulas inside classes so that I didn't need to browser the names of the functions anymore but only determine which Quantity I want to calculate and then check which methods are avaiable for determining it. This is based on the astropy.units module. Just to make a small example:

import astropy.units as u

class Length(object):
    unit = u.m

    @classmethod
    #@quantitydecorator # I'll explain this later
    def from_velocity_time(cls, velocity, time):
        """
        Calculate length from a given velocity and time.

        Parameters
        ----------
        velocity: `astropy.units.Quantity`
            The velocity of the object.
        time: `astropy.units.Quantity`
            The time the object moved at this velocity

        Returns
        -------
        length: `astropy.units.Quantity`
            The determined length based on velocity * time
        """
        return velocity * time

This works great, I tried:

Length.from_velocity_time(100*u.km/u.h, 100*u.h)
# gives 10000 km

but has some downsides when the units are equivalent but different:

Length.from_velocity_time(100*u.km/u.s, 100*u.h)
# 10000 h*km/s

so I decided to create a general decorator that converts the results unit to the unit defined in the class or have an additional parameter result_unit for every method call:

def quantitydecorator(f):
    """
    Allows for an extra argument "result_unit" for all methods
    and converts the result to the unit specified there or if not
    given to the unit specified in the class.
    """
    @wraps(f)
    def wrapper(*args, **kwds):
        # Check if result_unit is given otherwise use the class default
        # (args[0] is the class)
        if 'result_unit' in kwds:
            result_unit = u.Unit(kwds.pop('result_unit'))
        else:
            result_unit = args[0].unit

        # Calculate the result
        result = f(*args, **kwds)

        # Convert to result unit if the result has a unit
        if not hasattr(result, 'unit'):
            # No unit attribute so we have a plain numpy array
            # or number, only let it pass when target unit is
            # dimensionless
            if args[0].unit != u.dimensionless_unscaled:
                raise ValueError('Got dimensionless quantity but needed'
                        ' quantity with unit: {0}'.format(args[0].unit))
        # Result has a different unit than wanted, convert it to wanted unit
        elif result.unit != result_unit:
            result = result.to(result_unit)
        return result
    return wrapper

This works fine (this time the decorator must be uncommented in the class):

Length.from_velocity_time(100*u.km/u.s, 100*u.h)
# 3.6e10m

Length.from_velocity_time(100*u.km/u.s, 100*u.h, result_unit=u.AU)
# 0.24064514AU

but I can't help suspecting that this is rather awkward. I'm using approximately 300 functions but there are only around 30-40 parameters (like Length in the example but more sophisticated like "free-fall-time", "half-light-radius". "redshift", etc. everything that I at some point needed for any calculation and there are typically 2-10 ways to calculate such a Quantity) so it would be a great gain to collect them into classes and don't have duplicate logic with the result_unit. Would you consider this "good coding" style or should I dismiss this attempt and choose a different approach (if so, any idea which)?


texts: Changing a user status flag, with validation

texts:
I am writing a function which on update of any attribute of model sets the status of variable is_kyc_verified to false.

Here is the code of the User model and the method which changes the status:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  before_update :change_kyc_status, unless: :is_kyc_verified_changed?

  #Associations
  has_one  :address, dependent: :destroy
  has_one  :kyc, dependent: :destroy
  has_one  :pan_detail, dependent: :destroy
  has_one  :document, dependent: :destroy
  has_many :nominee_details, dependent: :destroy
  has_many :bank_details, dependent: :destroy

  #Accept Attributes for associated model

  accepts_nested_attributes_for :address, :kyc, :pan_detail,
                                :document, :nominee_details, :bank_details,
                                allow_destroy: true, reject_if: :all_blank

  #validates
  validates :name, :mobile_no, :gender, :dob,  presence: true
  validates :mobile_no, numericality: true, length: { is: 10 }

  private
  ##
  # Check if is_kyc_verified is set to true
  # if 'yes' then alert user and set is_kyc_verified to false
  def change_kyc_status
    self.is_kyc_verified = false if self.valid? and self.is_kyc_verified.present?
    true
  end

end

As you can see the method initially used to return the self.is_kyc_verified which was false, which in turn resulted in "rollback of transaction" so I explicitly added a true at the end so it won't "rollback the transaction"

However I feel, that this is not the right way to implement this function.
Can you please review my code and suggest me the right way to do so?


texts: Printing all the combination of indexes for 2 sum exact outcome

texts:
Can somebody review the code and provide suggestions on where I can improve on the code like use of better data structure etc.

Input: {1,7,2,8,3,6}, 9

Output: [0, 3] [1, 2] [4, 5]

public class TwoSumExactAll {
    public static void main(String[] args) {
        int[] nums1 = {1,7,2,8,3,6};
        for (List<Integer> list : twoSumExactWithList(nums1,9)) {
            System.out.println(list);
        }
    }

    public static ArrayList<List<Integer>> twoSumExactWithList(int[] nums,int target) {
        HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
        ArrayList<List<Integer>> outerList = new ArrayList<List<Integer>>();
        ArrayList<Integer> innerList=null;
        int complement;
        for(int i=0;i<nums.length;i++) {
            complement = target-nums[i];
            if(map.containsKey(complement)) {
                innerList = new ArrayList<Integer>();
                innerList.add(map.get(complement));
                innerList.add(i);
                outerList.add(innerList);
            }else {
                map.put(nums[i], i);
            }
        }
        return outerList;
    }
}


texts:
I'm teaching myself code using Zed Shaw's Learn Python The Hard Way, and I got bored during one of the memorization lessons so I thought I would make a random D20 number generator for when I play RPGS.

How can I make this code better? Is there anything stupid I'm doing?

import random

name = raw_input('Please Type in your name > ')

print "\nHello %s & welcome to the Random D20 Number Generator by Ray Weiss.\n" % (name)

first_number = random.randint(1, 20)

print first_number

prompt = ("""
Do you need another number? Please type yes or no.
""")

answer = raw_input(prompt)

while answer == "yes":
    print random.randint(1, 20)
    answer = raw_input(prompt)

if answer == "no":
print "\nThank you %s for using the D20 RNG by Ray Weiss! Goodbye!\n" % (name)

Eventually I would love to add functionality to have it ask you what kind and how many dice you want to role, but for now a review of what I've done so far would really help.


texts:
We are developing an automatic text Captcha solver in python 3. The solver has a module that is responsible for extracting letters out of captcha images that contain 4 letters each. We would like to get a review of this module and understand if there are any ways to write it more elegantly.

Here is an example of a captcha image:

Thanks!

import os
import os.path
import cv2
import glob
import imutils

CAPTCHA_IMAGE_FOLDER = "generated_captcha_images"
OUTPUT_FOLDER = "extracted_letter_images"

# Get a list of all the captcha images we need to process
captcha_image_files = glob.glob(os.path.join(CAPTCHA_IMAGE_FOLDER, "*"))
counts = {}

# loop over the image paths
for (i, captcha_image_file) in enumerate(captcha_image_files):
    print("[INFO] processing image {}/{}".format(i + 1, len(captcha_image_files)))

    # Since the filename contains the captcha text (i.e. "2A2X.png" has the text "2A2X"),
    # grab the base filename as the text
    filename = os.path.basename(captcha_image_file)
    captchaCorrectText = os.path.splitext(filename)[0]

    # Load the image and convert it to grayscale
    image = cv2.imread(captcha_image_file)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Add some extra padding around the image
    gray = cv2.copyMakeBorder(gray, 8, 8, 8, 8, cv2.BORDER_REPLICATE)

    # Threshold the image (convert it to pure black and white)
    Thresh = cv2.Threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

    # find the contours (continuous blobs of pixels) the image
    contours = cv2.findContours(Thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Hack for compatibility with different OpenCV versions
    if imutils.is_cv2():
        contours = contours[0]
    else:
        contours = contours[1]

    letter_image_regions = []

    # Now we can loop through each of the four contours and extract the letter
    # inside of each one
    for contour in contours:
        # Get the rectangle that contains the contour
        (x, y, w, h) = cv2.boundingRect(contour)

        # Compare the width and height of the contour to detect letters that
        # are conjoined into one chunk
        if w / h > 1.25:
            # This contour is too wide to be a single letter!
            # Split it in half into two letter regions!
            half_width = int(w / 2)
            letter_image_regions.append((x, y, half_width, h))
            letter_image_regions.append((x + half_width, y, half_width, h))
        else:
            # This is a normal letter by itself
            letter_image_regions.append((x, y, w, h))

    # If we found more or less than 4 letters in the captcha, our letter extraction
    # didn't work correcly. Skip the image instead of saving bad training data!
    if len(letter_image_regions) != 4:
        continue

    # Sort the detected letter images based on the x coordinate to make sure
    # we are processing them from left-to-right so we match the right image
    # with the right letter
    letter_image_regions = sorted(letter_image_regions, key=lambda x: x[0])

    # Save out each letter as a single image
    for letter_bounding_box, letter_text in zip(letter_image_regions, captchaCorrectText):
        # Grab the coordinates of the letter in the image
        x, y, w, h = letter_bounding_box

        # Extract the letter from the original image with a 2-pixel margin around the edge
        letter_image = gray[y - 2:y + h + 2, x - 2:x + w + 2]

        # Get the folder to save the image in
        save_path = os.path.join(OUTPUT_FOLDER, letter_text)

        # if the output directory does not exist, create it
        if not os.path.exists(save_path):
            os.makedirs(save_path)

        # write the letter image to a file
        count = counts.get(letter_text, 1)
        p = os.path.join(save_path, "{}.png".format(str(count).zfill(6)))
        cv2.imwrite(p, letter_image)

        # increment the count for the current key
        counts[letter_text] = count + 1


texts:
I'm handling parameters that are passed from a URL. I want to keep my URLS neat, and the following (rather exhaustive code) has been able to achieve it.
There will be more added, so it would be good to keep it versatile and compact. Code below does work.
URLS patterns
a.com/

a.com/q=bar

a.com/filters=foo

a.com/q=bar&filters=foo

Current code to account for above
const isSearch = this.props.location.pathname.includes("q=")
const isFilter = this.props.location.pathname.includes("filters=")

const encodedVal = encodeURIComponent(e.target.value)

if (encodedVal && isSearch && isFilter) {
    const filters = this.props.match.params.q.split("filters=")[1].split("&")[0];
    this.props.history.push("/q=" + encodedVal + "&filters=" + filters );
  }
 else if (encodedVal && isFilter) {
    const filters = this.props.match.params.q.split("filters=")[1].split("&")[0];
    this.props.history.push("/q=" + encodedVal + "&filters=" + filters );
  }
 else if (encodedVal && isSearch) {
    this.props.history.push("/q=" + encodedVal);
  }
 else if (isFilter && !encodedVal) {
    const filters = this.props.match.params.q.split("filters=")[1].split("&")[0];
    this.props.history.push("/filters="  + filters);
  }
 else if (encodedVal) {
    this.props.history.push("/q=" + encodedVal);
  }
  else {
    this.props.history.push("/");
  }


texts:
I posted this same question on StackOverflow but guys over there told me to post it here.

I have programming in PHP since past 2 years and yet haven't found a perfect script for logging the user in. It's very messy when it comes to deciding whether to use Session or Cookies or both. What value to assign to the Session ID? Whether to store that value in MySQL table or not. How to auto-login the user? And so on...

I've been using this code for few months. Please tell me whether this is fine.

This is the main signin function.

<?php
    //this function is called after sanitizing the user-input
    //$u is username and $p is password
function signin($u,$p) {
    global $conn, $current_user, $signin_stat, $incorrect;
    $q_string="SELECT uid FROM users WHERE (emailid='$u' OR uname='$u') AND AES_DECRYPT(pass,CONCAT(uname,'$p'))='$p'";
    $q=$conn->query($q_string);
    if($q->num_rows==1) {
        $c=$q->fetch_row();
        $uid=$c[0]; //getting uid
        $current_user=new User($uid); //creating $current_user object

        set_session($uid); //setting session

        $signin_stat=1;

        return true;
    } else {
        signout(0);
        $incorrect=1;
        return false;
    }
}
?>

This is the set_session() function :

<?php
function set_session($uid) {
    global $conn;
    $sid=sha1($uid+time()+$_SERVER['REMOTE_ADDR']);
    $q_string="UPDATE users SET sid='$sid' WHERE uid=$uid";
    $q=$conn->query($q_string);
    $_SESSION['user_session']=$sid;
    if($q) return true; else return false;
}
?>

This is the auto_signin script :

<?php
if(isset($_SESSION['user_session'])) {
    $sid=$_SESSION['user_session'];
    global $conn, $current_user;
    $q_string="SELECT uid FROM users WHERE sid='$sid'";
    $q=$conn->query($q_string);
    if($q->num_rows==1) {
        $c=$q->fetch_row();
        $uid=$c[0];
        $current_user=new User($uid);
        $signin_stat=1;
        $current_user->update_online_stat();
    } else {
        signout(0);
    }
}
?>

This is the signout() function

<?php
function signout($uid) {
    global $conn, $current_user, $signin_stat;
    $sid='NULL';
    $q_string="UPDATE users SET sid='$sid' WHERE uid=$uid";
    $q=$conn->query($q_string);

    $signin_stat=0;
    $current_user=0;

    $_SESSION['user_session']='';
    unset($_SESSION['user_session']);
    unset($_POST);
    session_destroy();
}
?>

notes :
$conn is the mysqli object

$current_user is the user object

sid is the field in mysql users table which holds the current session id of the respective user.

Is this script fine or would you suggest some changes?

Or is this completely crap and needs to be written again from scratch?

Please help me out.


texts: Loading template file and replacing placeholders

texts:
I have an HTLP template file called "template.tmpl". In the template I have a few placeholders like {{NAME}} and {{USERNAME}}. I am then loading the template file into a variable called $template using file_get_contents. I then put the $template variable through a function which deals with replacing a series of placeholders.

My code is below and seems to be working fine, but wanted some input if there was any way to improve or make it more efficient.

function replace_tags($string){
    $vars = array('{{NAME}}'=>'Bob', '{{USERNAME}}'=>'user_name', '<?'=>'', '?>'=>'');
    return str_replace(array_keys($vars), $vars, $string);
}

$template = file_get_contents('template.tmpl', true);

echo replace_tags($template);


texts: Encode strings by subtracting one from each character code

texts:
I currently have this encoding function which simply subtracts one from each character code:

String.fromCharCode.apply(null, text.split("").map(function(v) {
    return v.charCodeAt() - 1;
}));

E.g. test becomes sdrs.

I know that this function is silly because it isn't a strong encoding algorithm, but that's not my point. The problem is that it is slow and causes a stack overflow for large strings (~130.000 in length).

I tried a regexp but that's even slower:

text.replace(/./g, function(v) {
    return String.fromCharCode(v.charCodeAt() - 1);
});

I tested both on jsPerf.

Currently, I'm executing a function for each character in both functions. How can I make a function that does the same thing as what these functions are doing, but executes faster without stack overflows?


texts: Turning relativenumber option off/on when opening/closing the gdb terminal window

texts:
When I was not sure about how to do this, I asked this question on StackOverflow, the body of which is the following:

  As regards line numbers, when doing normal file editing, I prefer to
  have the following setting

set number
set relativenumber

  because the former tells me where I am, the latter helps me using
  j and k effectively.

  However, when debugging with
  gdb,
  using the termdebug package and the :Termdebug command, I often
  want to set breakpoints; hence, I'd like to turn the latter option
  off, executing the set norelativenumber command on a global scope,
  so that all files I'm editing show the actual line numbers.

Reading the answer, and Vim help pages a bit more, I ended up with the following solution, which is now part of my ~/.vimrc file:

" Source the termdebug plugin
packadd termdebug

" Add mapping to load termdebug
noremap <silent> <Leader>td :call MyTermdebug()<CR>

" turn off relativenumber,
" start Termdebug,
" and create autocmd to turn relativenumber back on
function! MyTermdebug()
  call SetRelNumInAllWin(v:false)
  augroup ClosingDebugger
    au!
    autocmd BufUnload !gdb call SetRelNumInAllWin(v:true)
  augroup END
  Termdebug
endfunction

" set/unset relativenumber in all windows if flag is v:true/v:false
function! SetRelNumInAllWin(flag)
  let current_win_id = win_getid()
  tabdo windo call SetRelNum(a:flag)
  call win_gotoid(current_win_id)
endfunction

" set/unset relativenumber in current window if flag is v:true/v:false
function! SetRelNum(flag)
  if &number
    if a:flag
      set relativenumber
    else
      set norelativenumber
    end
  end
endfunction


texts: Counting squares in a grid that is subdivided by line segments

texts:
Problem:

  Given a picture of square with a bunch of horizontal and vertical lines in it (lines are not necessarily spanning the full square length, in other words think of a fine grid with many holes in it), design data structure(s) representing the data and a function that returns a number of squares pictured.

My ideas for the solution (in Python 2.7) are:

Using a enum to represent if a cell in a square has left, right, top and bottom border, and initial square with 4 borders;
For each horizontal line, the cell above the line has bottom border, and the cell under the line top border;
For each vertical line, the right cell has left border and the left border has right border;
Count how many cells have 4 borders, the result is the # of sub-squares.

Any advice on better data structure/method design, better algorithm performance in terms of time complexity, or code style advice are highly appreciated.

class SquareBorder:
    has_left = 1
    has_right = 2
    has_top = 4
    has_bottom = 8

def init_square(matrix):
    for col in range(len(matrix[0])):
        matrix[0][col] |= SquareBorder.has_top
        matrix[len(matrix)-1][col] |= SquareBorder.has_bottom
    for row in range(len(matrix)):
        matrix[row][0] |= SquareBorder.has_left
        matrix[row][len(matrix[0])-1] |= SquareBorder.has_right

def add_horizonal_line(matrix, row, start_col, end_col): # on top of row
    for col in range(start_col, end_col + 1):
        matrix[row][col] |= SquareBorder.has_top
        matrix[row-1][col] |= SquareBorder.has_bottom
def add_vertical_line(matrix, col, start_row, end_row): # on left of col
    for row in range(start_row, end_row + 1):
        matrix[row][col] |= SquareBorder.has_left
        matrix[row][col-1] |= SquareBorder.has_right

def find_squares(matrix):
    result = 0
    has_four_borders = SquareBorder.has_right | SquareBorder.has_left | SquareBorder.has_bottom | SquareBorder.has_top
    for row in range(len(matrix)):
        for col in range(len(matrix[0])):
            if matrix[row][col] == has_four_borders:
                result += 1
    return result

if __name__ == "__main__":
    '''
     _ _ _
    |_|_ _|
    |_|_ _|
    |_|_|_|
    '''
    size = 3
    matrix = [[0] * size for _ in range(size)]
    init_square(matrix)
    add_horizonal_line(matrix, 1, 0, 2)
    add_horizonal_line(matrix, 2, 0, 2)
    add_vertical_line(matrix, 1, 0, 2)
    add_vertical_line(matrix, 2, 2, 2)
    print find_squares(matrix) # output is 5


texts:
I'm practicing data structures in C and I implemented a queue based on its description:

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

struct QueueNode {
    int data;
    struct QueueNode* nextNode;
};

struct Queue{
    struct QueueNode* priorNode;
    struct QueueNode* lastNode;
};

struct Queue* initQueue(){
    struct Queue* queue = malloc(sizeof(struct Queue)); //only one is needed
    if(!queue){
        fprintf(stderr,"memory error");
        exit(1);
    }
    queue->priorNode = NULL;
    queue->lastNode = NULL;
    return queue;
}

void enqueue(struct Queue* queue, int num){
    struct QueueNode* queuenode = malloc(sizeof(struct QueueNode));
    if(!queuenode){
        fprintf(stderr,"memory error");
        exit(1);
    }
    queuenode->data = num;
    queuenode->nextNode = NULL;

    if(!queue->priorNode){
        queue->priorNode = queuenode;
    }

    if(queue->lastNode){
        struct QueueNode* temp = queue->lastNode;
        queue->lastNode = queuenode;
        temp->nextNode = queue->lastNode;
    } else {
        queue->lastNode = queuenode;
    }
}

struct QueueNode dequeue(struct Queue* queue){
    if(!queue->priorNode){
        fprintf(stderr,"Queue is empty.\n");
        struct QueueNode nullnode = {0, NULL};
        return nullnode;
    }
    struct QueueNode prior = *queue->priorNode;
    free(queue->priorNode);
    if(prior.nextNode){
        queue->priorNode = prior.nextNode;
    } else {
        queue->priorNode = NULL;
    }
    return prior;
}

void peekQueue(struct Queue* queue){
    printf("\"%d\" is the current prior element in the queue\n", queue->priorNode->data);
}

void listQueue(struct Queue* queue){
    struct QueueNode* qn = queue->priorNode;

    printf("elements in the queue from left(the most prior) to right(the least prior) are:\n");
    while(qn){
        if(!qn->nextNode){
            printf("%d",qn->data);
            break;
        }
        else{
            printf("%d - ",qn->data);
            qn = qn->nextNode;
        }
    }
    printf("\n");
}

void closeQueue(struct Queue* queue){

    struct QueueNode* next = NULL;
    while(queue->priorNode){
        next = queue->priorNode->nextNode;
        free(queue->priorNode);
        if(!next) break;
        queue->priorNode = next;
    }

    free(queue);
}

int main(){
    struct Queue* queue = initQueue();

    enqueue(queue,15);
    enqueue(queue,4);
    enqueue(queue,8);
    enqueue(queue,13);
    enqueue(queue,7);

    listQueue(queue);

    peekQueue(queue);

    struct QueueNode node;

    node = dequeue(queue);
    printf("\"%d\" came out of the queue\n",node.data);
    node = dequeue(queue);
    printf("\"%d\" came out of the queue\n",node.data);
    node = dequeue(queue);
    printf("\"%d\" came out of the queue\n",node.data);
    node = dequeue(queue);
    printf("\"%d\" came out of the queue\n",node.data);
    node = dequeue(queue);
    printf("\"%d\" came out of the queue\n",node.data);
    node = dequeue(queue);
    printf("\"%d\" came out of the queue\n",node.data);

    closeQueue(queue);
return 0;
}

I especially didn't know what to do in my dequeue function when the queue was empty. I don't want the 0 to be returned as well because that would of course be confusing to the user.


texts: Show a search input bar depending on which path the user currently is viewing

texts:
I'm using Laravel with the Blade template engine. I'm trying to show a search input bar, depending on which path the user currently is viewing. The three paths are all, snes and nes.

This is what I have done so far:

@if (request()->route()->getName() === 'snes')
    @include('partials._search')
@endif

@if (request()->route()->getName() === 'nes')
    @include('partials._search')
@endif

@if (request()->route()->getName() === 'all')
    @include('partials._search')
@endif

It doesn't seem so effective nor like good looking code.

How can I shorten this?


texts: Obtaining weather station data from a MySQL database

texts:
I have a PHP page for a weather station that I'm trying to build.

I run multiple queries to pull out data from a MySQL database for min/max/average values for temp, pressure, humidity etc.

All of these are done by multiple MySQL select statements - here are 2 of them:

 $sql_dht22_temp_max = "select DATE_FORMAT(date,'%H:%i'), dht22_temp from weather inner join (select max(dht22_temp) as ts from weather where date(date) = curdate()) as ds on weather.dht22_temp = ds.ts order by date desc limit 1;";

if (!$result = $db->query($sql_dht22_temp_max)){
        die('error 1');
}

while ($row = $result->fetch_assoc()){
        $dht22_temp_max = $row['dht22_temp'];
        $dht22_max_date = $row["DATE_FORMAT(date,'%H:%i')"];
}

$sql_inside_temp_min = "select DATE_FORMAT(date,'%H:%i'), temperature from inside_temp inner join (select min(temperature) as ts from inside_temp where date(date) = curdate()) as ds on inside_temp.temperature = ds.ts order by date desc limit 1;";

if(!$result = $db->query($sql_inside_temp_min)){
    die('error running query');
}

while($row = $result->fetch_assoc()){
    $inside_temp_min = $row['temperature'];
    $inside_min_date = $row["DATE_FORMAT(date,'%H:%i')"];
}

While each statement takes a few milliseconds to run, adding them all up and it takes about 3-4 seconds. So on loading my page, you have to wait 3-4 seconds, which doesn't seem like much but is a pain.

If there a better way of doing this? Running all the statement in parallel? Can the MySQL/PHP code be optimized?

explain select DATE_FORMAT(date,'%H:%i') As MyDate, dht22_temp
    from weather inner join (select min(dht22_temp) as ts from weather
    where date(date) = curdate()) as ds on weather.dht22_temp = ds.ts
    order by date desc limit 1;

# id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
'1', 'PRIMARY', '<derived2>', 'system', NULL, NULL, NULL, NULL, '1', NULL
'1', 'PRIMARY', 'weather', 'index', NULL, 'id_date', '9', NULL, '1', 'Using where'
'2', 'DERIVED', 'weather', 'ALL', NULL, NULL, NULL, NULL, '65420', 'Using where'

Here is the table structure:

# Field, Type, Null, Key, Default, Extra
'idweather', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment'
'date', 'datetime', 'YES', 'MUL', NULL, ''
'rainfall', 'float', 'YES', '', NULL, ''
'windspeed', 'float', 'YES', '', NULL, ''
'dewpoint', 'float', 'YES', '', NULL, ''
'pressure', 'float', 'YES', '', NULL, ''
'bmp085_temp', 'float', 'YES', '', NULL, ''
'dht22_temp', 'float', 'YES', '', NULL, ''
'abs_hum', 'float', 'YES', '', NULL, ''
'gust', 'float', 'YES', '', NULL, ''
'uvi', 'float', 'YES', '', NULL, ''
'light', 'float', 'YES', '', NULL, ''
'rel_humidity', 'float', 'YES', '', NULL, ''
'wind_dir', 'varchar(5)', 'YES', '', NULL, ''


texts:
I'm trying to understand the strtod() function, and how I can handle any user input given to the function. I assume I tested for everything, however I am hoping for a review to make sure and to catch anything I missed. (I know I should separate everything into functions, however, I am just trying to understand the nature of the function, therefore I left everything in main.)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
#include <stdbool.h>

/*@param MAXSIZE max number of chars that are converted to a 64bit double*/
#define MAXSIZE 1077

int main() {

    char str[MAXSIZE];
    printf("Enter a rational number: ");

    for (;;) {
        if (fgets(str, sizeof str, stdin) != NULL) {
            if (strchr(str, '\n')) {
                str[strcspn(str, "\n")] = '\0';
            }
            if (str[0] != '\0') {
                break;
            }
            printf("\nTry again: ");
        }
    }

    char* endptr = NULL;
    errno = 0;
    double number = strtod(str, &endptr);

    //passes over trailing whitespace
    for (; isspace(*endptr); ++endptr);

    if (errno == ERANGE) {
        fprintf(stderr, "Error out of range...\n");
    }
    else if (*endptr != '\0') {
        fprintf(stderr, "error could not convert: %s\n", str);
    }
    else {
        printf("Your string was converted into the rational number: %lf\n", number);
    }
    printf("Your string was: %s\n", str);
    printf("Press any key to continue...\n");
    getch();
}


texts:
This is my take on a simple hangman game, which is played from command prompt.

import random

wordlist = []

word =  random.choice(open("words.txt").readlines())
#word.txt is a list of words, in the same directory with the game file.

length  = len(word)

mock_word = "_ " * length
#The underscores presented to the player

mock_word =  mock_word.split()
#making it a list, since strings can't be assigned

used_lets = []

lives = 7

while True:
    print " ".join(mock_word) #Needs space in join, so the underscores are separated.
    let = raw_input("Give a letter: ")

    if len(let) > 1: #User can only give one letter
        print "Only one!"

    elif (let not in word):
        if let not in used_lets:
            lives = lives - 1
            if lives == 0:
                print "Sorry you lost, the word was:", word
                break
            print "Try again, you have only %r lives left!" % lives
            used_lets.append(let)
            print "So far you have used:"
            print used_lets

    else:
        for i in range(length):
            if let == word[i]:
                mock_word[i] = let

    if "".join(mock_word) == word: #Making it a string again
        print word + " You won!"
        break

If you want to test, just set word to something. That is how I tested the loop.
I would appreciate criticisms of my coding technique, and perhaps the suggestion of an alternative of the while loop use, which feels wrong.


texts:
Context

I have a project which has an importation module to import content of Excel files.

Originally, importation was possible only for .xls file (< 2003) through Interop assemblies through a pretty ugly non-modular architecture. But there was a need to support importation of .xlsx files.

I have refactored the module to build a system of data readers. Depending on the extension of the files that is imported, a data reader class is instantiated accordingly to be able to read the data from either an Excel <2003 file or an Excell >2003 file transparently.

So I have two classes Excel2003DataReader and OpenXmlDataReader both based on the following interface:

public interface IImporterDataReader: IDisposable
{
    object DataFile { get; }

    bool HasValue(string workSheetName, int rowIdx, int columnIdx);

    string GetValue(string workSheetName, int rowIdx, int columnIdx);

    List < RangeItem > GetRangeValues(string workSheetName, int rowIdx, int columnIdx, ExtractDirection direction = ExtractDirection.Horizontal, int amountExtraValues = 0);
}

The IImporterDataReader instance is then passed a parameter to the Import method:

void Import(XmlDocument calculator, IImporterDataReader dataSource, Dictionary<string, string> parameters = null)

So dataSource.GetValue() can be used inside the method without worrying what kind of Excel file is actually imported.

The problem

The problem is that this system is too tightly adressed to Excel files. What I need to be able to reader xml files or json files as well ?

I was thinking of abstracting the way the parameters are passed to the methods HasValue()and GetValue() so they could be different per data reader implementations: have workSheetName, row and column properties for excel files, have an xpath property for xml files, etc.

Could be something like this:

public interface IImporterDataReader: IDisposable
{
    object DataFile { get; }

    bool HasValue(IDataAccessor accessor);

    string GetValue(IDataAccessor accessor);

    // Let's forget about this one right now
    //List < RangeItem > GetRangeValues(string workSheetName, int rowIdx, int columnIdx, ExtractDirection direction = ExtractDirection.Horizontal, int amountExtraValues = 0);
}

Question

I haven't honestly tried implementing such a mechanism, this is still in my mind.

Is this an interesting path to go for to implement such a mechanism ?
Also what could the accessor look like ?

I have the feeling this is a bit too complicated for the purpose, but maybe not.


texts: Slow Flask-SQLAlchemy query using association tables

texts:
I have two models in Flask-SQLAlchemy (Post and Comment) that have many-to-many relationship that is manifested in the third model (post_mentions):

post_mentions = db.Table(
    'post_mentions',
    db.Column('post_id', db.Integer, db.ForeignKey('posts.id'), primary_key=True),
    db.Column('comment_id', db.Integer, db.ForeignKey('comments.id'), primary_key=True),
)

class Post(db.Model):
    __tablename__ = 'posts'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, unique=True, nullable=False)
    mentions = db.relationship('Comment', secondary=post_mentions, lazy='dynamic')

    def __eq__(self, other):
        return self.name.lower() == other.name.lower()

    def __hash__(self):
        return hash(self.name.lower())

class Comment(db.Model):
    __tablename__ = 'comments'

    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.Integer, nullable=False)

There is also a /posts endpoint that triggers the following query:

# flask and other imports

@app.route('/posts')
def posts():
    page_num = request.args.get('page', 1)
    posts = models.Post.query.join(models.post_mentions)\
                             .group_by(models.post_mentions.columns.post_id)\
                             .order_by(func.count(models.post_mentions.columns.post_id).desc())\
                             .paginate(page=int(page_num), per_page=25)
    return render_template('posts.html', posts=posts)

There are more than 14k+ posts and 32k+ comments stored in SQLite database. As you can see from the snippet above, when someone hits /posts endpoint, SQLAlchemy loads all data at once to the memory and then subsequent queries (e.g. retrieving posts, comments to that posts, etc..) take sub-millisecond time, since data is being served from the memory without hitting the database. Initial load takes 10s+ on my laptop, which is, to put it mildly, suboptimal.

So the question is: Considering that users won't view 97+% of posts, how can I both order posts by number of mentions in comments and load them on demand instead of doing it in one swoop?


texts:
I am working on a (HTML/CSS) website to improve my skills but I am not sure if I am doing it the right way, because I have a lot of floats and sizes. I also need help with some CSS things:

What I have:

What I am Shooting for

The red dimensions in the image are the dimensions I've tried to give the objects and which I am not sure if it is the correct way of doing it.
The black words are the things I would like to change in the future, but I need this code reviewed first.

All my code:
INDEX.HTML

sidebar

 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

STYLE.CSS

@import url(reset.css);

body {
background:#f1f1f1;
}

#fullHeader {
float:left;
min-width:100%;
height:90px;
}

#header {
min-width:100%;
height:60px;
background:#B52B42;
}

#inner-header {
width:1180px;
height:60px;
margin:0 auto;
}

#home {
float: left;
width: 140px;
}

#menubar{
float: left;
width: 1180px;
}

#wrapper {
width:1180px;
margin:0 auto;
-moz-box-shadow:0 0 5px #888;
-webkit-box-shadow:0 0 5px #888;
box-shadow:0 0 5px #888;
}

#mainContent {
width:100%;
float:left;
background-color:#FFF;
}

#newsHolder {
float:left;
width:840px;
height:493px;
}

#item1 {
float:left;
width:477px;
height:320px;
margin-bottom:5px;
}

#item2 {
float:right;
width:358px;
height:244px;
margin-bottom:5px;
}

#item3 {
float:left;
width:236px;
height:167px;
margin-right:5px;
}

#item4 {
float:left;
width:236px;
height:167px;
}

#item5 {
float:right;
width:358px;
height:244px;
}

#item1 img,#item2 img,#item3 img,#item4 img,#item5 img {
width:100%;
height:100%;
}

#sidebar-right {
float:right;
width:340px;
background:#FFF;
}

#newsList {
float:left;
width: 840px;
background:#FFF;
}

#footer {
float:left;
min-width:100%;
height:70px;
background:#006;
}

I did not post the CSS code of the navigation menu because it is already working correctly.

I would be very happy if anyone can help me make my HTML/CSS cleaner