texts: Parsing JSON and exploring relationships in Python

texts:
Question:

  Given two users say user1 and usern, print True if there was a chain
  of tweets such that user1 tagged user2, user2 tagged user3 .....
  usern-1 tagged usern or viceversa.

  Input Format

  The 1st line and the 2nd line contains the two users. The 3rd line of
  the input contains the filename in which the dataset of tweets in JSON
  format.

  JSON Format

  { "TweetCount" : 1, "TwitterData" : [ { "userName" : "user1",
  "tweetid" : 12345, "tweet" : "@user2" } ] }

  Output Format

  Print "True" ( quotes are for clarity ) if the two mentioned users are
  connected, and "False" otherwise.

  Constraints:

  1 <= TweetCount <= 300000
  Username, Tweet are of UTF-8 format
  1 <= Tweetid <= 1020

  Sample Input:

user1
user2
input000.in

  input000.in

  { "TweetCount" : 2, "TwitterData" : [ { "userName" : "user1",
  "tweetid" : 1, "tweet" : "Tweet 1 @user2" }, { "userName" : "user2",
  "tweetid" : 2, "tweet" : "Tweet 2 @user4" } ] }

  Sample Output:

  True

  Explanation:

  user1 has user2 tagged in his tweet, hence True

I was wondering if you could take a look at my code and see if

there's a better way of solving the problem than the way I did it (i.e. should I construct a graph?)
I make my code more pythonic

import json

# standardize all input names to lower case
user1 = raw_input().lower()
user2 = raw_input().lower()

filename = raw_input()
user1_mentions = []
to_explore = []
reached = [] # list of users reached

with open(filename) as f:
    json = json.load(f) # JSON representation of input file

# find user1's mentions
for tweet in json['TwitterData']:
    if tweet['userName'] == user1:
        user1_mentions += ([x[1:].encode('utf-8') for x in tweet['tweet'].split() if x.startswith('@') and x[1:].isalnum()])
        to_explore = user1_mentions

while to_explore != []:
    temp_to_explore = [] # temp array for storing words to explore next
    for tweet in json['TwitterData']:
        if tweet['userName'] in to_explore:
            temp_to_explore += ([x[1:].encode('utf-8') for x in tweet['tweet'].split() if x.startswith('@') and x[1:].isalnum()])
    reached += to_explore
    to_explore = temp_to_explore

print reached # ['user2', 'user4']
print user2 in reached # True


texts: Simple boolean gate with two TriState inputs

texts:
As part of a code review I came across this isDummy(a,b)-Method and the question, whether it is more readable as a conjunction, or a disjunction:

Original snippet:

public static boolean isDummy(TriState a, TriState b) {
    return (a.is(ZERO) || b.is(ZERO)) && (a.is(NULL) || b.is(NULL));
}

Suggested change:

public static boolean isDummy(TriState a, TriState b) {
    return a.is(ZERO) && b.is(NULL) || a.is(NULL) && b.is(ZERO);
}

Both of the above return true if one TriState is ZERO and the other is NULL.

Both do exactly the same; however, the latter imho clearly states, that just two possible combinations are a dummy.
The first one could - without knowing that ZERO is not a VALUE and TriState#is(TriState) does an equality check - possibly suggest, that four possible combinations are dummy values.

As you can see in TriState's constructor the author's intention was to implement a helper mechanism to check Doubles for its "valueness". Infinity and NaN aren't taken into account:

enum TriState {
    NULL, ZERO, VALUE;

    public static TriState of(Double number) {
        if (number == null) {
            return TriState.NULL;
        } else if (number == 0d) {
            return TriState.ZERO;
        } else {
            return VALUE;
        }
    }

    private boolean is(TriState other) {
        return this == other;
    }

    /**
    * Tests if this object is {@link #VALUE} and the given TriState is not {@link #VALUE}.
    *
    * @param other the TriState to test against
    * @return true if this object is {@link #VALUE} AND the given TriState is not {@link #VALUE}. False otherwise.
    */
    public boolean andNot(TriState other) {
        return this.is(VALUE) && !other.is(VALUE);
    }

    /**
    * Compares two TriState objects to find out if exactly one is ZERO and exactly one is NULL. This method is commutative.
    *
    * @param a a TriState instance to check
    * @param b a TriState instance to check
    * @return true, if one of the given TriState objects is {@link #ZERO} while the other is {@link #NULL}. False otherwise.
    */
    public static boolean isDummy(TriState a, TriState b) {
        return (a.is(ZERO) || b.is(ZERO)) && (a.is(NULL) || b.is(NULL));
    }
}

While the mere existence of that Enum instead of just using Double instances directly is a whole different matter, I would be interested if there are any known best practices regarding that boolean expression.

Which of the both is easier to understand?


texts: Computer tries to guess your inputted number

texts:
I'm rehashing some of the basics of c++ and I just want to find useful points along the way of things I can do to improve my coding.
This program has the user enter a number, then the computer try to guess it, with some higher/lower logic.
#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    srand(static_cast<unsigned int>(time(0)));  //seed random number generator

    int secretNumber = 0;
    int tries = 0;
    int guess;

    int highRange = 100;
    int lowRange = 0;

    std::cout << "\tWelcome to Guess My Number\n\n";

    std::cout << "\tPlease enter your number between 1 and 100:\n";

    std::cin >> secretNumber;

    do
    {
        do
            guess = rand() % highRange + 1;
        while (guess <= lowRange);

        ++tries;

        if (guess > secretNumber)
        {
            std::cout << "Computer guess was too high! (" << guess << ")\n\n";
            highRange = guess;
        }
        else if (guess < secretNumber)
        {
            std::cout << "Computer guess was too low! (" << guess << ")\n\n";
            lowRange = guess;
        }
        else
        {
            std::cout << "\nI guessed it! (" << guess << ") in " << tries << " guesses!\n";
        }

    } while (guess != secretNumber);

    return 0;
}


texts: Reading a dynamic record length binary file

texts:
I am trying to read a dynamic record length binary file, which has data like this:

field1field2field3field4vector1vector2

Here, field3 defines the occurrence of vectors.

For example, field3 is 2, then vector1&2 would be present and if the value is 3 then vector1,2&3 would be present.

Let's say field1-4 is fixed, the length is 2652 and each vector length is 301. field3 is 3 bytes from position 2396.

I have written the below code which is working fine but giving very bad performance.

my $string;
my $rep_factor;
my $size;

open (FILE, $ARGV[0]) or die $!;
my $re = 2396;
my $rec = 0;
while (<FILE>) {
   seek(FILE,$re,0);
   read(FILE,$rep_factor,2);
   my $rep_fact = undefined2defined(convert2ascii_decimal($rep_factor,0));
   $size = ($rep_fact * 301) + 2652;
   seek(FILE,$rec,0);
   read FILE,$string,$size;

   filewrite ($ARGV[1], recordparse($string));
   $rec = $size + $rec;
   $re = $size + 2396;
}


texts:
I decided to write a console program that can generate a random alphanumerical password in the C language. It's quite useful for when I'm making a new account and need to make up a quick password on the spot. I've noticed a lot of the password generators people have shown on this are written in Java and maybe Python or C# so hopefully mine will add some variety.

This is my code, I've aimed to make it as simple as possible:

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

int main()
{
    srand((unsigned int)(time(NULL)));
    int i;
    char pass[12];

    printf("Press enter to get a twelve-character password\n");
    getchar();

    for (i = 0; i < 4; i++) {
        pass[i] = rand() % 9;
        char capLetter = 'A' + (rand() % 26);
        pass[i + 2] = capLetter;
        char letter = 'a' + (rand() % 26);
        pass[i + 3] = letter;
        printf("%d%c%c", pass[i], pass[i + 2], pass[i + 3]);
    }
    printf("\n\n");
}

I can generate decent passwords, such as: 7Qb4Le2Id0Ss, 1Sw0Nb2Ky1Zp, 0Am3Wa4Wo1Tm and 4Rr4My1Mt1Gj. Like I said, I want to make it more efficient if I can, and perhaps add some punctuation, which does not seem that easy, since the ASCII codes are quite spread out.

Does anyone have any ideas?


texts: Determining if a file or URL is a git repo or archive

texts:
I'm getting these three offenses:

libraries/helpers.rb:4:1: C: Method has too many lines. [11/10]
def get_files(url, file, destination)
^^^
libraries/helpers.rb:18:1: C: Assignment Branch Condition size for unpack_archive is too high. [16.52/15]
def unpack_archive(url, file, destination)
^^^
libraries/helpers.rb:18:1: C: Method has too many lines. [16/10]
def unpack_archive(url, file, destination)

These are all length based offenses. Is there any way to refactor to meet the style guidelines?

# Takes a file and or a url decides if it is a git repo or an archive.
# Downloads or clones it. to the destination.
# Do not enter url with trailing slash.
def get_files(url, file, destination)
  case File.extname(file)
  when '.tar.gz', '.zip' then unpack_archive(url, file, destination)
  when '.git'
    git 'destination' do
      repository "#{url}/#{file}"
      reference 'master'
      user node['apache']['user']
      action :sync
    end
  else fail ArgumentError, "dunno how to handle #{file}"
  end
end

def unpack_archive(url, file, destination)
  remote_file "#{Chef::Config['file_cache_path'] || '/tmp'}/#{file}" do
    owner 'root'
    group 'root'
    mode '0644'
    source "#{url}/#{file}"
    not_if File.readable?(file)
  end
  extract = case File.extname(file)
            when '.tar.gz' then "tar-xC #{destination} -f #{file};"
            when 'zip' then "unzip -d #{destination} -qo #{file};"
            end
  bash "Extract #{file}" do
    cwd ::File.dirname("#{Chef::Config['file_cache_path'] || '/tmp'}/#{file}")
    code   extract
    not_if { ::File.readable(file) }
  end
end


texts: Divide the last element in an array of arrays among the remaining elements

texts:
The function below is part of an overall chunk of code to partition an array  of size M into sub-arrays of size N. The function in question is written to handle the case: what if M isn't divisible by N?  Then, the way the rest of the code works, the last element in the partitioned array might have fewer than N items.  (E.g., if N = 3, there might be an array like [[A, B, C], [D, E, F], [G, H]].

There are two reasonable solutions: (a) just accept a shorter array at the end (maybe with padding, depending on use case), or (b) take the shorter array and distribute it among the remaining arrays.  This code implements solution (b).

function mushInLittleArray(arrs, size){
    var correctSize = arrs[arrs.length - 1].length == size;
    if (correctSize) {
        return arrs;
    }
    var last = arrs.pop();
    var len = last.length;
    var j = 0;
    var div = false;
    var arrlen = arrs.length;
    for (var i = 0; i < len; i++) {
        div = divisible(j, arrlen);
        if (div) {
            j = 0;
        }
        arrs[j].push(last[i]);
        j++;
    }
    return arrs;
}

This code just feels awkward and hackish to me.  In particular, the sleight of hand in the conditional toward the end beginning if (div) smells bad. It's meant to deal with the edge case where leftover group is larger than number of other groups, for example, where N = 5 and we have something like [[A, B, C, D, E], [F, G, H, I, J], [K, L, M, N]], and hence the iteration over the large array needs to reset.  The code as written seems to work fine, but having two loop variables and modifying one of them manually within the block seems like dirty pool to me.  Surely there must be a better way?


texts:
I am looking for ways to improve my API wrapper for Pocket. So far, my code is quite compact and nice (I think), but I feel like there must be a better way to do this.

This is the part where I think a lot of code redundancy due to different parameters that need to be serialized to Json and later send to server.

        public async Task<List<ItemRetrieved>> GetAllUnreadAsync(int sinceInUnixTime = 0)
        {
            var requestUrl = MakeRequestUri("v3/get");

            var request = new HttpRequest(HttpMethod.Post, requestUrl);

            request.AddBody(new
                {
                    consumer_key = _consumerKey,
                    access_token = _accessToken,
                    state = "unread",
                    sort = "newest",
                    since = sinceInUnixTime
                });

            var response = await SendAsync<ItemRetrievedWrapper>(request);

            return response.List.Values.ToList();
        }

    public async Task<List<ItemRetrieved>> GetFavoriteAsync(int sinceInUnixTime = 0)
    {
        var requestUrl = MakeRequestUri("v3/get");

        var request = new HttpRequest(HttpMethod.Post, requestUrl);

        request.AddBody(new
            {
                consumer_key = _consumerKey,
                access_token = _accessToken,
                favorite = 1,
                sort = "newest",
                since = sinceInUnixTime
            });

        var response = await SendAsync<ItemRetrievedWrapper>(request);

        return response.List.Values.ToList();
    }

I have few other methods that look like this as well but the only different is the anonymous object passed inside the AddBody. The anonymous object is the parameters that need to be set. AddBody will serialize the object into Json.

My idea currently is to create a separate class/object for the parameters and use method chaining to build up the parameters before passing it into AddBody.

Maybe looks something like this.

var requestParams = new RequestParams();
requestParams.SortBy("newest").Since(2312321312).IsFavorite(true);
request.AddBody(requestParams);

Are there any other good ways I can refactor my code?

If you need to see the big picture, you can take a look here at my Github https://github.com/shulhi/PocketNet

Thank you.


texts:
So I have been working on this Chess project and for that I need a move generator. I wish to know if I can improve my code for the move generation for the Knight. Here is my current code;
Let me tell a few things so you can better understand it. I am using vector<vector<int>> for the main pseudo moves. I use add the move to a vector<int> first, then I add it to the pseudomoves.
The board is simply represented with int board[8][8]. Here are the values and the pieces that they correspond to;

1-Pawn
2-Bishop
3-Knight
5-Rook
6-Queen
10-King

The negative of the same numbers correspond to the black pieces!
This is the code for generating all moves of the knight.
                if (row > 0 && col < 6 && board[row-1][col+2] <= 0){
                    move.push_back(row);
                    move.push_back(col);
                    move.push_back(row-1);
                    move.push_back(col+2);
                    pseudomoves.push_back(move);
                    move.clear();
                }
                if (row > 1 && col < 7 && board[row-2][col+1] <= 0){
                    move.push_back(row);
                    move.push_back(col);
                    move.push_back(row-2);
                    move.push_back(col+1);
                    pseudomoves.push_back(move);
                    move.clear();
                }
                if (row < 7 && col < 6 && board[row+1][col+2] <= 0){
                    move.push_back(row);
                    move.push_back(col);
                    move.push_back(row+1);
                    move.push_back(col+2);
                    pseudomoves.push_back(move);
                    move.clear();
                }
                if (row < 6 && col < 7 && board[row+2][col+1] <= 0){
                    move.push_back(row);
                    move.push_back(col);
                    move.push_back(row+2);
                    move.push_back(col+1);
                    pseudomoves.push_back(move);
                    move.clear();
                }
                if (row < 6 && col > 0 && board[row+2][col-1] <= 0){
                    move.push_back(row);
                    move.push_back(col);
                    move.push_back(row+2);
                    move.push_back(col-1);
                    pseudomoves.push_back(move);
                    move.clear();
                }
                if (row < 7 && col > 1 && board[row+1][col-2] <= 0){
                    move.push_back(row);
                    move.push_back(col);
                    move.push_back(row+1);
                    move.push_back(col-2);
                    pseudomoves.push_back(move);
                    move.clear();
                }
                if (row > 1 && col > 0 && board[row-2][col-1] <= 0){
                    move.push_back(row);
                    move.push_back(col);
                    move.push_back(row-2);
                    move.push_back(col-1);
                    pseudomoves.push_back(move);
                    move.clear();
                }
                if (row > 0 && col > 2 && board[row-2][col-1] <= 0){
                    move.push_back(row);
                    move.push_back(col);
                    move.push_back(row-2);
                    move.push_back(col-1);
                    pseudomoves.push_back(move);
                    move.clear();
                }
}


texts:
This piece of code checks to see if all the values within an array are all negative and returns true if they all are.

public static boolean allNegatives(int[] a) {

  if(a == null) {

      return false;

   }

    for(int i = 0; i < a.length; i++) {
        if(a[i] > 0)
            return false;
    } return true;
}


texts:
The idea here is we have Roles, Permissions, and a table called PermissionRoles that connect the two. So a Permissions can be in many Roles, and many Permissions can have the same Role. So what the following code does is:

Get all the permissions required for a user to authenticate, by
ActionName
Loop through each of these permissions
Get the list PermissionsRole records that have one of those Permission objects
Get the list of Roles from the list of PermissionRoles
Loop through that list of Roles
Check if a user is in any of those roles

This is the code, I feel like there may be a more efficient way to write this. It is implied that I have instantiated a UserManager and Database Context.

string[] permissions = Permissions.Split(',').ToArray();

IEnumerable<string> perms = permissions.Intersect(db.Permissions.Select(p => p.ActionName));
List<IdentityRole> roles = new List<IdentityRole>();

if (perms.Count() > 0)
{
    foreach (var item in perms)
    {
        var currentUserId = httpContext.User.Identity.GetUserId();

        var permissionsRoles = db.PermissionRoles.Where(p => p.Permission.ActionName == item && p.CompanyId == companyId).ToList();
        var existingRoles = dbu.Roles.Select(x => x.Id).Intersect(permissionsRoles.Select(x => x.RoleId)).ToList();
        foreach (var role in existingRoles)
        {
            ApplicationRole thisRole = dbu.Roles.Find(role);
            if (userManager.IsInRole(currentUserId, thisRole.Name))
            {
                return true;
            }
        }
    }
}
return false;


texts: Demonstration of processing a queue of no-op threads

texts:
I am creating a script, that will SSH to several hosts, get stuff, parse it and return. Because I wait for server response, I'm using threading.

Real script is more complex, so I created this simple program to demonstrate logic.

In real application 'timer' function does ssh with paramiko and parsing, 'main' is pretty much same.

Do I need to use threading.Lock() in this program?

from threading import Thread
import time
import random
import queue

'''
This function demonstrates usage of threads with queue
'''

que = queue.Queue()

def timer(name, delay, que):  # timer's name, time.sleep() delay, queue.Queue() object
    time.sleep(delay)  # sleep

    que.put(name + " is done after " + str(delay) + " seconds")  # add items to queue, used when threaded
    return name + " is done after " + str(delay) + " seconds"  # this is used if fuction is called directly

def main(repeat):
    threads = []  # stores threads after they are started. needed to join threads
    out = []      # used for return
    for i in range(1, repeat):  # Will loop few times, executing threads
        t = Thread(target=timer, args=(('timer' + str(i)), random.choice([2, 3, 2]), que))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()        # Join is needed so that main function waits for threads. We need this to return out list

    while not que.empty():      # At this point threads are completed and joined. so we can dequeue que variable
        out.append(que.get())

    print("main completed")
    return out

start_time = time.time()        # To measure time
if __name__ == '__main__':
    print('\n'.join(main(30)),)
print("--- Done in %s seconds ---" % (time.time() - start_time))


texts:
I have a Data First Migration and have been struggling a little with storing an enum value as a string.

(Im aware that enums should be stored as ints but, personally I have never liked this, yes enums are hard and fast values but I have always percived them to vary a little bit as the code evolves, i am therefore worried about the integrity of using an int value as new values are added.)

However in my example I need to store the value as a string anyway so that other systems will be able to understand it.

So the database has the following generated property

public string billing_location { get; set; }

The View Model

public string billing_location { get; set; }

public MobiusBillingLocation BillingLocation
{
    get
    {
        MobiusBillingLocation mbl;
        if (Enum.TryParse(billing_location, true, out mbl))
        {
            return (MobiusBillingLocation)      Enum.Parse(typeof(MobiusBillingLocation), billing_location, true);
        }

        return MobiusBillingLocation.None;
    }
    //This also needs setting in the controller code
    set { billing_location = value == MobiusBillingLocation.None ? null : value.ToString(); }
}

public enum MobiusBillingLocation { None, UK, US, SGSingapore }

The code has been designed so that it will be happy with null values and translates None as null and back again.

My questions are, does this approach seem reasonable?
Any ideas / suggestions for improvments?
Would you use this approach for enums on a code first model for example?

UPDATE

I will add that, in this database, due to it being legacy and unnormalized (thats another topic) and has systems on it that i can't touch I cant be adding extra lookup tables at this time, the data in it however needs to have meaning to a user, ie integer values won't work as they don't pass meaning.

I am however also interested in some side discussion about use of enums.


texts: Adding some wait time between API requests to avoid overloading the server

texts:
In Shopify a product can belong to a collection.
I have written a method which accepts an organisation. It would then get a list of collections that this organisation has from Shopify. Finally, it has to loop through each collection to get the products that belong to this collection.
I don't want to overload Shopify server by sending too many requests, so I have added 75 ms wait between each request. But since this method is async, I am not quite sure if the responses are handled correctly? Do I need any sort of mutext or locking mechanism to ensure each response is being handled correctly?
public async Task<List<ShopifyCollection>> GetShopifyCollections(Organisation organisation)
{
    int waitInMilliSeconds = 50;
    var shopifyCollections = new List<ShopifyCollection>();
    var customCollections = await GetAllCustomCollections(organisation);

    foreach (var cc in customCollections)
    {
        shopifyCollections.AddCollection(cc.Id, cc.Title);
    }

    foreach (var curCollection in shopifyCollections)
    {
        var products = await GetCollectionProducts(organisation, curCollection.CollectionId);
        curCollection.ProductIds = products.Where(p => p.Id != null && p.Id > 0).Select(p => p.Id.Value).ToList();
        await Task.Delay(waitInMilliSeconds);   // <-- do not overload Shopify
    }

    return shopifyCollections;
}


texts: Return all anagrams for a word matched against a list of words in a file

texts:
The exercise description:

  Given a ‘words.txt’ file (attached) containing a newline-delimited
  list of dictionary words, please implement a small command line
  application capable to return all the anagrams from ‘words.txt’ for a
  given word. You can use any Scala library of your choice, no
  frameworks though.

Note: the file contains words that are sometimes Uppercased or have random upper/lowercasing. Checking for an anagram should not consider casing.

My solution:

Main.scala

import scala.io.Source
import scala.util.Using

object Main extends App {

  def isAnagram(word: String, anagram: String) : Boolean = word.toLowerCase.toSeq.sorted.unwrap == anagram.toLowerCase.toSeq.sorted.unwrap

  print("Type the word for which you wish to search anagrams: ")

  val word = scala.io.StdIn.readLine()

  Using(Source.fromResource("words.txt")){ source =>
    print("Anagrams found: ")
    val anagrams = source.getLines().filter(possibleAnagram => isAnagram(word, possibleAnagram)).toList
    println(anagrams match {
      case _ :: _ => anagrams.mkString(", ")
      case _ => "none"
    })
  }
}

MainTest.scala

import org.scalatest.FunSuite
import org.scalatest.prop.TableDrivenPropertyChecks

class MainTest extends FunSuite with TableDrivenPropertyChecks {
  test("anagram") {
    val parametersTable =
      Table(
        ("listen", "silent"),
        ("stressed", "desserts"),
        ("Dusty", "Study")
      )

    forAll (parametersTable) { (word: String, anagram: String) =>
      assert(Main.isAnagram(word, anagram) === true)
    }
  }

  test("not an anagram") {
    val parametersTable =
      Table(
        ("listen", "desserts"),
        ("stressed", "silent"),
        ("testing", "study")
      )

    forAll (parametersTable) { (word: String, anagram: String) =>
      assert(Main.isAnagram(word, anagram) === false)
    }
  }
}

Using scalatest library for writing the tests.

Stuff I considered when writing the code:

having data driven tests that cover all the basic corner cases
performance - the data is read from the file and processed in a streaming fashion
readability and conciseness - I tried to apply this as much as my Scala knowledge allowed me

Feedback I received from a third party:

Was told that this code is not good enough without getting any concrete explanation.


texts:
I am creating a chat API for Android developers, but it's slow -- the chat app is getting messages a little bit late.

How can I improve the performance of my code?

<?php
require_once('config.php');
$sender_id = $_GET['sender_id'];
$receive_id = $_GET['receive_id'];

$response = array();

if($sender_id && $receive_id)
{

        $results = mysql_query("select * from cpo_chat_system where (sender_id = '$sender_id' AND receive_id = '$receive_id') union select * from cpo_chat_system where (sender_id = '$receive_id' AND receive_id = '$sender_id') ORDER BY date ASC, time ASC");
        $total_record = mysql_num_rows($results);

        if($total_record > 0)
        {
            $response['success'] = '1';
            while($row = mysql_fetch_assoc($results))
            {
                $response['user'][] = $row;
            }
        }
        else
        {
            $response['success'] = '0';
            $response['user']['error'] = "1";
            $response['user']['error_msg'] = "Not Data Found";
        }
}

echo json_encode($response);

?>


texts: Reducing code complexity for UsergridClient constructor

texts:
I'm initializing a class in JavaScript with a bunch of complex property checks. Codacy is showing that this is bad design and recommends reducing cyclomatic complexity.

I'm at a loss for how to improve/streamline this, though.

var ok = require('objectkit')

var UsergridClient = function(opts) {
    var self = this

    // required properties
    if (arguments.length === 2) {
        self.orgId = arguments[0]
        self.appId = arguments[1]
    } else {
        self.orgId = ok(opts).getIfExists('orgId') || ok(config).getIfExists('usergrid.orgId')
        self.appId = ok(opts).getIfExists('appId') || ok(config).getIfExists('usergrid.appId')
    }

    // optional initializer properites
    self.baseUrl = ok(opts).getIfExists('baseUrl') || ok(config).getIfExists('usergrid.baseUrl') || 'https://api.usergrid.com' // default: https://api.usergrid.com
    self.clientId = ok(opts).getIfExists('clientId') || ok(config).getIfExists('usergrid.clientId') // default: undefined
    self.clientSecret = ok(opts).getIfExists('clientSecret') || ok(config).getIfExists('usergrid.clientSecret') // default: undefined
    self.tokenTtl = ok(opts).getIfExists('tokenTtl') || ok(config).getIfExists('usergrid.tokenTtl') || 3600 // time in seconds, default:  3600
    self.authFallback = ok(opts).getIfExists('authFallback') || ok(config).getIfExists('usergrid.authFallback') || 'none' // ('none'|'app') default: 'none'

    // optional post-init properties
    self.paginationPreloadPages = 0 // number of pages to preload
    self.paginationCacheTimeout = 300 * 1000 // default: 300 seconds
    self.paginationCursors = [] // array of pagination cursors

    if (self.orgId !== undefined && self.appId !== undefined) {
        return self
    } else {
        throw new Error('"orgId" and "appId" parameters are required when instantiating UsergridClient')
    }
}


texts: Calculate the lattice paths in an n*n lattice (Project Euler #15)

texts:
Project Euler #15 is to find out all the distinct possible ways there are to move from the first point (1,1) to point (n,n) in an n*n lattice.

def lattice_paths_of_n(n):
    list2 = []
    my_list = []
    for i in range(1, n+2):
        list2.append(i)
    for i in range(1, n+2):
        my_list.append(list2)
    for i in range(0,n+1):
        for f in range(0,n+1):
            if f == 0 or i == 0:
                my_list[i][f] = 1
            else:
                my_list[i][f] = my_list[i-1][f]+my_list[i][f-1]
    return my_list[n][n]

print(lattice_paths_of_n(20))

However, this function is extremely inefficient and I would appreciate it if you could give me suggestions to optimize the same. I tried to find a more efficient solution to this problem on this site, but couldn't find one in Python 3.


texts:
I've just done Project Euler question 10:

  Find the sum of all the primes below two million.

I get the correct answer and it takes about 3.5-4 seconds to run.

I tried to use the Sieve of Eratosthenes to find the solution, but am not sure if my solution is using the method correctly, or if it could be improved in any way.

I was also wondering if anyone knew if for this case, is the Sieve of Eratosthenes the fastest way?

Any feedback would be very much appreciated.

import java.math.BigInteger;
import java.util.ArrayList;

public class Problem10 {

public static void main (String[] args) {
    double startTime = System.currentTimeMillis();
    run();
    double endTime = System.currentTimeMillis();
    System.out.println("Took "+((endTime - startTime) / 1000)+" seconds");
}

public static void run() {
    ArrayList<Boolean> numbers = new ArrayList<Boolean>();
    for (int i = 0; i < 2000000; i++) {
        if (i < 2) numbers.add(false); else numbers.add(true);
    }

    BigInteger count = BigInteger.ZERO;
    int index = 0;
    while (index < 2000000) {
        if (numbers.get(index) == true) { // if the index is true, i.e. prime
                count = count.add(BigInteger.valueOf(index)); // then add it's sum to the count
                for (int i = index; i < numbers.size(); i+=index) { // and then go through all of it's multiples (including itself)
                    if(numbers.get(i) == true) {
                        numbers.set(i, false); // and set them all to be false
                    }
                }
        }
        index++;
    }
    System.out.println("The sum of all primes below 2 million is:  " + count);
}
}


texts:
I have a model Users that each instance have 3 features. It was alright until I wanted to tell if this instance can do the 1st feature, the 3rd or all.

I did a migration:

class AddStatusFeaturesToUsers < ActiveRecord::Migration
  def change
    add_column :users, :status_feature_a, :boolean
    add_column :users, :status_feature_b, :boolean
    add_column :users, :status_feature_c, :boolean
  end
end

Is there a better way for doing this?


texts:
I'm from PPCG so I was making an esolang and I decided to write it in Python. Eventually it went from an esolang to an OEIS (Online Encyclopedia of Integer Sequences) lookup tool. I'm very new to Python.

Essentially this program takes an OEIS sequence number (e.g. 55 for sequence A000055) and the nth number in the sequence to return.

The code gets the OEIS page, parses it with BeautifulSoup, and returns the result, if it doesn't exist it returns "OEIS does not have a number in the sequence at the given index".

import sys, re
from urllib2 import*
from bs4 import BeautifulSoup

# Main logic
def execute(code, nth):
  # Decode input stuff
  num = int(code)
  try:
    f = urlopen("http://oeis.org/A%06d/list" % num)
    # global tree, data # Debugging
    # >:D I'm sorry but I have to use RegEx to parse HTML
    print {key: int(value) for key, value in
      re.findall( r'(\d+) (\d+)', re.sub(r'\D+', " ", re.sub(r'<[^>]+>', "",
        str(BeautifulSoup(f, "lxml").find(lambda tag:
          tag.name == "table" and # A table
          not tag.get('cellspacing') == "0" and # A table table
          len(tag.contents) > 1 # A two column table
        ))
      )) )
    }.get(nth, "OEIS does not have a number in the sequence at the given index")
  except HTTPError:
    print "Could not find sequence A%06d" % num
  except URLError:
    print "Could not connect to sources";
  except:
    print "Verify your numbers are correct"
    raise

if __name__ == '__main__':
  if len(sys.argv) > 1:
    execute(sys.argv[1], sys.argv[2])
  else:
    print """This is the OEIS lookup tool
You haven't entered the sequence""" % (LANGNAME)

As I'm new to Python. I'm using things I only kind of understand. My main concern is how I laid out this program. Especially the HTML parsing, I really doubt I'm doing that in the best way.


texts:
I am rewriting a VB.NET application in C#. This code was originally done in 50 lines and I am trying to clean it up. As you can see I have gotten it down to 10 but I still feel its ugly. I want to convert the call and assignments into one Linq statement or method chain. See Comments:

public void Update(IEnumerable<MyObjectproperties> properties)
    {
        var propertiesToBeUpdated = new List<MyObjectproperties>();
        //I am convinced I can do this in one linq statement
        foreach (var output in properties)
        {
            var outputToBeUpdated = _context.MyObjectProperties.FirstOrDefault(x => x.Key == output.Key);
            outputToBeUpdated.propertiesName = output.propertiesName;
            outputToBeUpdated.propertiesValue = output.propertiesValue;
            propertiesToBeUpdated.Add(outputToBeUpdated);
        }

        _context.Entry(propertiesToBeUpdated).State = EntityState.Modified;
        _context.SaveChanges();
    }

What I am hoping this method looks like when I am done is:

public void Update(IEnumerable<MyObjectProperties> properties)
{
    var propertiesToBeUpdated = //My new linq statement here
    _context.Entry(propertiesToBeUpdated).State = EntityState.Modified;
    _context.SaveChanges();
}

I am "okay" at writing complex linq statements but this one is a bit more than I can handle (assuming its possible).


texts:
What improvements can I make? Should I organize my functions based on A-Z? For example, find_letter function comes before guessing function.

import json
import random
import re

def find_letter(user_input, vocab, i=None):
    return [i.start() for i in re.finditer(user_input, vocab)]

def guessing(tries,vocab,blank_line):
    while tries > 0:
        user_input = input("Guess:")

        if user_input in vocab:
            if not(user_input in blank_line):
                index = find_letter(user_input=user_input,vocab=vocab)
                i = 0
                while i < len(index):
                    blank_line[index[i]] = user_input
                    i += 1

                if not('_' in blank_line):
                    return "you won!!!"
            else:
                print("YOU ALREADY TRIED THAT LETTER!")
        else:
            tries -= 1

        print(str(blank_line) + "  Number of Tries : " + str(tries))

    return "you lost"

def hangman_game(vocab):
    'Preliminary Conditions'
    print(introductory(vocab=vocab))
    tries = num_of_tries(vocab=vocab)
    blank_line = produce_blank_lines(vocab=vocab)
    print(blank_line)

    print(guessing(tries=tries,vocab=vocab,blank_line=blank_line))

def introductory(vocab):
    return "HANGMAN GAME. So...what you gotta do is guess and infer what the word might be. " \
           "WORD COUNT : " + str(len(vocab))

def num_of_tries(vocab):
    if len(vocab) < 7:
        return 8
    elif 7 <= len(vocab) < 10:
        return 10
    else:
        return 14

def produce_blank_lines(vocab):
    blank_line = []
    for i in vocab:
        if i.isalpha():
            blank_line += "_"
        elif i == " ":
            blank_line += " "
        else:
            blank_line += i + " "

    return blank_line

if __name__ == '__main__':
    data = json.load(open("vocabulary.json"))
    vocab = random.choice(list(data.keys())).lower()
    print(vocab)
    print(hangman_game(vocab=vocab))

Snippet of the JSON File

{"abandoned industrial site": ["Site that cannot be used for any purpose, being contaminated by pollutants."], "abandoned vehicle": ["A vehicle that has been discarded in the environment, urban or otherwise, often found wrecked, destroyed, damaged or with a major component part stolen or missing."], "abiotic factor": ["Physical, chemical and other non-living environmental factor."], "access road": ["Any street or narrow stretch of paved surface that leads to a specific destination, such as a main highway."], "access to the sea": ["The ability to bring goods to and from a port that is able to harbor sea faring vessels."], "accident": ["An unexpected, unfortunate mishap, failure or loss with the potential for harming human life, property or the environment.", "An event that happens suddenly or by chance without an apparent cause."], "accumulator": ["A rechargeable device for storing electrical energy in the form of chemical energy, consisting of one or more separate secondary cells.\\n(Source: CED)"], "acidification": ["Addition of an acid to a solution until the pH falls below 7."], "acidity": ["The state of being acid that is of being capable of transferring a hydrogen ion in solution."], "acidity degree": ["The amount of acid present in a solution, often expressed in terms of pH."], "acid rain": ["Rain having a pH less than 5.6."]


texts:
I recently challenged @Hosch520 with writing a query as such:

  Find first questions with answers posted within 24 hours

And he did great. I figured I would have a go at it too. Turns out I learned valuable things about data subsets, so here I am seeking review.

I did not specify whether to return only the first answer within 24 hours, or all answers within 24 hours, so we went about it a bit differently. The remarks at the top of my query give more details.

In any case, mine returns all answers posted to a new user's first question within 24 hours.

Link to query on SEDE.

/*
 * Author: @Phrancis
 * Title: 1st questions with answers within X hours
 * Date: 2015-04-16
 * Purpose:
 *   To query a new user's first question under the condition that
 *   the question received one or more answers within a certain number of
 *   hours (default 24), as well as all qualifying answers, and both users'
 *   name and current reputation. It also calculates the interval between
 *   question and answers.
*/

DECLARE @HoursElapsed AS INT;
SET @HoursElapsed = ##NumberOfHours:float?24##;
-- NumberOfHours: Hours elapsed between OP 1st question and answers following it "Decimals are allowed"

DECLARE @QuestionType INT;
DECLARE @AnswerType INT;
SET @QuestionType = 1;
SET @AnswerType = 2;

WITH AllFirstQuestions AS (
  SELECT
      OwnerUserId
    , Id
  FROM Posts
  WHERE CreationDate IN (SELECT MIN(CreationDate) FROM Posts GROUP BY OwnerUserId)
  AND PostTypeId = @QuestionType
)

SELECT
    qUser.Id AS [User Link]
  , qUser.Reputation AS [Q OP Rep]
  , firstQ.Id AS [Post Link]
  , q.CreationDate AS [Q Date]
  , CONVERT( DECIMAL(10,2), DATEDIFF(MINUTE, q.CreationDate, a.CreationDate) /60.0 ) AS [Hours Elapsed]
  , aUser.Id AS [User Link]
  , aUser.Reputation AS [A OP Rep]
  , a.Id AS [Post Link]
  , a.CreationDate AS [A Date]

FROM Posts AS q
INNER JOIN AllFirstQuestions AS firstQ
  ON q.Id = firstQ.Id
INNER JOIN Posts AS a
  ON q.Id = a.ParentId
  AND q.PostTypeId = @QuestionType
  AND a.PostTypeId = @AnswerType
INNER JOIN Users qUser
  ON q.OwnerUserId = qUser.Id
 AND q.OwnerUserId IS NOT NULL
INNER JOIN Users aUser
  ON a.OwnerUserId = aUser.Id
 AND a.OwnerUserId IS NOT NULL

 WHERE a.CreationDate <= (DATEADD(HOUR, @HoursElapsed, a.CreationDate))
  AND DATEDIFF(HOUR, q.CreationDate, a.CreationDate) <= @HoursElapsed
/* This condition is needed because some "fluke" questions
 * have an answer creation time that is before the question's.
 * Usually due to complicated migrations.
 */
  AND DATEDIFF(HOUR, q.CreationDate, a.CreationDate) >= 0

ORDER BY
    q.CreationDate DESC
  , aUser.Reputation DESC;

I'm looking to see if this can be improved. Maybe mine is too much? I personally feel it is reasonable, and it executes pretty fast:

  14662 rows returned in 194 ms

I scanned through the output for a while to make sure I did not have multiple first questions by the same user, and AFAIK, I do not. I'm open to any criticism to make this better!


texts:
I implemented my own spin on the Atbash cipher in Ruby:

# frozen_string_literal: true

module Cryptorb
  # The Atbash cipher
  module Atbash
    module_function

    # Encrypts a string
    #
    # @param plaintext [String] the message that will be encrypted
    #
    # @return [String] the encrypted message
    def encrypt(plaintext:)
      atbash(plaintext)
    end

    # Decrypts an encrypted string
    #
    # @param ciphertext [String] the encrypted message that will be decrypted
    #
    # @return [String] the decrypted message
    def decrypt(ciphertext:)
      atbash(ciphertext)
    end

    # The algorithm
    def atbash(string)
      cap_a, cap_z = 65, 90
      a, z = 97, 122

      ciphertext = string.chars.map do |char|
        limits = [cap_a, cap_z] if char.ord.between?(cap_a, cap_z)
        limits = [a, z] if char.ord.between?(a, z)

        limits ? (limits.last - (char.ord - limits.first)).chr : char
      end

      ciphertext.join
    end

    private_class_method :atbash
  end
end

White-space and numbers should not be modified. Character case should remain the same.

For example:

"1" should map to "1"
"." should map to "."
"B" should map to "Y"
"b" should map to "y"

Note: This implementation does not follow the "official" mathematical function of the Atbash cipher (E(x) = (-x mod m) + 1). Do you think it would be better if it did?

Here's a REPL if you want to test it online.


texts: How many conditions in an "if clause" is acceptable?

texts:
I'm trying to validate an HTTP Request, and first I want to get sure that all of the information has been posted (and then I'll check the correct format of each incoming data), so to get sure that no Form Spoofing attack is made. However, since this HTTP Post comes from a form, and that form contains almost 40 fields, I came across an if clause like this:

// Here, the if clause has almost 40 conditions to check
// first, second, third, etc. are imaginary names of incoming variables
if (Request["first"] == null || Request["second"] == null || ...)
{
    throw new ApplicationException("Incoming data is incomplete");
}
else
{
    // Now trying to validate the format of incoming data
}

Is it a normal checking mechanism? Is there a better way for doing it?


texts:
I pursued an according algorithm with an absolute best performance, the following class embodies the solution.

Any comment is welcome.

class TextCompressor
{
    private const char Seperator = '\x20';

    private StringBuilder builder;

    public TextCompressor()
    {
        this.builder = new StringBuilder();
    }

    public string Compress(string str)
    {
        int offset = 0;
        int end = str.Length - 1;

        for (int i = 0; i < end; i++)
        {
            if (Char.IsWhiteSpace(str[i]))
            {
                if (i != offset)
                {
                    if (str[i] == Seperator)
                    {
                        if (!Char.IsWhiteSpace(str[i + 1]))
                        {
                            i++;

                            continue;
                        }

                        builder.Append(str, offset, (i - offset) + 1);
                    }
                    else
                    {
                        builder.Append(str, offset, i - offset);
                        builder.Append(Seperator);
                    }
                }

                offset = i + 1;
            }
        }

        if (offset != 0)
        {
            builder.Append(str, offset, str.Length - offset);

            return Char.IsWhiteSpace(str[end]) ? Release().TrimEnd() : Release();
        }

        return Trim(str);
    }

    private static string Trim(string s)
    {
        return (s.Length != 0 && (Char.IsWhiteSpace(s[0]) || Char.IsWhiteSpace(s[s.Length - 1]))) ? s.Trim() : s;
    }

    private string Release()
    {
        string s = builder.ToString();

        builder.Length = 0;

        return s;
    }
}

Compress vs. Regex.Replace

.. using \s{2,}

String: "   The   quick    brown     fox      jumps       over        the         lazy          dog.   "

1.97017 * (10 times faster)
19.333874

String: "The quick brown fox jumps over the lazy dog."

0.485821 * (16 times faster)
8.049062


texts:
I'm trying to get the distance traveled in a collection of routes on a straight line. The rule to determine the distance is that a route segment counts only once. For example given the segments (50, 70) and (60, 80), the total distance covered is 30 instead of 40, because the segment (60, 70) is covered twice.

Sample:

╔═══════╦═══════╦═══════╗
║ Route ║ From  ║  To   ║
╠═══════╬═══════╬═══════╣
║     1 ║   100 ║   110 ║
║     2 ║   115 ║   116 ║
║     3 ║   100 ║   111 ║
║     4 ║     0 ║    15 ║
║     5 ║    50 ║   110 ║
║     6 ║    70 ║   120 ║
╚═══════╩═══════╩═══════╝

In these routes the actual distance traveled was 85m. I made a solution that uses a bit array to control, and a counter to calculate the distance, with this solution the process speed and the memory consumption is good, up to 20250000 meters, after this distance the performance begins to fall. Could they recommend me some algorithm to solve this kind of problem?

Note: These distance are in a straight line, they are not routes that have georeference, they are segments of a straight line.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    static Estacion[] estaciones = new Estacion[]{
          new Estacion(100,110),
          new Estacion(115,116),
          new Estacion(100,111),
          new Estacion(0,15),
          new Estacion(50,110),
          new Estacion(70,120)
      };

  public static void Main (string[] args) {
      Console.WriteLine (Calcular());
  }

  public static int Calcular()
  {

    var min =estaciones.Min(m=> m.Desde);
    var max =estaciones.Max(m=> m.Hasta);

    var recorrido =0;
    var cantidad= max-min;
    var bA = new BitArray(cantidad,false);
    foreach(var e in estaciones.OrderByDescending(o=> o.Longitud))
    {
      var h= ((e.Hasta-e.Desde)/2);
      for(int i= 0;i<= h ; i++)
      {
        var slot=i+e.Desde-min;
        if(slot<cantidad)
        if(!bA.Get(slot))
        {
           bA.Set(slot,true);
          recorrido++;
        }
        slot=e.Hasta-i-min-1;
        if(!bA.Get(slot))
        {
           bA.Set(slot,true);
          recorrido++;
        }
        if(recorrido== cantidad)
          return recorrido;
      }
    }
    return recorrido;
  }

  public class Estacion
  {
    public Guid Id {get; set;}
    public int Desde {get; set;}
    public int Hasta {get; set;}
    public int Longitud {get; set;}

    public Estacion(int a, int b)
    {
      Desde = a;
      Hasta= b;
      Longitud= Hasta-Desde;
      Id= Guid.NewGuid();
    }
  }
}


texts: Lock-free queue with doubly linked list correctness

texts:
I need a lock-free queue which is implemented by doubly linked list.

Is my code correct?  Are there any errors?  Are there any improvements to be made?

linkedlist.h

/*
 * linkedlist.h
 *
 *  Created on: 2014. 5. 10.
 *      Author: dlaru_000
 */

#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_

/*
 * circular doubly linked list
 * PushBack / PopFront: single-producer, single-customer lock-free queue
 * Erase: thread-unsafe
 */

#include <stddef.h>
#include <stdint.h>

typedef struct tagLinkedListNode
{
    struct tagLinkedListNode * volatile pNext;
    struct tagLinkedListNode * volatile pPrev;
} LinkedListNode;

typedef struct tagLinkedList
{
    LinkedListNode dummy;

    /*
     * It can be invalid while some function is running on the other thread.
     * However it must valid after/before the function is finished.
     */
    uint32_t size;
} LinkedList;

void ckLinkedListInit(LinkedList *pList);

static inline LinkedListNode *ckLinkedListHead(LinkedList *pList) { return pList->dummy.pNext; }
static inline LinkedListNode *ckLinkedListTail(LinkedList *pList) { return pList->dummy.pPrev; }

void ckLinkedListPushBack(LinkedList *pList, void *pNode);
LinkedListNode *ckLinkedListPopFront(LinkedList *pList);

void ckLinkedListErase(LinkedList *pList, void *pNode);

#endif /* LINKEDLIST_H_ */

linkedlist.c

/*
 * linkedlist.c
 *
 *  Created on: 2014. 5. 10.
 *      Author: dlaru_000
 */

#include "linkedlist.h"

void ckLinkedListInit(LinkedList *pList)
{
    // circular linked list
    pList->dummy.pNext = &pList->dummy;
    pList->dummy.pPrev = &pList->dummy;
    pList->size = 0;
}

void ckLinkedListPushBack(LinkedList *pList, void *pNode)
{
    __sync_add_and_fetch(&pList->size, 1);

    LinkedListNode *dummy = &pList->dummy;

    LinkedListNode *ptr = (LinkedListNode *)pNode;
    LinkedListNode *tail;

    ptr->pNext = dummy;

    while (1)
    {
        tail = dummy->pPrev;
        ptr->pPrev = tail;
        if (__sync_bool_compare_and_swap(&dummy->pPrev, tail, ptr))
        {
            tail->pNext = ptr;
            break;
        }
    }
}

LinkedListNode *ckLinkedListPopFront(LinkedList *pList)
{
    LinkedListNode *dummy = &pList->dummy;

    LinkedListNode *ptr, *next, *dnext;

    ptr = dummy->pNext;
    if (ptr == dummy)
    {
        return NULL;
    }

    while (1)
    {
        next = ptr->pNext;
        if (__sync_bool_compare_and_swap(&next->pPrev, ptr, dummy))
        {
            dnext = dummy->pNext;
            __sync_bool_compare_and_swap(&dummy->pNext, dnext, next);
            break;
        }
    }

    __sync_sub_and_fetch(&pList->size, 1);
    return ptr;
}

void ckLinkedListErase(LinkedList *pList, void *pNode)
{
    LinkedListNode *ptr = (LinkedListNode *)pNode;
    LinkedListNode *prev = ptr->pPrev;
    LinkedListNode *next = ptr->pNext;

    prev->pNext = next;
    next->pPrev = prev;
    pList->size--;
}

The type of the second parameter of PushBack is void *, because the list actually contains such a thing like the following:

struct SomeData
{
    LinkedListNode _node;
    ...
};

I'm using GCC 4.8.2 with cygwin.

Um, I've noticed that "__sync" functions, which the program is using, are legacy, and there are new functions __atomic. How can I migrate to __atomic?


texts: C++ call std::list of objects instead of C linked list

texts:
Can this be made more C++ a like with std::list or something so the Clink class is not needed?

I have a dynamic list of objects, and the number of them could change during runtime.

The expected output in no specific order. As an example 'Cb' runs before 'Ca':

link-contructed
Ca-contructed
Cb-contructed
Cb-run
Ca-run
Ca-destructed
Cb-destructed
link-destructed

I would like the program to be more C++ like with std::list or something. I have looked at std::forward_list but can not really see how it should be used. All examples I could find is about std::list<int>. My Ctask needs to have next in it and Clink needs to know which objects is used. Not so generic. Here is the mixed C/C++ program which does the expected:

/*
vim: ts=4 :
g++ -lstdc++ -o linked linked.cpp && ./linked
*/

#include <iostream>
using namespace std;

class Ctask {
public:
    Ctask *next = NULL;
    Ctask(void) {}
    virtual ~Ctask(void) {}
    virtual void run(void) = 0;
};

/* --------------------------------- */

class Clink {
public:
    Clink(void) {
        cout << "link-contructed" << endl;
    }
    ~Clink(void) {
        Ctask *temp;
        while (temp = head) {
            head = head->next;
            delete temp;
        }
        cout << "link-destructed" << endl;
    }
    void run(void) {
        Ctask *temp = head;
        while (temp) {
            temp->run();
            temp = temp->next;
        }
    }
    void add(Ctask *newnode) {
        if (tail)
            tail->next = newnode;
        else
            head = newnode;
        tail = newnode;
    }
private:
    Ctask *head = NULL;
    Ctask *tail = NULL;
};

/* --------------------------------- */

class Ca: public Ctask {
public:
    Ca(void) {
        cout << "Ca-contructed" << endl;
    }
    ~Ca(void) {
        cout << "Ca-destructed" << endl;
    }
    void run(void) {
        cout << "Ca-run" << endl;
    }
};

class Cb: public Ctask {
public:
    Cb(void) {
        cout << "Cb-contructed" << endl;
    }
    ~Cb(void) {
        cout << "Cb-destructed" << endl;
    }
    void run(void) {
        cout << "Cb-run" << endl;
    }
};

/* --------------------------------- */

int main(void) {
    Clink link;
    link.add((Ctask *)new Ca());
    link.add((Ctask *)new Cb());
    link.run();
    return 0;
}


texts:
I am building game where a player must build a path from the bottom of the grid to the top. When a grid square is changed I check to see if they have completed the path (won).

Because the check happens a lot, and the server is doing the check, I need it to be efficient. I am using basic recursion.

Detection

var tiles = create2dTiles(arrayOfTiles, snapshot.width);

if(!checkObviousNoWin(tiles, -1)) {
    console.log("Checking win for player (-1)");
    var won = false
    for(var i=0; i<tiles[0].length; i++) {
        // START RECURSION HERE
        won = checkWin(tiles, tiles.length - 1, i, -1, 0);
        if(won) {
            break;
        }
    }
    if(won) {
        console.log("Bottom player (-1) (user1) won!");
        ref.child("games").child("active").child(snapshot.game_key).child("status").set(-1);
        return;
    }
}

Check win (recursion here)

var traversed = []
// Start this func with the every index of the last sub array (top or bottom sub array)
function checkWin(tiles, outerIndex, innerIndex, owner, depth) {
    if(owner != tiles[outerIndex][innerIndex].owner) {
        return false
    }
    // Win check
    if(owner == -1 && owner == tiles[outerIndex][innerIndex].owner && outerIndex == 0) {
        // Bottom player
        console.log("Bottom player won");
        return true
    }
    if(owner == 1 && owner == tiles[outerIndex][innerIndex].owner && outerIndex == tiles.length - 1) {
        // Top player
        console.log("Top player won");
        return true
    }

    // Get neighbors
    var neighbors = getNeighbors(tiles, outerIndex, innerIndex);
    for(var i=0; i<neighbors.length; i++) {
        var didTraverse = false
        for(var t=0; t<traversed.length; t++) {
            if(traversed[t][0] == neighbors[i][0] && traversed[t][1] == neighbors[i][1]) {
                didTraverse = true
                console.log("Traversed (" + outerIndex + ", " + innerIndex + ") already...");
            }
        }
        if(!didTraverse) {
            traversed.push([outerIndex, innerIndex]);
            // RECURSION HERE
            if(checkWin(tiles, neighbors[i][0], neighbors[i][1], owner, depth + 1)) {
                return true;
            }
        }
    }
    return false;
}

Get neighbors

function getNeighbors(tiles, outerIndex, innerIndex) {
    var neighbors = [];
    var indexOuter = -1;
    var indexInner = -1;
    var changes = [
        [-1,-1], [-1, 0], [-1,1], [0,1], [1,1], [1,0], [1,-1], [0,-1]
    ];
    for(var i=0; i<changes.length; i++) {
        indexOuter = outerIndex + changes[i][0];
        indexInner = innerIndex + changes[i][1];
        // Can check tiles[0].length because we created, know they're all the same length
        if((indexOuter >= 0 && indexOuter < tiles.length) && (indexInner >= 0 && indexInner < tiles[0].length)) {
            neighbors.push([indexOuter, indexInner]);
        }
    }
    return neighbors;
}

Basically, I made a 2D array of all the squares. Then do a basic check before the recursion, I have excluded that code, then:

Loop through bottom squares, if one is colored (owned) then get its neighbors
Get 8 possible neighbors, check if any are owned, if so, recurse
Record all squares already traversed, don't check those again
Repeat until one of those neighbors is at the top or fail


texts: Is it possible to make a re-usable icon component that doesn't create duplicate TemplateRefs

texts:
I have attempted to create an IconComponent that shows a different SVG icon depending on the string that is passed in.
Example:
<app-icon icon="tick"></app-icon>

Would show an SVG of a tick.
Small StackBlitz example
I believe this approach, however, creates a new and unique TemplateRef for each instance of IconComponent, which would create useless duplicates of data in memory.
This problem concerns me when there may be thousands of icons on a page, such as on a table/grid.
Is there a better approach?
import {
  ChangeDetectorRef,
  Component,
  Input,
  OnChanges,
  SimpleChanges,
  TemplateRef,
  ViewChild
} from "@angular/core";

@Component({
  selector: "app-icon",
  templateUrl: "./icon.component.html",
  styleUrls: ["./icon.component.css"]
})
export class IconComponent implements OnChanges {
  @Input("icon")
  public icon?: string;

  @ViewChild("chevronTemplate", { static: true })
  public chevronTemplate?: TemplateRef<undefined>;

  @ViewChild("tickTemplate", { static: true })
  public tickTemplate?: TemplateRef<undefined>;

  public iconTemplate?: TemplateRef<undefined>;

  public constructor(private readonly changeDetectorRef: ChangeDetectorRef) {}

  public ngOnChanges(changes: SimpleChanges): void {
    let hasChanges = false;

    if (changes.icon !== undefined) {
      this.iconTemplate = this.getIconTemplate();

      hasChanges = true;
    }

    if (hasChanges) {
      this.changeDetectorRef.detectChanges();
    }
  }

  private getIconTemplate(): TemplateRef<undefined> {
    switch (this.icon) {
      case "chevron":
        return this.chevronTemplate;

      case "tick":
        return this.tickTemplate;

      default:
        throw new Error(`Unknown Icon Type '${this.icon}'.`);
    }
  }
}


texts: Handling optional parameters in a servlet

texts:
I have a form that submits to a servlet that has optional parameters. If they are empty they are just ignored. This is the template I am using:

if (!(param = (String)params.get("httpParam")).equals("")) {
   // Handle parameter
}

It doesn't quite feel right. It works, but I think it could be more readable. Any suggestions?


texts: Bank account supporting deposit, withdrawal, and interest

texts:
This is my completed code I was wondering whether it needs a correction

This is my first class

public class Account
{
    private double balance; //STATE
    private double interestRate; //STATE
    private double rate;//STATE

    public Account()
    {
        balance = 0;
        interestRate = 0;
    }

    public Account(double amount, double interestRate)
    {
        balance = amount;
        rate = interestRate;

    }

    public void deposit(double amount)
    {
        balance=balance+amount;
    }

    public void withdraw(double amount)
    {
        balance = balance - amount;
    }

    public void setInterest(double rate)
    {
        balance = balance + balance * rate;
        //this.setInterst = setInterest;
        //setInterest = InterestRate / 12;
    }

    public double computeInterest(int n)
    {
        balance=Math.pow(balance*(1+rate),n/12);
        return balance;
    }

    public double getsetInterest()
    {
        return rate;
    }

    public double getBalance()
    {
        return balance;
    }

    public void close()
    {
        balance =0;
    }

}

This is my second class

public class TestAccountInterest
{
    public static void main (String[] args)
    {
        Account acc1 = new Account(500, 0.1);//0.10);
        Account acc2 = new Account(400, 0.2); //0.20);

      /*************************************
       ACC1 ACCOUNT BELOW
       *************************************/
        acc1.deposit(500);
        acc1.withdraw(300);
        acc1.computeInterest(12);
        System.out.println(acc1.computeInterest(12));

        /**************************************
        ACC2 ACCOUNT BELOW
         **************************************/
        acc2.withdraw(200);
        acc2.deposit(800);
        acc2.computeInterest(24);
        System.out.println(acc2.computeInterest(24));

    }

}

Can anyone see whether I would be able to make the code more compact and is the way that I have coded perfectly valid. The code is about an Accounts class with a test account class for the second class it is supposed to calculate the compute interest of 12 months for the first one and for the second one is supposed to be about 24 months.


texts: Avoiding shell injection when calling Git in Python

texts:
I'm developing a command line application in Python which processes information that users provide. I've been reading the Python documentation on this topic and found that the built-in module subprocess provides the call method, which executes a string as if it was run on a command line. The disadvantage of this approach is that it can lead to shell injection.

The solution I came up with uses a set of illegal substrings, such as rm or -rf, and then uses regex to check whether the provided string contains a substring from the set.

import re
from string import ascii_letters, punctuation

# Generate a set of characters used for string sanitization.
punctuation_minus = set(punctuation) - set(('.', '_', '-'))
substrings = set(("rm", "&&", "-f", "null", "/dev/null", "2>&1", "-rf",
              "rf"))
illegal = [re.escape(item) for item in (punctuation_minus | substrings)]
illegal_as_str = "|".join(illegal)

def sanitize_string(s):
    """Cleans a string from illegal characters."""
    # Get all legal strings.
    operations = re.split(illegal_as_str, s)
    # Remove trailing spaces
    no_trailings = [x.strip() for x in operations]
    # Remove empty strings.
    list_of_operations = filter(None, no_trailings)
    # Generate a safe string to return.
    operations_str = " ".join(list_of_operations)
    try:
        operations_str.decode("utf-8")
        return operations_str
    except UnicodeDecodeError as detail:
        print("UnicodeDecodeError: " + str(detail))
        return False

The inherent issue with this approach is that it heavily depends on the set of illegal characters I'm using. Is there any way I can sanitize a string taking into account the common attacks? And if not, how can I improve my code?

The user is expected to provide git commands, such as git add or git push. Each one of these git commands needs certain parameters that the user needs to provide. The next example shows how all the illegal substrings are removed from a user input when adding files to the staging area:

>>> git_add_str = "git add {}"
>>> files_to_add = input("Files to add as string:")
Files to add as string: "file1.py file2.py; rm -rf /"
# Clean files_to_add before modifying git_add_str.
>>> clean_str = sanitize_string(files_to_add)
>>> clean_str
'file1.py file2.py'
>>> git_add_str = git_add_str.format(clean_str)
>>> git_add_str
'git add file1.py file2.py'

This output is considered legal as it does not contain any of the illegal substrings. Now it is safe to run subprocess.call with this string and shell=True.


texts: Should view related methods be included in models?

texts:
class Submission < ActiveRecord::Base

  def get_status_css()
    if self.status == IN_PROGRESS
      "info"
    elsif self.status == FAILED
      "error"
    elsif self.status == COMPLETED
      "success"
    else
      "warning"
    end
  end

end

Submission is a model class and it has a method that returns css variables based on its status. Is this correct in the MVC architecture? I was thinking that since get_status_css is a method that is related to view, it shouldn't belong to a model class. Perhaps it should be put in the controller?


texts: Party Invitation - Trimming the Invitation List

texts:
I am learning Java right now and am coding some simple programs to practice. Right now, one of my for loops has an inelegant way of ending the loop. I was wondering if there was another way to express what I want the program to do.

Problem: Party Invitation

  Problem Description

    Number your friends 1,2,....,K and place them in a list in this order. Then perform m rounds. In each round, use a number to determine which friends to remove from the ordered list.

    The numbers will use numbers r1, r2,....,rm. In round 'i' remove all the remaining people in positions that are multiples of ri (that is, ri, 2ri, 3ri,...) The beginning of the list is position 1.

    Output the numbers of the friends that remain after this removal process.

  Input Specification

    The first line of input contains the integer K. The second line of input contains the integer m, which is the number of rounds of removal. The next m lines each contain one integer. The 'i'th of these lines contains ri indicating that every person at a position which is multiple of ri should be removed.

  Output Specification

    The output is the integers assigned to friends who were not removed. One integer is printed per line in increasing sorted order.

  Sample Input

    10

    2

    2

    3

  Output for Sample Input

    1

    3

    7

    9

  Explanation of Output for Sample Input

    Initially our list of invitees in 1,2,3,4,5,6,7,8,9,10. There will be two rounds of removals. After the first round of removals, we remove the even positions (because round 1 is '2', so every second position), which causes our list of invitees to be 1, 3, 5, 7, 9. After the second round of removals. we move every 3rd remaining invitee: thus, we keep 1 and 3, remove 5 and keep 7 and 9, which leaves us with an invitee list of 1, 3, 7, 9.

My code has a few System.out.printlns so I can keep track of what it is doing.

public class Party {

public static void main(String args[]) {
    try {

        BufferedReader input = new BufferedReader(new InputStreamReader(
                System.in));

        int totalFriends = Integer.parseInt(input.readLine());
        int rounds = Integer.parseInt(input.readLine());
        int[] roundNumber = new int[rounds];
        ArrayList<Integer> friendList = new ArrayList<Integer>(totalFriends);

        // create my list of friends
        for (int i = 0; i < totalFriends; i++) {
            friendList.add(i + 1);
        }

        // create an array for the number of rounds to cut, and how to cut
        // each time
        for (int i = 0; i < rounds; i++) {
            roundNumber[i] = Integer.parseInt(input.readLine());
        }

        System.out.println("Rounds: " + Arrays.toString(roundNumber));

        // for each round, do this
        for (int h = 0; h < rounds; h++) {

            System.out.println("Removing every " + roundNumber[h]
                    + " number");

            System.out.println("Starting with: " + friendList);

            int indexToRemove = 0;

            //the for loop here tells it to exit when the indexToRemove is larger
            //than the friendlist. I have to say +roundNumber[h] - 1, because the indexToRemove is
            //from the last iteration, not the one I want it to check.

            for (int i = 0; (indexToRemove + (roundNumber[h] - 1)) < friendList
                    .size(); i++) {

                indexToRemove = ((roundNumber[h] - 1) + (i * (roundNumber[h] - 1)));
                System.out.println("Removing index: " + indexToRemove);

                friendList.remove(indexToRemove);

                System.out.println(friendList);

            }

        }

        // the required output for this problem
        for (int i = 0; i < friendList.size(); i++) {
            System.out.println(friendList.get(i));
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}


texts: Babel codemod to transform require statements

texts:
I'm starting to explore the world of ASTs and codemods. As such my first foray is a simple transform to move statements like let fs = require('fs') to const fs = require('fs').

const declaratorKinds = { let: null, var: null }

export default function(babel) {
 const { types: t } = babel

 return {
   visitor: {
     VariableDeclaration(path) {
       if (!(path.node.kind in declaratorKinds)) { return }

       const d = path.node.declarations[0]

       if (!(
         d.init
         && d.init.callee
         && d.init.callee.name === 'require')) { return }

       path.replaceWith(
         t.VariableDeclaration('const', path.node.declarations)
       )
     }
   }
 }
}

Here's a live ast explorer version.

I'm a newbie here so i'm interested in any feedback, but I'd particuarly like to know about:

Is VariableDeclarator the best node type to base this transform on?
Is there a way I could better filter for require declarations?


texts:
Is the following good design for doing entity framework code first? What am I missing for a production system? I haven't included all my code, just a snapshot...

My application, doesn't update the database; it just reads it.

public class Document
{
    [Key, ScaffoldColumn(false)]
    public Int32 DocumentID { get; set; }

    [ScaffoldColumn(false)]
    public Boolean? Status { get; set; }

    [Display(Name = "Document Text"), DataType(DataType.MultilineText)]
    public String DocumentText { get; set; }

    [ScaffoldColumn(false), DataType(DataType.Url)]
    public String DocumentFolderPath { get; set; }

    [ScaffoldColumn(false), DataType(DataType.Url)]
    public String DocumentJSONPath { get; set; }

    [ForeignKey("DocumentID")]
    public virtual DocumentMetadata Metadata { get; set; }

    [ForeignKey("DocumentID")]
    public virtual ICollection<Page> Pages { get; set; }
}

public class Page
{
    [Key, ScaffoldColumn(false)]
    public Int32 PageID { get; set; }

    [Required, Display(Name = "Page"), DataType(DataType.Text)]
    public Int32 PageNumber { get; set; }

    [Required, ScaffoldColumn(false)]
    public Int32 DocumentID { get; set; }

    [ScaffoldColumn(false), DataType(DataType.ImageUrl)]
    public String ImagePath { get; set; }

    [Required, Display(Name = "Page Text"), DataType(DataType.MultilineText)]
    public String PageText { get; set; }

    [NotMapped]
    public String HighlightedText { get; set; }

    [ForeignKey("PageID")]
    public virtual ICollection<Word> Words { get; set; }
}

public class ArchiveDatabaseInitializer : DropCreateDatabaseIfModelChanges<ArchiveContext>
{
    protected override void Seed(ArchiveContext context)
    {
        try
        {
            GetDocuments().ForEach(d => context.Documents.Add(d));
            GetDocumentMetatdata().ForEach(d => context.DocMetadata.Add(d));
            GetPages().ForEach(d => context.Pages.Add(d));
            GetWords().ForEach(d => context.Words.Add(d));
            context.SaveChanges();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private static List<Document> GetDocuments()
    {
        var documents = new List<Document> {
            new Document
            {
                DocumentID = 1,
                DocumentFolderPath = @"Doc1",
                DocumentJSONPath = @"Doc1.json",
                Status = true
            },
            new Document
            {
                DocumentID = 2,
                DocumentFolderPath = @"Doc2",
                DocumentJSONPath = @"Doc2.json",
                Status = true
            }
        };
        return documents;
    }

public class ArchiveContext : DbContext
{
    public ArchiveContext()
        : base("archiveDB")
    {
    }
    public DbSet<Document> Documents { get; set; }
    public DbSet<DocumentMetadata> DocMetadata { get; set; }
    public DbSet<Page> Pages { get; set; }
    public DbSet<Word> Words { get; set; }
}


texts: Best practice for cleaning Pandas dataframe columns

texts:
I am cleaning str columns in a Pandas dataframe (see below for an example), and I have been wondering if there are more concise ways or additional inplace methods to do so. What are the general best practices for cleaning columns in Pandas?
import pandas as pd
df = pd.DataFrame.from_dict({"col1": [0, 1, 2, 3], "col2": ["abcd efg", ".%ues", "t12 ^&3", "yupe"]})

df["col2"] = df["col2"].str.lower()
df["col2"] = df["col2"].str.strip()
df["col2"].replace(to_replace="[^a-zA-Z ]", value="", regex=True, inplace=True)


texts: Regex - Input Checker Class - Lambda with two lists

texts:
I have an input checker class with some RegExes, and I have converted some of the loops to lambdas. Am I doing it right? They seem to work fine, but I'm new to Lambdas. Does this offer a performance benefit over the commented implementation? Should I try implementing the first one as a lambda, and if so, how? Thanks in advance!
public static class DataChecker
{
    public static bool IsGameInputDataValid(string[] dataFile)
    {
        if (dataFile.Length < 5)
        {
            return false;
        }

        var regexList = new List<Regex>();
        regexList.Add(new Regex("^\\d\\s\\d$"));
        regexList.Add(new Regex("^(\\d,\\d )*(\\d,\\d)$"));
        regexList.Add(new Regex("^\\d\\s\\d$"));
        regexList.Add(new Regex("^\\d \\d [NESW]{1}$"));
        regexList.Add(new Regex("^[RLM]{1}( [RLM]{1})*$"));

        //cant figure this one out as lambda... but should it even be converted for performance reasons?
        for (int i = 0; i < 4; i++)
        {
            if (!regexList[i].IsMatch(dataFile[i]))
            {
                return false;
            }
        }

        var listOfMoves = dataFile.Select(x => x).Skip(4).ToList();
        //instead of:
        // for (int i = 4; i<countOfLinesInInputFile; i++)
        // {
        //     listOfMoves.Add(lines[i]);
        // }

        var areaAnyMoveSequencesInvalid =
            listOfMoves.Select(x => regexList[4].IsMatch(x)).ToList()
            .Any(y => y == false);

        if (areaAnyMoveSequencesInvalid)
        {
            return false;
        }

        // instead of:
        // foreach (var line in listOfMoves)
        // {
        //     if (!regexList[4].IsMatch(line))
        //     {
        //         return false;
        //     }
        // }

        return true;
    }
}

edit: Originally I wanted the question to only focus on the lambdas, but I got a lot of responses for the RegExes as well. Therefore I'll add the missing parts to make sense of that. It's a turtle-moving game in 2-dimensional x,y coordinates map.
Sample data file:
5 4
1,1 1,3 3,3
4 2
0 1 N
R M L M M
R M M M
M R M M M M
M R M M
M M M

Rules:
The first line should define the board size
• The second line should contain a list of mines (i.e. list of co-ordinates separated by a space)
• The third line of the file should contain the exit point.
• The fourth line of the file should contain the starting position of the turtle.
• The fifth line to the end of the file should contain a series of moves.
Where:
R: Rotate right
L: Rotate left
M: Move
N,E,S,W: cardinal directions
I've updated the original with d+ instead of d, to allow for multiple digit coordinates:
        regexList.Add(new Regex("^\\d+\\s\\d+$"));
        regexList.Add(new Regex("^(\\d+,\\d+ )*(\\d+,\\d+)$|^$"));
        regexList.Add(new Regex("^\\d+\\s\\d+$"));
        regexList.Add(new Regex("^\\d+ \\d+ [NESW]{1}$"));
        regexList.Add(new Regex("^[RLM]{1}( [RLM]{1})*$"));


texts: Median solving from Interview street in Python

texts:
Any suggestions to improve the performance of the following code? This code is exceeding the time limit for the last four cases. This is a solution to the problem https://www.interviewstreet.com/challenges/dashboard/#problem/4fcf919f11817

def main():
    N = int(raw_input())
    if(0<=N<=100000):
        x = []
        ans=[]
        l=[]
        m=[]
        for i in xrange(0, N):
            tmp = raw_input()
            a, b = [xx for xx in tmp.split(' ')]
            l.append(a)
            m.append(int(b))

        for i in xrange(0, N):
            if l[i]=='r':
                if len(x)<1 or m[i] not in x:
                        ans.append('Wrong!')
                elif m[i] in x:
                    x.remove(m[i])
                    q=len(x)
                    if q%2==1:
                        ans.append(x[(q/2)])
                    elif q%2==0:
                        if q==0:
                            ans.append('Wrong!')
                        else:
                            k=x[q/2]+x[(q/2)-1]
                            if k%2==0:
                                ans.append(int(k)/2)
                            else:
                                ans.append(k/2.0)
            elif l[i]=='a':
                x.append(m[i])
                x=sorted(x)
                p=len(x)
                if p%2==1:
                    ans.append(x[(p/2)])
                else:
                    k=x[p/2]+x[(p/2)-1]
                    if k%2==0:
                        ans.append(int(k)/2)
                    else:
                        ans.append(k/2.0)

        for i in ans:
            print i

if __name__ == "__main__":
    main()

from sys import stdin,stdout
from bisect import bisect,insort
def main():
    N = int(raw_input())
    x = []
    ans = []
    append = x.append
    ans_append = ans.append
    remove = x.remove
    read = stdin.readline
    for i in xrange(0, N):
        tmp = read()
        a, b = tmp.split(' ')
        b = int(b)
        if a == 'r':
            search_result = search(x,b)
            if len(x) < 1 or not(search_result):
                ans_append('Wrong!')
            else:
                remove(b)
                ans_append(median(x))
        else:
            insort(x, b)
            ans_append(median(x))
    for i in ans:
        print i

def median(arr):
    q = len(arr)
    if q==0:
        return 'Wrong!'
    if q%2 == 1:
        return arr[(q/2)]
    else:
        k = arr[q/2] + arr[(q/2)-1]
        if k%2 == 0:
            return int(k)/2
        else:
            return k/2.0

def search(arr,element):
    position = bisect(arr, element)
    if len(arr) >= position and len(arr)!=0:
        if arr[position-1] == element:
            return True
        else:
            return False
    else:
        return False

if __name__ == "__main__":
    main()


texts: Download a PDF and submit it as a print job

texts:
I have following Java code, which is to print PDF, but in a busy location this code is taking about 20 to 30 second delay before submitting to the hardware.

get the PDF file via the network
download and save locally
then submit local file, to the print job to printer
printer hardware warm up
printer hardware prints

Whole job takes about 1 to 2 minute
(depending on the hardware mode, and networking mode).

I am getting lot of complaints and I can't seem to find any issue in my version.  Is there any improvement I can make in the following code which might boost the speed?

While testing, it seems like the delay is causing when the file is saved to the disk and read from the disk.

import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaTray;
import javax.print.attribute.standard.Slides;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

public class IPrint {

  public static boolean saveFile(URL url, String file) throws IOException {
    boolean download_status = false;

    System.out.println("[OK] - open");
    InputStream in = url.openStream();
    FileOutputStream fos = new FileOutputStream(new File(file));
    System.out.println("[OK] - reading file...");
    int length = -1;
    byte[] buffer = new byte[1024];

    while ((length = in.read(buffer)) > -1) {
        fos.write(buffer, 0, length);
    }
    fos.close();
    in.close();

    download_status = true;
    System.out.println("[OK] - downloaded");
    return download_status;
  }

  public static void main(String[] args) throws IOException, PrinterException {
    String downloaded_filename = "C:/Python27/pdf.pdf";
    String download_pdf_from = "http://www.example.com/" + args[0];
    String downloaded_filename_open_as_pdf = "C:\\Python27\\pdf.pdf";

    String printerNameDesired = "Brother HL-6180DW series";

    PrintService[] services = PrinterJob.lookupPrintServices();
    DocPrintJob docPrintJob = null;
    for (int i = 0; i < services.length; i++) {
      System.out.println(services[i]);
    }

    try{
      URL url = new URL(download_pdf_from);

      if(saveFile(url, downloaded_filename)) {
        try {
          PDDocument pdf = PDDocument.load(new File(downloaded_filename_open_as_pdf));
          PrinterJob job = PrinterJob.getPrinterJob();
          for (int i = 0; i < services.length; i++) {
           if (services[i].getName().equalsIgnoreCase(printerNameDesired)) {
             docPrintJob = services[i].createPrintJob();
           }
          }

          job.setPrintService(docPrintJob.getPrintService());
          job.setPageable(new PDFPageable(pdf));

          PrintRequestAttributeSet pset = new HashPrintRequestAttributeSet();

          //'top': The top input tray in the printer.
          //'middle': The middle input tray in the printer.
          //'bottom': The bottom input tray in the printer.
          //'envelope': The envelope input tray in the printer.
          //'manual': The manual feed input tray in the printer.
          //'large-capacity': The large capacity input tray in the printer.
          //'main': The main input tray
          //'side': The side input tray

          //pset.add(MediaTray.TOP);// From top to bottom, first tray1
          pset.add(MediaTray.BOTTOM); // from top to bottom, the last tray2
          pset.add(Sides.DUPLEX);
          job.print(pset);

        } catch (Exception e) {
          System.out.println("[FAIL]" + e);
        }
      } else {
        System.out.println("[FAIL] - download fail");
      }
    } catch (Exception ae) {
      System.out.println("[FAIL]" + ae);
    }

  }

}


texts:
I've created a JavaScript application to highlight the syntax of HTML and PHP. I know a lot of syntax highlighter are available nowadays, I just created to extend my knowledge in JS and regular expressions. I only wanted to know if its the right way to do this. (The code below works fine.)

js/codeHighlighter.js

function codeHighlighter(){
    var obj=document.getElementsByTagName("code");
    for(var i=0;i<obj.length;i++){
        var data=obj[i].innerHTML;
        data=data.replace(/&lt;(.*?)&gt;/g,"&lt;$1&gt;");
        data=data.replace(/"(.*?)"/g,"&quot;$1&quot;");
        data=data.replace(/&lt;\?(.*?)\s/g,"&lt;?$1");
        data=data.replace(/\s\?&gt;/g,"?&gt;");
        data=data.replace(/\/\* (.*?) \*\//g,"/* $1 */");
        data=data.replace(/(new|echo|print|while|for|foreach|class|public|function|static|protected|private|return|required|required_once|include|include_once)[^=]/g," $1 ");
        data=data.replace(/\\n/g,"
");
        data=data.replace(/\\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp");
        obj[i].innerHTML=data;
    }
}

index.html

        <title>Code Highlighter</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

This application highlights `php` and `html` code.

            /* A sample code. */\n
            &lt;div class="code" &gt;\n
            \t Hello!\n
            &lt;/div&gt;\n
            &lt;?php\n
            class Anish(){\n
            \n
            \t public function __construct(){\n
            \t\t return "Hello";\n
            \t }\n
            \n
            }\n
            $anish=new Anish();\n
            echo $anish;\n
            ?&gt;\n


texts: Porting ProcMonDebugOutput from C# to VBA

texts:
This code has one public method. ProcMonDebugOutput(). It will sent a string of text to Process Monitor that process monitor will display.

I'm basically ported this file.

I don't have a 64 bit version of office to test this on, but I think I used all the LongPtr right.

My two big concerns are:
* Are the Win32 API calls "correct". I know they're passing the right data, but should I fiddle with them to make more sense?
* Is my error handling appropiate?

Option Explicit

' Win32 API Constants
Private Const GENERIC_WRITE As Long = &H40000000
Private Const OPEN_EXISTING As Long = &O3&
Private Const FILE_WRITE_ACCESS As Long = &H2
Private Const FILE_SHARE_WRITE As Long = &H2
Private Const FILE_ATTRIBUTE_NORMAL As Long = &H80
Private Const METHOD_BUFFERED As Long = 0
Private Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000
Private Const LANG_NEUTRAL = &H0

' Process Monitor Constants
Private Const FILE_DEVICE_PROCMON_LOG As Long = &H9535
Private Const PROCMON_DEBUGGER_HANDLER As String = "\\.\Global\ProcmonDebugLogger"
Private Const IOCTL_EXTERNAL_LOG_DEBUGOUT As Long = -1791655420

Dim hProcMon As LongPtr

Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileW" _
    (ByVal lpFileName As LongPtr, _
     Optional ByVal dwDesiredAccess As Long = GENERIC_WRITE, _
     Optional ByVal dwShareMode As Long = FILE_SHARE_WRITE, _
     Optional lpSecurityAttributes As LongPtr = 0, _
     Optional ByVal dwCreationDisposition As Long = OPEN_EXISTING, _
     Optional ByVal dwFlagsAndAttributes As Long = FILE_ATTRIBUTE_NORMAL, _
     Optional ByVal hTemplateFile As LongPtr = 0) As LongPtr

Private Declare Function DeviceIoControl Lib "kernel32" _
    (ByVal hDevice As LongPtr, _
     ByVal dwIoControlCode As Long, _
     ByVal lpInBuffer As LongPtr, _
     ByVal nInBufferSize As Long, _
     Optional lpOutBuffer As LongPtr, _
     Optional ByVal nOutBufferSize As Long, _
     Optional lpBytesReturned As Long, _
     Optional ByVal lpOverlapped As LongPtr) As Long

Private Declare Function GetLastError Lib "kernel32" () As LongPtr
Private Declare Sub SetLastError Lib "kernel32" (ByVal dwErrCode As LongPtr)
Private Declare Function FormatMessage Lib "kernel32" Alias "FormatMessageA" _
    (ByVal dwFlags As Long, lpSource As Any, ByVal dwMessageId As Long, _
     ByVal dwLanguageId As Long, ByVal lpBuffer As String, ByVal nSize As Long, _
     Arguments As Long) As Long

Public Function ProcMonDebugOutput(message As String) As LongPtr
    ProcMonDebugOutput = False
    Dim outLen As Long
    outLen = 0

    If hProcMon = 0 Then
        hProcMon = CreateFile(StrPtr(PROCMON_DEBUGGER_HANDLER))
    End If
    If hProcMon = -1 Then
        Dim Buffer As String
        'Create a string buffer
        Buffer = Space(200)
        FormatMessage FORMAT_MESSAGE_FROM_SYSTEM, ByVal 0&, Err.LastDllError, LANG_NEUTRAL, Buffer, 200, ByVal 0&
        Err.Raise Buffer
    End If

    ProcMonDebugOutput = DeviceIoControl _
        (hProcMon, IOCTL_EXTERNAL_LOG_DEBUGOUT, _
        StrPtr(message), Len(message) * 2)
End Function

UPDATE

Based on the feedback I've changed one API Signature and my public method:

Private Declare Function DeviceIoControl Lib "kernel32" _
    (ByVal hDevice As LongPtr, _
     ByVal dwIoControlCode As Long, _
     ByVal lpInBuffer As LongPtr, _
     ByVal nInBufferSize As Long, _
     Optional lpOutBuffer As LongPtr, _
     Optional ByVal nOutBufferSize As Long, _
     Optional lpBytesReturned As Long, _
     Optional ByVal lpOverlapped As LongPtr) As Boolean

Public Function ProcMonDebugOutput(message As String) As Boolean
    If hProcMon = 0 Or hProcMon = 0 Then
        hProcMon = CreateFile(StrPtr(PROCMON_DEBUGGER_HANDLER))
    End If
    If hProcMon = -1 Then
        Err.Raise Err.LastDllError
    End If

    ProcMonDebugOutput = DeviceIoControl _
        (hProcMon, IOCTL_EXTERNAL_LOG_DEBUGOUT, _
        StrPtr(message), Len(message) * 2)
End Function


texts: Validation of uploading images and adding records to the database

texts:
I am doing a php project with the codeigniter framework. In my controller, I have a function that does the following.

Uploads an image to the server
Add a row to the database. The data would be retrieved from the form that calls the controller.

The best approach might be to put these two things in separate functions, but it has to be atomic (If either the upload or the insert fails, the other should not complete) so I decided to put these in one function.

First here are the helper functions I used:

// I created this so I can use it an an argument to functions
function is_empty($var) {
    return empty ( $var );
}

// has the functionality of array_map and array_filter
function array_map_filter($orig, $pred, $apply) {
    $result = array ();
    foreach ( $orig as $key => $value ) {
        if ($pred ( $value )) {
            $result [$key] = $apply ( $value );
        }
    }
    return $result;
}

// checks the status of the new uploaded file saved in a temporary folder. The error code and full path of the file is taken from the $_FILES variable
function validate_file($full_path, $error_code) {
    if (is_file ( $full_path )) {
        throw new Exception ( 'This file already exist.' );
    }
    if ($error_code != 0) {
        throw new Exception ( $error_code );
    }
}

Here is my function.

public function add() {
    if (empty ( $_POST )) {
        $data ['title'] = 'add form';
        $this->load->view ( 'templates/header', $data );
        $this->load->view ( 'content/add' );
        return;
    }
    $errors = array ();
    try {
        $errors = array_map_filter ( $_POST, 'is_empty', function ($val) {
            return "no value";
        } );
        if (empty ( $errors )) {
            $root = $_SERVER ['DOCUMENT_ROOT'];
            $upload_path = $root . 'images/';
            $file_field = 'image_path';
            $file = $_FILES [$file_field];
            $file_name = $file ['name'];
            $full_path = $upload_path . $file_name;
            // a file should already be uploaded in a tmp folder. The following function checks the status of the upload
            // throws an exception, so the rest cannot execute
            validate_file ( $full_path, $file ['error'] );
            $rest = array (
            // ...
            // throws an exception if the record already exist in the database, so the rest cannot execute
            $this->gmodel->insert ( 'neo_content', array_merge ( $_POST, $rest ), array (
                    'title' => $_POST ['title']
            ) );
            move_uploaded_file ( $file ['tmp_name'], $full_path );
        }
    } catch ( Exception $e ) {
        // catch everything and add them to the $errors array
        $errors ['error'] = $e->getMessage ();
    }
    header ( 'Content-Type: application/json' );
    // send to ajax
    echo json_encode ( $errors );
}

As you've noticed, the way I tried to insure the operation is atomic is to throw an exception so I can guarantee the program will not continue to the next part of the code. I've read that doing this is generally bad because users giving wrong inputs should always be expected and the flow of the program should not be interrupted because of that. But I believe I can use exceptions in this case because I wish to preserve atomicity.

Is my code wrong? Are there better ways of doing this? How can I make this code better?


texts: Refactoring two similar methods into a single Angular service

texts:
I am trying to create a service for two similar-but-still different methods:

Method one is this:

scope.computeStyle = (element, rowComponent) ->
  elementHash = {}
  if element.type == 'table'
    elementHash.height = 600
    if rowComponent?.height?
      elementHash.height = rowComponent.height
  else if element.type == 'single_value'
    elementHash.height = 200
    elementHash.width = 800
  return elementHash

Method two is this:

scope.computeStyle = (component) ->
  elementHash = {}
  if component.element.type == 'table'
    elementHash.height = 600
    if component.height?
      elementHash.height = component.height * 50
  else if component.element.type == 'single_value'
    elementHash.height = 200
    elementHash.width = 800
  return elementHash

What I am confused about is that method one has two inputs, while method one has one input.

There are also two idiosyncrasies in the two where we could compute a component.height * 50 for method two while method one, we can ignore that.

I tried something like the following -- to call computeStyle(element, rowComponent) when used in the controller for method one, and computeStyle(element, ""), and then check if the second input is an empty string. Then in the implementation, I would have method one be one code block, and method two be a second code block like:

scope.computeStyle = (myElement, rowComponent) ->
  elementHash = {}
  if rowComponent == ""
    if myElement.element.type == 'table'
      elementHash.height = 600
      if myElement.height?
        elementHash.height = myElement.height * 50
    else if myElement.element.type == 'single_value'
      elementHash.height = 200
      elementHash.width = 800
    return elementHash
  else
    if myElement.type == 'table'
      elementHash.height = 600
      if rowComponent?.height?
        elementHash.height = rowComponent.height
    else if myElement.type == 'single_value'
      elementHash.height = 200
      elementHash.width = 800
    return elementHash

But that is even more unreasonable than having two separate methods in two different files.


texts:
Challenge: Write a program which determines the largest prime palindrome less than 1000.

The answer is 929, and my program correctly finds and prints this, but actually ended up being more complex than I expected.

I'd like a general review, but also want to pinpoint if

I'm overdoing it/the plain way would be faster.
I'm doing anything inefficiently/there are superior alternatives.

Solution

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class PrimePalindrome {
    public static void main(String[] args) {
        final int LIMIT = 1000;

        System.out.println(computeLargestPrimePalindrome(LIMIT));
    }

    private static boolean isPalindromic(int s) {
        return s == reverse(s);
    }

    private static int reverse(int n) {
        return Integer.parseInt(
            new StringBuilder(Integer.toString(n)).reverse().toString()
        );
    }

    /* Finding all prime numbers under an integer,
    using Sieve of Eratosthenes
    http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes */
    private static List<Integer> getPrimesUnder(int limit) {
        int prime;
        List<Integer> primes = new ArrayList<>();
        List<Integer> numbers = new ArrayList<>();

        for (int i = 2; i < limit; i++) {
            numbers.add(i);
        }

        while (!numbers.isEmpty()) {
            prime = numbers.get(0);
            primes.add(prime);

            for (int i = prime; i < limit; i += prime) {
                numbers.remove((Integer) (i));
            }
        }

        return primes;
    }

    private static int computeLargestPrimePalindrome(int limit) {
        List<Integer> primes = getPrimesUnder(limit);
        ListIterator li = primes.listIterator(primes.size());

        while (li.hasPrevious()) {
            if (isPalindromic((int) li.previous())) {
                return (int) li.next();
            }
        }

        return -1; // if none are found
    }
}


texts: Parsing a string of key-value pairs as a dictionary

texts:
I always use nested list and dictionary comprehension for unstructured data and this is a common way I use it.

In [14]: data = """
41:n
43:n
44:n
46:n
47:n
49:n
50:n
51:n
52:n
53:n
54:n
55:cm
56:n
57:n
58:n"""
In [15]: {int(line.split(":")[0]):line.split(":")[1] for line in data.split("\n") if len(line.split(":"))==2}
Out [15]:
{41: 'n',
 43: 'n',
 44: 'n',
 46: 'n',
 47: 'n',
 49: 'n',
 50: 'n',
 51: 'n',
 52: 'n',
 53: 'n',
 54: 'n',
 55: 'cm',
 56: 'n',
 57: 'n',
 58: 'n'}

Here I am doing line.split(":")[0] three times. Is there any better way to do this?