texts: Setting the smallest number so far from user input

texts:
I'm trying to teach myself C++ from Stroustrup's Principles and Practice Using C++ (second edition) and I've gotten to the drill in chapter 4. The problem tells me to make a program that takes in a number with a unit of either feet, inches, meters, and centimeters, as well as log the largest and smallest numbers the user has input. I got the code to work by initializing my smallest number as 0 and making an if statement check if the input was smaller or 0 (because you can't really have 0 length).

Is there a way to either start with an infinitely larger "smallest number" variable so it always changes it in the if statement, or a way to where it has to do as few if statements as possible? Also, I'd rather not ask for an initial starting number before the while loop.

#include "std_lib_facilities.h"

using namespace std;

int main()
{
    cout << "Please input a number followed by a unit (cm, m, in, ft). Results are read in meters. Input a '|' to terminate the program." << endl;

    double x;
    string unit = " ";;
    constexpr double cm = .01;
    constexpr double in = .0254;
    constexpr double ft = .3048;
    double smallest = 0;
    double largest;
    double sum = 0;

    while(cin >> x >> unit)
    {
        if((char)x == '|')
            break;

        cout << "Value entered: " << x << unit << endl;
        if(unit=="m" || unit=="cm" || unit=="in" || unit=="ft") //converts units to meters
        {
            if(unit == "m")
            {
                x=x;                //
            }
            else if(unit == "cm")
            {
                x*=cm;
            }
            else if(unit == "in")
            {
                x*=in;
            }
            else if(unit == "ft")
            {
                x*=ft;
            }
            else
                cout << "Something went wrong." << endl;

            if(x > largest)
            {
                largest = x;
            }
            if(x < smallest || smallest == 0)
            {
                smallest = x;
            }
            cout << "The smallest number so far is: " <<smallest<< " meters\n";
            cout << "The largest number so far is: " << largest << " meters\n";

            sum+=x;
        }
        else
            cout << "Invalid unit! Try again." << endl;
    }
    cout << "The sum of all lengths is: " << sum << " meters\n";
}


texts: Conversion to typescript from javascript

texts:
This is my first attempt in converting a pure javascript to typescript. Any comment?
const apiUrl = 'https://localhost:123'

export function webApiUrl() {
    return apiUrl;
}

export function downloadPdf(id : number, fileName: string) {
    const spinner: HTMLElement = document.getElementById('spinner') as HTMLImageElement

    spinner.style.display = 'block'

    fetch(`${apiUrl}/api/file/download?fileDocumentId=${id}`).then(resp => resp.arrayBuffer()).then(resp => {

        // set the blog type to final pdf
        const file = new Blob([resp], { type: 'application/pdf' });

        // process to auto download it
        const fileURL: string = URL.createObjectURL(file);
        const link: HTMLAnchorElement = document.createElement('a');
        link.href = fileURL;
        link.download = fileName;
        link.click();
        spinner.style.display = 'none'
    });
}

I think the only code I can't figure out how to convert over is the blob type.


texts:
I am trying to make file read and update operations thread safe and prevent race conditions in Python. Am I missing out something, or would this work in production?

import os
import time
from contextlib import contextmanager
import errno

current_milli_time = lambda: int(round(time.time() * 1000))
lock_retry_wait = 0.05 # in seconds

@contextmanager
def exclusive_file(filename, mod, lock_wait_timeout=3000):

    lockfile = filename + ".lock"

    wait_start = current_milli_time()

    while True:
        try:
            # acquire lock
            fd = os.open(lockfile, os.O_CREAT|os.O_EXCL)
            break

        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise

            else:
                t = current_milli_time()
                if (t - wait_start) > lock_wait_timeout:
                    raise

                time.sleep(lock_retry_wait)

    with open(filename, mod) as f:
        yield f

    os.close(fd)
    os.unlink(lockfile)

with exclusive_file("test.txt","a+") as f:
    previous_value = f.read()
    f.truncate()
    f.write(previous_value + str(time.time()))
    time.sleep(20)


texts: AngularJS with global data and "service" / using $watch on $rootScope

texts:
I am currently learning angular.js.

The following is an example I came up with. The goal:

An editor for a dict, the dict format is: {key: [type, data]}
A view of the same data
The "type" should be validated. I use two types: "string" (can be anything) and "greeting" (a string that starts with hello)
Don't care for minify compatibility

The first solution I came up with did the validation inside the controllor of the editor view - but I would prefer it to be global. Every time the global data changes - no matter from where - the validation should be run.

<!doctype html>

The Editor

            {{ key }}
            <input ng-model="value[1]">
            ok
            NOK {{ !validation[key] }}

Some View

            {{ key }}
            {{ value[1] }}


texts: !empty() check before a foreach statement

texts:
Is this the best way to prevent that foreach loop from happening if $terms doesn't exist?

$terms = get_the_terms( $postid, 'fecha' );
if(!empty($terms)) {
    foreach($terms as $term) {
        $myterm = $term->slug;
        if(in_array($myterm, $queried_terms)) {continue;}
        $queried_terms[] = $myterm;
    }
}


texts:
Basically I implement a traditional file-descriptor-based streambuffer for istream operations. The implementation overrides the sync and underflow functions, while in sync the buffer will be automatically enlarged if necessary (just like vector).

class InputStreamBuffer : public std::basic_streambuf<char> {

  private:

    // small stack buffer optimization
    constexpr static size_t _STACK_BUFSZ = 128;

    static_assert(_STACK_BUFSZ >= 1, "Stack buffer size should be at least 1");

    char_type  _stk [_STACK_BUFSZ];
    char_type* _buf {_stk};

    size_t _size {_STACK_BUFSZ};

    const int _fd {-1};

  public:

    InputStreamBuffer(const int);
    ~InputStreamBuffer();

  protected:

    int sync() override;
    int_type underflow() override;
};

InputStreamBuffer::InputStreamBuffer(const int fd) :
  _fd {fd} {
  setg(_buf, _buf, _buf);
}

InputStreamBuffer::~InputStreamBuffer() {
  if(_buf != _stk) {
    std::free(_buf);
  }
}

int InputStreamBuffer::sync() {

  auto success = int {0};

  while(1) {

    size_t empty = gptr() - eback();
    size_t avail = egptr() - gptr();

    // Before we issue the read, make sure we have enough space.
    if(egptr() == eback() + _size) {
      // Reuse the empty region.
      if(empty > _size / 2) {
        std::memmove(eback(), gptr(), avail);
      }
      // Double the array size.
      else {
        _size = _size * 2;
        auto chunk = static_cast<char_type*>(std::malloc(_size*sizeof(char_type)));
        std::memcpy(chunk, gptr(), avail);
        if(_buf != _stk) std::free(_buf);
        _buf = chunk;
      }
      setg(_buf, _buf, _buf + avail);
    }

    // Read the data.
    issue_read:
    auto ret = ::read(_fd, egptr(), _size - avail);

    if(ret == -1) {
      if(errno == EINTR) {
        goto issue_read;
      }
      if(errno != EAGAIN && errno != EWOULDBLOCK) {
        success = -1;
      }
      break;
    }
    else if(ret == 0) {
      break;
    }

    setg(eback(), gptr(), egptr() + ret);
  }

  return success;
}

InputStreamBuffer::int_type InputStreamBuffer::underflow() {
  int success = sync();
  if(success == -1 || gptr() == egptr()) return traits_type::eof();
  return *(gptr());
}

The idea here is to use this streambuffer with non-blocking io. The IO multiplexer will autonomously call sync and invoke the user-registered callbacks to perform istream-style operations. Simply put, here are some of my questions:

The input streambuffer has certain type of operations called "putback". What is the potentially benefit of using the putback?
The ::read will return 0 when reaching EOF, which is a very useful indicator for signaling the connection status of socket-based IO. What is the best practice to handle this in sync? My current implementation simply skips this.
Any comments that can improve my implementation will be greatly appreciated!


texts: Iterating lists and updating dictionary for corresponding match logic improvement

texts:
I have two lists:

Users - [<UserObject1>, <UserObject2>, ...]
Contributions - [<ContributionObject1>, <ContributionObject2>, ...]

Every ContributionObject further can have single or multiple UserObject in it which are mentioned as person_links here and both the objects that are ContributionObject and UserObject has certain methods and attributes.

UserObject has an attribute affiliation.

I have to check whether UserObject from Users and have the same affiliation to one of the UserObject from ContributionObject from Contributions.

If yes, I have to make a dictionary where key will be the user from Users and value will be an array of ceratin ContributionObject attributes that is title and url.

I am able to do it with the following logic.

I wanted to ask if this logic can be improved further?

If there is another efficient way to do this task, do mention that. Thanks for all the help. :)

conflicts = dict()
for user in users:
    if user.affiliation:
        for contribution in contributions:
            if not conflicts.get(user):
                conflicts[user] = [
                    (
                        contribution.title,
                        contribution.url,
                    )
                    for person in contribution.person_links
                    if user.affiliation in person.affiliation
                ]
            else:
                conflicts[user] += [
                    (
                        contribution.title,
                        contribution.url,
                    )
                    for person in contribution.person_links
                    if user.affiliation in person.affiliation
                ]

I tried to find out better ways to update dict values on SO but they were mostly about updating the existing values(overriding) not about adding(appending) to an existing value.


texts:
I'm learning how to use SequelizeJS.
What i found was that (at least for me) the definition of the DB model was too invasive in my code when creating object.
I was thinking that the user of your model should not have to learn how to use sequelize (or even that i use it at all)
So I created 2 class that add a layer on top of the model, I would want to know if it is normal/OK as the abstraction is already something that Sequelize aim to provide.
I would also welcome critics of my abastraction
Models classes :
import { Sequelize, Model, DataTypes } from 'sequelize';

const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'database.sqlite'
  });

export class User {
    public sqlObject: Promise<UserModel>;

    constructor(
        public username: string,
        public birthdate?: Date,
        public team?: Team
    ) {
        if(team) {
            this.createWithTeam(team);
        }
    }

    private async createWithTeam(team: Team) {
        const sql = await team.sqlObject;
        console.dir(sql);
        (sql as any).createUser({
           username: this.username,
           birthdate: this.birthdate,
        });
    }
}

export class Team {
    public sqlObject: Promise<TeamModel>;

    constructor(
        public name: string
    ) {
        this.sqlObject = TeamModel.findOrCreate({
            where: { name: this.name }
        }).then(([o]) => o);
    }
}

class UserModel extends Model {
    static TeamModel: any;
}
UserModel.init({
  username: DataTypes.STRING,
  birthday: DataTypes.DATE
}, { sequelize, modelName: 'user' });

class TeamModel extends Model {
    static UserModel: any;
};
TeamModel.init({
    name: DataTypes.STRING
}, { sequelize, modelName: 'team' });
TeamModel.UserModel = TeamModel.hasMany(User);
UserModel.TeamModel = UserModel.belongsTo(TeamModel);

Usage :
const team1 = new Team('Belgium Red Devils');
const player1 = new User('Laurent', new Date('01-01-1990'), team1);


texts:
I've just finished work on my guessing game. I'm still fairly new to Python, so I'm looking for feedback and criticism on the code.

def game():

    import random #imports the module 'random'

    yes={"Yes","Y","yes","y"} #set 'yes' to these 4 strings
    no={"No","N","no","n"} #set 'no' to these 4 strings

    name=input("What is your name? \n") #asks for a name

    secret=int(random.random()*10)+1 #randomly generate a number

    trynum=0 #sets the number of tries to 0

    print ("---------------------------------------------------------------------\n"
           "---- Welcome,",name+"!\n"
           "---- I am thinking of a number between 1 and 10.\n"
           "---- Lets see how many times it will take you to guess the number.\n"
           "---------------------------------------------------------------------\n")

    while True: #starts a loop

        trynum=trynum+1 #sets number of tries to itself + 1

        guess=int(input("What is guess #"+str(trynum)+"? \n")) #asks for a guess

        if guess<secret: #if guess is too low/less than(<)
            print ("Too Low. Try again!")

        elif guess>secret: #if guess is too high/greater than(>)
            print ("Oops!! Too high, better luck next try!")

        else:
            if trynum==1: #if number of tries is only 1
                print ("-------------------------------------------------\n"
                       "----",name+"! You got it in",trynum,"guess!\n"
                       "-------------------------------------------------\n")
            else: #if number of tries is anything else
                print ("-------------------------------------------------\n"
                       "----",name+"! You got it in",trynum,"guesses!\n"
                       "-------------------------------------------------\n")

            if trynum<3: #if guessed in less than 3 tries
                print ("Bravo!")

            elif trynum<5: #if guessed in less than 5 tries
                print ("Hmmmmpf... Better try again")

            elif trynum<7: #if guessed in less than 7 tries
                print ("Better find something else to do!")

            else: #if guessed in more than 7 tries
                print ("You should be embarssed! My dog could pick better.")

                choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
                if choice in yes: #if yes, then run game again
                    game()
                if choice in no: #if no, then quit the game
                    print ("Okay.. Goodbye :(")
                    quit
            break
game()


texts:
I've written a simple numeric menu which displays in the console. When the user types in '1', something happens.  When the user hits ENTER, I clear the whole output except for the menu itself. When the user types in '5', the program ends.

However, the code got ugly. It's full of cin.get()s, couts, and other stuff.

int main()
{
    using namespace std;
    node *root = NULL;
    char ch = '0';

    while(ch != '5')
    {
        cout << "1. Add new elements\n"
            "2. Display info about the tree\n"
            "3. Remove nodes\n"
            "4. Export to file\n"
            "5. Exit\n";
        cin >> ch; cin.get();

        switch(ch)
        {
            case '1': case '3':
            {
                vector<int> numbers;
                string line;
                cout << "\nProvide numbers divided with spaces: ";
                getline(cin, line);
                istringstream in(line, istringstream::in);
                int current;
                while (in >> current) numbers.push_back(current);

                (ch == '1') ? insert(root, numbers) : remove(root, numbers);
                cout << "\nClick to return to menu";
                cin.get();
                break;
            }
            case '2':
            {
                displayTreeInfo(root, cout);
                cout << "\n\nClick to return to menu";
                cin.get();
                break;
            }
            case '4':
            {
                string name;
                cout << "Provide filename: ";
                cin >> name;

                buildTree(root, loadNumbersFromFile(name));
                exportTreeToFile(root, name);
                std::cout << "\nData has been exported.\n\n";
                cin.get(); cin.get();
                break;
            }
        }
        system("cls");
    }

    exit(EXIT_SUCCESS);
}

How could I improve this code?


texts: Check if a given number N is a power of k

texts:
I am trying to solve a problem to check whether a given number N is a power of k.

Example:

Input 9, 3  > True //  3**2 = 9
Input 10, 2  > False
Input 4096, 16  > True // 16**3 = 4096

I want to know if there is a better solution for this problem.

def check_Power(N,k):
    if N <= 0 or k <=0:
        print "not a valid input"
    else:
        for i in range (1,20):
            x = k**i
            if x == N :
                print " True "
                print k, "power ", i , "is", N
                break
            elif x> N:
                print "false"
                break

check_Power(244140625,5)
check_Power(4096, 16)
check_Power(0, 16)
check_Power(1,1)


texts: Replicating Bash's command substitution in PowerShell

texts:
I want to be able to use Bash's ^search^replace functionality in PowerShell, the closest I can come is with this function and linking it to the alias ^.

So in Bash I would do:

$ ping google.com
$ ^google^bing

And then I'd get to ping bing without re-writing the command.

In PS with this code I have to do:

> ping google.com
> ^ google^bing

The extra space isn't that big of a deal to me. However, there are some other issues that I'm not sure of how to fix.

If I do a few of the search and replaces in a row, the term is found in a previous command, so it doesn't trigger the error which prevents it from running a random command. IE:

PS H:\> ^ gdsajhfgajhgjf^domain.com
    gdsajhfgajhgjf not found in previous command
...

PS H:\> ^ gdsajhfgajhgjf^domain.com
    gdsajhfgajhgjf not found in previous command
...

PS H:\> ^ gdsajhfgajhgjf^domain.com
    ping domain.com

The commands that are run aren't ever entered into the PowerShell history. So while they run as one would hope, I can't go back and see the commands. I looked through the documentation for get-history, add-history and invoke-history but can't find a way to use those for anything.
I'm not sure if there's better ways to do this, in general. I looked around but can't find anything that looks comparable to this functionality. It seems inelegant to me because of the way PowerShell's history works doesn't insert the command that's actually run, it just inserts ^ search^replace so I have to go back until it finds the last actual command, and then do the search/replace on that.

Anyhow, here's the code:

Function PSReplace {
    param ([string]$SearchAndReplace)

    $SearchTerm = $SearchAndReplace.split("^")[0]
    $Search = $SearchTerm
    $Replace = $SearchAndReplace.split("^")[-1]
    $CommandHistory = Get-History

    $Found = $False
    $CommandCount = -1
    $LastCommand = $CommandHistory[$CommandCount].CommandLine

    if ($LastCommand[0] -ne "^"){
        if ($LastCommand -like "*$SearchTerm*"){
            $Found = $True
        }
    }

    else{
        while ($LastCommand[0] -eq "^"){
            $CommandCount -= 1
            $LastCommand = $CommandHistory[$CommandCount].CommandLine
            $Search = $LastCommand.Split(" ")[1].split("^")[0]

            if ($LastCommand -like "*$SearchTerm*"){
                $Found = $True
            }
        }
    }

    if ($Found -eq $False){
        Throw "$SearchTerm not found in previous command"
    }

    $ReplacedCommand = $LastCommand.Replace($Search, $Replace)
    write-host $ReplacedCommand
    Invoke-Expression $ReplacedCommand
}


texts:
I used jQuery-UI and jQuery to create a dialog popup for help snippets on search form inputs.

HTML (Calling Page)

    Name Search

Script to call dialog

   $("#Help").click(function () {
       $("#dialog-confirm").load("/help/nameSearch.htm").dialog({
           resizable: false,
           height: screen.height - 300,
           position: {
               my: "left top",
               at: "left top",
               of: "#Table1"
           },
           width: '790px',
           height: 'auto',
           modal: true,
           buttons: {
               "Okay": function () {
                   $(this).dialog("close");
               }
           },
           hide: { effect: "drop", direction: "up" },
           show: { effect: "drop", direction: "down" }
       });
   })

   $("#dialog-confirm").keypress(function (e) {
       if (e.keycode == $.ui.keyCode.ENTER) {
           $(this).dialog("close");
       }
   })

This works nicely to load the page from another folder in my site, but I get this weird glitchy feeling on the first time, which is going to probably be the most anyone will use these really awesome popup dialogues. I want them even better.

Is there any way to make it load more smoothly?

I am not opposed to using AJAX.


texts:
This is my first time implementing a merge sort (just getting started with algorithms & data structures).

Are there any obvious things I have done wrong?

I am also worried that I have overused recursion, as both the merge & the sort function are recursive.

function sort(array) {
  var len = array.length;
  var middle = Math.floor(len*0.5);
  var left = array.slice(0,middle);
  var right = array.slice(middle, len);

  if (len == 1) {
    return array;
  } else {

  }

  return merge(sort(left), sort(right));
}

function merge(left, right) {
  var a = left.length;
  var b = right.length;

  if (a > 0 && b > 0) {
    if (left[0] > right[0]) {
      return [].concat(left[0], merge(left.slice(1,a), right));
    } else {
      return [].concat(right[0], merge(right.slice(1,b), left));
    }
  } else if (a == 0) {
    return right;
  } else of (b == 0)
    return left;

}

var array = [];
for(var i = 0; i < 20; i++) {
   array.push(Math.round(Math.random() * 100));
}
console.log(array);
console.log(sort(array));

From the feedback in this question, I have improved my solution, which can be found here.


texts: Database query inside a method of a class and return data

texts:
I'm trying to find out what is the right approach to return DB values from a class. This is what I came up with:

class Category {

  public $result;
  public $errors;

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

  public function getCategoryNames () {

    $sql = "SELECT category_id, category_name FROM category";

    try {
      $query =  $this->pdo->prepare( $sql );

      if( $query->execute( ) ) {
        if( $query->rowCount() ) {
          $this->result = $query->fetchAll();
          return true;
        }
        return false;
      }
      return false;
    } catch ( PDOException $pe ) {
      trigger_error( 'SQL Error' . $pe->getMessage() );
    }
  }

  public function getUserDetails($userid) {
    $sql = "SELECT * FROM users WHERE user_id = :user_id";

    try {
      $query =  $this->pdo->prepare( $sql );

      if( $query->execute( array( 'user_id' => $userid ) ) ) {
        if( $query->rowCount() ) {
          $this->result = $query->fetch(PDO::FETCH_ASSOC);
          return true;
        }
        return false;
      }
      return false;
    } catch ( PDOException $pe ) {
      trigger_error( 'SQL Error' . $pe->getMessage() );
    }
  }

$category = new Category($pdo);
$category->getCategoryNames();
print_r($result);
$category->getUserDetails('1');
print_r($result);

Is this approach good? Or what is the proper way to do this?


texts: What is the shortest snippet that emulates `include` in JavaScript without third-party scripts?

texts:
JavaScript doesn't offer a module system. There are many third-party solutions, like require.js or jQuery's $.getScript. Most, while good, they bring dependencies, extra kbs and/or limit your folder structures. Sometimes it's necessary to make a .js file self-sufficient. This said, what is the smallest snippet that can be inserted at the top of a .js file, which will emulate "import", so it can load other scripts before running itself?

The .js file should look like this, for example. Notice the addition is just a small one-liner:

(function(i,m,p,o,r,t){for(p=i.length,o=0;o<p;++o){r=(t=document).createElement('script');r.src=i[o];r.onload=function(){!--p&&m()};t.head.appendChild(r); }; })
(['http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js','http://underscorejs.org/underscore-min.js'],
function main(){
    console.log('jQuery loaded:',$);
    console.log('underscore.js loaded:',_);
});

For clarity, the top function above, expanded, is equivalent to:

(function (u, f, l, i, a, d) {
        for (l = u.length, i = 0; i < l; ++i) {
            a = (d = document).createElement('script');
            a.src = u[i];
            a.onload = function () {
                !--l && f()
            };
            d.head.appendChild(a);
        };
    })

Can this be minimized even further?


texts: Creating input when checking/clicking radio button

texts:
I'm new to jQuery and played a bit with what can I do with radio button. I want to create ONLY one input type when I click the Notice radio button. I already using many way to achieve this, but this is the only way I can do this, you can see the following code.

HTML

<input type="radio" name="radio1" value="Immediate" /> Immediate

<input type="radio" name="radio1" id="others" value="Notice" /> Notice me in...

jQuery

$(function(){
    $("#others").click(function(){
        while($("#others").val()=="Notice")
        {
            var newElement = $(document.createElement('input')).attr({name:"noticeweeks", id:"noticeweeks"});
            newElement.appendTo("#inputplace");

            $("#others").val("Notice me in...");
        }
    });
});

With that jQuery, I changed the value of the radio button into "Notice me in...", so the while function will stop creating a new element since the value has been changed.

Are there any others way to achieve the same result?


texts:
I have so many classes like this in my solution but I've chosen this one just to show you guys what I mean by it.

In my solution I have lots of classes that just follow the same 2 classes exactly the same, except for the class name and for different purposes.

The issue is, I think I'm OP'ing it. Does something this simple, something I do with around 50 class pairs in my solution really need to take up 2 files and this much code?

It seems like it can be improved but I just can't work out a well-driven way, someone said something about structs but I didn't really look into it too much and it's been too long to remember what else they said.

Is there some sort of layout or structure I can do to reduce the amount of code or the time it takes to code this? I feel like somethings staring me right in the face and I'm missing it.

The purpose of this class pair is to cache database information, store it in a dictionary and return it in case you need it later. It saves an extra call to the database every time I need to get something, and it's just a lot easier to maintain and work with than constant database calls all over the place.

internal class SubscriptionHandler
{
    private readonly Dictionary<int, Subscription> _subscriptions;

    public SubscriptionHandler()
    {
        _subscriptions = new Dictionary<int, Subscription>();
    }

    public void Load()
    {
        using (var dbConnection = Program.Server.DatabaseHandler.Connection)
        {
            dbConnection.SetQuery("SELECT * FROM `subscriptions`;");

            using (var reader = dbConnection.ExecuteReader())
            {
                while (reader.Read())
                {
                    var subscriptionId = reader.GetInt32("id");
                    _subscriptions[subscriptionId] = new Subscription();
                }
            }
        }
    }

    public bool TryGetSubscriptionById(int subscriptionId, out Subscription subscription)
    {
        return _subscriptions.TryGetValue(subscriptionId, out subscription);
    }
}

internal class Subscription
{
    public int Id;
    public string Name;
    public string Badge;
    public int Credits;
    public int Pixels;
    public int Respects;

    public Subscription(int id, string name, string badge, int credits, int pixels, int respects)
    {
        Id = id;
        Name = name;
        Badge = badge;
        Credits = credits;
        Pixels = pixels;
        Respects = respects;
    }
}


texts: TimeSpan don't support years so how do I deal with it? Is there could be smarter solution?

texts:
explain:

from start day till now I've got 7.7 mb size, how long it will be to make it 10 gb size

open System

let dd = (DateTime.Now - DateTime.Parse("12/09/2012")).Days
let oneday = 7.7 / Convert.ToDouble(dd)

let in10gb = Convert.ToInt32( Math.Round (10.0 * 1024.0 / oneday) )
let years = Convert.ToInt32( Math.Round (float in10gb / 365.0) )
let mutable months = Convert.ToInt32( Math.Round (float (in10gb - years * 365) / 30.0) )
let days =
    let d = in10gb - years * 365 - months * 30
    if d > 0 then d else month = month - 1; (30 - d)

printf "%d years %d months %d days" years months days
Console.ReadKey() |> ignore

Also / 30.0 for months is dirty hack here... I'm not sure how to avoid it in easy way.


texts:
I was given an assignment to check for balanced parentheses from an arbitrary string where parentheses are defined as (, [ or { and their respective "closing" parentheses. The other requirement for the assignment was that I had to use either Stack<T> , Queue<T> or List<T>.

Here is my implementation:

private static void CheckParentheses()
{
    Console.Write("Please enter the string you wist to check formity of: ");
    var input = Console.ReadLine();
    var stack = new Stack<char>();

    char[] allowedChars = { '(', '[', '{', ')', ']', '}' };

    foreach (char chr in input)
        if (allowedChars.Any(x => x == chr))
            stack.Push(chr);

    var reverseStack = stack.Reverse();
    var sequencedBalanced = reverseStack.SequenceEqual(stack, BalancedParanthesisComparer.Instance);
    Console.WriteLine("The input string was {0}well formed", sequencedBalanced ? string.Empty : "NOT ");
}

public sealed class BalancedParanthesisComparer : EqualityComparer<char>
{
    private static readonly BalancedParanthesisComparer _instance = new BalancedParanthesisComparer();

    private BalancedParanthesisComparer() { }

    public static BalancedParanthesisComparer Instance { get { return _instance; } }

    public override bool Equals(char x, char y)
    {
        if ((x == '(' && y == ')') || (y == '(' && x == ')'))
            return true;
        if ((x == '[' && y == ']') || (y == '[' && x == ']'))
            return true;
        if (x == '{' && y == '}' || (y == '{' && x == '}'))
            return true;

        return false;
    }
}

I would like general feedback and would also like to know: regarding the use of an EqualityComparer to do something that isn't really equality-checking, is it very bad practice or is it fine?


texts: Batch file that executes multiple .msi files

texts:
I am attempting to create a batch file that will execute multiple msi files in a particular location on our network. My intention is not to have any user interactions until they are prompted to do a reboot. We have an automated tool that I will use to rolls this out, just need some help with the batch file itself. Keep in mind I have minimal experience writing these out, so the syntax could be off. This is what I have so far:

@echo off

:: Intended to update all 3 components prepping it for uninstallation
msiexec.exe /i "\\FileShare\Folder\install1" /QN /L*V c:\temp\update1.log REBOOT=reallysuppress
msiexec.exe /i "\\FileShare\Folder\install2" /QN /L*V c:\temp\update2.log REBOOT=reallysuppress
msiexec.exe /i "\\FileShare\Folder\install3" /QN /L*V c:\temp\update3.log REBOOT=reallysuppress

:: Genaric uninstallation of install1
wmic product where "name like 'Vendor%Product%Configuration'" uninstall

:: Uninstallation of install2
:: Check to see which version is identified within registry and uninstall
:: all versions within {} are registry keys
msiexec.exe " /X {version1} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version2} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version3} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version4} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version5} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version6} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version7} /qn REBOOT=reallysuppress"

:: Uninstallation of install3
:: Check to see which version is identified within registry and uninstall
:: all versions within {} are registry keys
msiexec.exe " /X {version1} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version2} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version3} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version4} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version5} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version6} /qn REBOOT=reallysuppress"
msiexec.exe " /X {version7} /qn REBOOT=reallysuppress"

I hope this information is clear. Please let me know what does or does not make sense and I can answer questions promptly. This is written as a .bat file type.


texts: StringBuilder replacing specific characters

texts:
I want to mask certain parts of an email address, and not to use regex at all.

Example:

  "testing@gmail.com" should become "t*****g@g***l.com"

Where the characters in the email (barring the first and last) become masked out, and no change to the domain.

        String email = "testing@gmail.com";
        StringBuilder sb = new StringBuilder(email);
        int mp = sb.lastIndexOf("@");
        int dp = sb.substring(mp).indexOf(".");
        for (int i = 1; i < sb.length(); i++) {
            if (i != mp && i != mp - 1 && i != mp + 1 && i != ((mp + dp) - 1) && i < (dp + mp)) {
                sb.setCharAt(i, '*');
            }
        }

I know this will fail if something unusual such as an @ in the domain, but that's fine.

It's mainly the if statement that seems awful to me, and wondering if I could shorten it to much simpler logic.

Online Demo


texts: Check if clicked element has specific tagname

texts:
I'm trying to determine whether an element which has been clicked has a specific tagname. The trick is, that sometimes when you click an element you want any parent to be that specific tag.

My approach:

var ignore = 'a input textarea body'.split(' ');

var isClickable = function(elem) {
    var cancel = false;

    for (i in ignore) {
        if (elem.nodeName.toLowerCase() !== ignore[i]) {
            if (elem.parentNode.nodeName.toLowerCase() !== 'body')
                isClickable(elem.parentNode);
        }
        else {
            cancel = true;
            return cancel;
        }
    }

    return cancel;

};

document.onclick = function(evt) {
    isClickable(evt.target);
}

Is that code right or did I forget something?

SOLUTION: I came up to that tiny script based on Guffas solution (thanks!)
I've optimized the code to a shorter and faster version:

var isClickable = function(elem) {
    for (i in ignore)
        if (elem.nodeName.toLowerCase() === ignore[i])
            return true;
    return (elem.parentNode.nodeName.toLowerCase() !== 'body') && isClickable(elem.parentNode);
};


texts:
I made a program to find words in a word grid. It will find words that are horizontal, vertical, positive sloped and vertical sloped, all in both forwards and backwards.
Here is my code:
with open('grid.txt', 'r') as f:
    lst = [[a for a in l.strip() if a != ' ' and a!= '\n'] for l in f.readlines() if l] # Convert file to a nested list, with all whitespaces removed
    lst2 = [a[::-1] for a in zip(*lst)] # Create another nested list that is the first nested list rotated 90 degrees clockwise

height = len(lst) # Height of grid
width = len(lst[0]) # Width of grid

while True:

    word = input("Input your word: ") # Word to find

    # Find horizontal word
    for l in lst:
        w = ''.join(l)
        if word in w or word in w[::-1]:
            print(w)
            print('Horizontal!')

    # Find vertical word
    for l in lst2:
        w = ''.join(l)
        if word in w or word in w[::-1]:
            print(w)
            print('Vertical!')

    # Find Negative slope
    for i in range(width):
        w = ''
        for j in range(height):
            try:
                w += lst[j][i]
                i += 1
            except:
                break
        if word in w or word in w[::-1]:
            print(w)
            print('Negative Slope!')

    for i in range(height):
        w = ''
        for j in range(width):
            try:
                w += lst[i][j]
                i += 1
            except:
                break
        if word in w or word in w[::-1]:
            print(w)
            print('Negative Slope!')

    # Find positive slope
    for i in range(height):
        w = ''
        for j in range(width):
            try:
                w += lst2[j][i]
                i += 1
            except:
                break
        if word in w or word in w[::-1]:
            print(w)
            print('Positive Slope!')

    for i in range(width):
        w = ''
        for j in range(height):
            try:
                w += lst2[i][j]
                i += 1
            except:
                break
        if word in w or word in w[::-1]:
            print(w)
            print('Positive Slope!')

Here is my grid.txt:
n x b z t a ê s e y m t w u e r r
y s j q l n o i l f k j c y h t a
q x n e z d l g v r x y x a p u a
b b k à a y e g q i h u x b q e u
m h z x r é q m x m e l t i b t q
i k i g c j c h w l w i ï t p u o
i s o w u w m a p z a b w g d e p
i p s g u y n n j i j f o f n w l
l i u l ô i e j b e o t s e b c j
y m f v f e v h f c p r d m y v n
f w h v d t z y i x t e e u v n e
e w x e h l x n q m s n p z e f b
e j l v r x ç t d b i a z v d h z
c i i n s s i b s t o q o d d k x
z o f c a w b j b l m w k f e i s

I feel like my code is unnecessarily long for a rather simple task.
Are there any ways to shorten and improve it?


texts: RxJs observables pipes SwitchMap and async with typealong search input

texts:
I'm using RxJs for type along search, I setup an observable to emit a value after 1 second so it behaves like http with delay. I subscribe to it via the async operator in the template, the component has a switchMap to watch the searchTerm observable. Is this how typealong search should be implemented with RxJS?

I've included commented code of how I'd use http, is that how the http observable should be used?

Search Service:

searchTerm(term: string): Observable<Array<ObjectDefinition>> {

   /*
   return this.http.get('http://localhost:8080/api/search?term=abc')
          .pipe(
            map(result => {
              console.log(result);
              return result['body'];
            })
          );
   */

   let observer = new Observable<Array<ObjectDefinition>>((subscription) =>    {

      const timer$ = timer(1000);

      timer$.subscribe(() => {
         console.log('timer 1 second');
         subscription.next(this.objectDefinitions);
      });

   });

   return observer;

}

Testing data:

objectDefinitions = [
    new ObjectDefinition({ name: 'Sydney', description: 'Largest city in Australia'}),
    new ObjectDefinition({ name: 'Melbourne', description: 'City in south of Australia in VIC'}),
    new ObjectDefinition({ name: 'Brisbane', description: 'East coast'}),
    new ObjectDefinition({ name: 'Perth', description: 'West coast'}),
    new ObjectDefinition({ name: 'Adelaide', description: 'Small city in south Australian region'})
  ];

Component consumer:

searchInput = new FormControl();

constructor(private definitionService: DefinitionService) {
   this.definitions = this.searchInput.valueChanges
                     .pipe(
                         tap(value => console.log('input')),
                         //startWith(''),
                         debounceTime(500),
                         distinctUntilChanged(),
                         switchMap(value => this.definitionService.searchTerm(value))
                     )
}

Template using async pipe to subscribe:

<input class="format-input-button"
        (click)="clickInput()"
        [formControl]="searchInput">

{{definition.name}}

{{definition.description}}


texts: Validation class to avoid ugly if-else blocks

texts:
I've answered this question on Stack Overflow. The problem is - there are 30 columns in an Excel sheet and I need to validate each of the fields with different validation logic.  The code should avoid a lot of if-else blocks. I have used strategy pattern to solve this. I would like to get a review of this code.

interface IValidator<T> {
  boolean validate(T field);
}

class SomeFieldOne<T> implements IValidator<T> {
  public boolean validate(T field) {
    System.out.println("SomeFieldOne validation");
    return true; // return true/false based on validation
  }
}

class SomeFieldTwo<T> implements IValidator<T> {
  public boolean validate(T field) {
    System.out.println("SomeFieldTwo validate");
    return true; // return true/false based on validation
  }
}

class Context {
  private IValidator validator;

  public Context(IValidator validator) {
    this.validator = validator;
  }

  public boolean validate(String field) {
    return this.validator.validate(field);
  }
}

public class TestValidation {
  public static void main(String[] args) {
    Context context;

    context = new Context(new SomeFieldOne());
    System.out.println(context.validate("some field one"));

    context = new Context(new SomeFieldTwo());
    System.out.println(context.validate("some field two"));

    // test other fields ....
    // .........
  }
}


texts:
Here I'm trying to learn the Abstract factory pattern. Have referred some examples and trying to mimic the same with some dummy server examples. Please help me to review this.
package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type server interface {
    Query()
    GetContent() string
}

type google struct {
    URL     string
    content string
}

type yahoo struct {
    URL     string
    content string
}

func (g *google) Query() {
    resp, err := http.Get(g.URL)
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    g.content = string(body)
}

func (g *google) GetContent() string {
    return g.content

}

func (g *yahoo) Query() {
    resp, err := http.Get(g.URL)
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    g.content = string(body)

}

func (g *yahoo) GetContent() string {
    return g.content
}

func createFactory(domain string) server {
    switch domain {
    case "google":
        return &google{URL: "https://www.google.com"}
    case "yahoo":
        return &yahoo{URL: "https://www.yahoo.com"}

    default:
        fmt.Println("Invalid domain")
        return nil
    }

}

func main() {
    googleServer := createFactory("google")
    googleServer.Query()
    fmt.Println(googleServer.GetContent())

    yahooServer := createFactory("yahoo")
    yahooServer.Query()
    fmt.Println(googleServer.GetContent())

}


texts: Randomly selecting an adjective and noun, combining them into a message

texts:
This is my first Rust program.  I have previously written a lot of Python, and some C.  I would like some advice on whether I am doing things idiomatically, and any improvements I could make!  I also appreciate any suggestions with regards to style.

The code takes two text files as cmd line args.  One file contains an adjective on each line, the other file contains a noun on each line.  The code reads the files and randomly chooses an entry from each.  It then combines them to give a message in this format, which is printed:

"You are a adjective noun"

For example:

"You are a beautiful avocado"

Here is the code:

extern crate rand;

use rand::Rng;
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

/// Takes file path, returns a vector of strings, each string a line in file.
///
/// # Arguments
/// * `file_path: &Path` - The path to the file to read
///
/// # Return value
/// Returns `Vec<String>` where each string is a line in the file
fn read_lines(file_path: &Path) -> Vec<String> {
    let content = read_file(file_path);
    split_lines(content)
}

/// Takes file path, returns corresponding `File` object.
///
/// # Arguments
/// * `file_path: &Path` - The path to file to read
///
/// # Return value
/// Returns `File` corresponding to `file_path`
fn open_file(file_path: &Path) -> File {
    let display = file_path.display();
    let file = match File::open(file_path) {
        Err(why) => panic!("Couldn't open file {}: {}", display,
                           Error::description(&why)),
        Ok(file) => file,
    };
    file
}

/// Takes `file path, returns string containing the file's content.
///
/// # Arguments
/// * `file_path: &Path` - The path of file to read
///
/// # Return value
/// Returns `String` containing contents of file
fn read_file(file_path: &Path) -> String {
    let mut file = open_file(file_path);
    let display = file_path.display();
    let mut content = String::new();
    match file.read_to_string(&mut content) {
        Err(why) => panic!("Couldn't read file {}: {}", display,
                           Error::description(&why)),
        Ok(content) => content,
    };
    content
}

/// Split a string on newlines and return vector of resulting strings.
///
/// # Arguments
/// * `string: String` - string to be split
///
/// # Return value
/// Returns `Vec<String>`
fn split_lines(string: String) -> Vec<String> {
    string
        .lines()
        .map(ToOwned::to_owned)
        .collect()
}

/// Chooses random adjective and noun from file, combines into message.
///
/// This function does not return the message, but prints it to stdout.
/// The message is in the format "You are a <adjective> <noun>."
///
/// # Arguments
/// * `adj: Vec<String>` - vector of adjectives
/// * `nouns: Vec<String` - vector of nouns
///
/// # Return value
/// ()
fn selfcare(adj: Vec<String>, nouns: Vec<String>) {
    let adjective = rand::thread_rng().choose(&adj).unwrap();
    let noun = rand::thread_rng().choose(&nouns).unwrap();
    println!("You are a{} {}", adjective, noun)
}

/// Print random inspiring message in format "You are a <adjective> <noun>".
///
/// Takes command line args `adj_file` and `noun_file`, respectively the paths
/// to the file containing the adjectives and the containing the nouns.
fn main() {
    let mut args: Vec<String> = env::args().collect();
    if args.len() == 1 {
        args.push("adjectives.txt".to_string());
        args.push("nouns.txt".to_string());
    }
    let adj_file = Path::new(&args[1]);
    let noun_file = Path::new(&args[2]);
    let adj = read_lines(adj_file);
    let nouns = read_lines(noun_file);
    selfcare(adj, nouns)
}


texts:
This function will draw a card in the console

vector<string> draw_card(const Carta& carta){
//The class Carta has two members, carta.value and carta.seme
//both are integers representing the card value or suit
//the card is represented on 9 lines where the second will be the
//card name and suite, while the middle will show a pattern
/*
  |-----------|
  |Asso picche|
  |           |
  |     *     |
  |    * *    |
  |   *****   |
  |  *     *  |
  | *       * |
  |           |
*/

    //card opening and closing line
    string card_delimiter = "|-----------|";

    // vector representing the card
    vector<string> v;

    v.push_back(card_delimiter);

    // construct the second line, so that it will fit different cards names
    // and suites
    string nome_seme = create_semi(carta.seme);
    string nome_valore = create_nome_valore(carta.valore);
    string init_string = "|           |";

    //characters in the init_string will be subsittuted according to the string
    //nome_seme and then after a space nome_valore
    uint valore_offset = 1;
    uint seme_offset = nome_valore.size() + valore_offset + 1;

    for(uint i = 0; i < init_string.size(); ++i){

        if(i >= valore_offset && i < nome_valore.size() + valore_offset){
            init_string[i] = nome_valore[i - valore_offset];
        }

        if(i >= seme_offset && i <= nome_seme.size() + seme_offset - 1){
            init_string[i] = nome_seme[i - seme_offset];
        }
    }

    // update the main vector holding the string
    v.push_back(init_string);

    // initialize the pattern for the center drawing
    vector<uint16_t> middle_matrix;
    middle_matrix.push_back(0x0000); //0      b0000000000000000
    middle_matrix.push_back(0x0400); //1024   b0000010000000000
    middle_matrix.push_back(0x0A00); //2560   b0000101000000000
    middle_matrix.push_back(0x1F00); //7936   b0001111100000000
    middle_matrix.push_back(0x2080); //8320   b0010000010000000
    middle_matrix.push_back(0x4040); //16448  b0100000001000000
    middle_matrix.push_back(0x0000); //0      b0000000000000000

    // scroll through the vector
    for(uint i = 0; i < middle_matrix.size(); ++i){
        string line = "|";
        // bitshift the mask to find if the character will be a space or a *
        for(uint16_t mask = 0x8000; mask != 0x0010; mask >>= 1){
            if(middle_matrix[i] & mask){ line += "*"; }
            else{ line += " "; }
        }
        line += "|";
        v.push_back(line);
    }

    // close the card
    v.push_back(card_delimiter);

    //print the card
    for(unsigned int i = 0; i < v.size(); ++i){
        cout << v[i] << endl;
    }

    return v;
}

I'm posting this for a couple of questions, first of all I'm pretty new to C++ and I would like to know if you would write the whole procedure differently, maybe using replace functions or functions to map the bit pattern.

Second this version will print only one pattern, what would you suggest to do for the other 13?
What I did now was to take a text file, draw the pattern, realize it could be expressed in binary and now I'm here with this integers.

How would you go to maintain clarity? Shall I read in the pattern from a file?
Declare a static array that contains the numbered patterns?
Where shall I place the function that reads the values? or maybe create a class that reads from a "pattern" file and stores them in some member variable, and call it afterwards?


texts:
My use case is to dispatch multiple long-running tasks to execute concurrently. The expectation is that the tasks will be IO-bound (e.g. network requests), but importantly each task is different. This is not a question about data parallelism.

I've written a simple pool type that wraps a sync.WaitGroup and collects any errors that occur.

package gopool

import "sync"

// GoPool is a pool of goroutines with error reporting.
type GoPool struct {
    waitGroup sync.WaitGroup
    errors    chan error
}

// New initializes a new GoPool.
func New() *GoPool {
    return &GoPool{
        waitGroup: sync.WaitGroup{},
        errors:    make(chan error),
    }
}

// Run runs the specified function in a goroutine, collecting any errors that might occur.
func (p *GoPool) Run(goFuncs ...func() error) {
    p.waitGroup.Add(len(goFuncs))
    for _, goFunc := range goFuncs {
        goFunc := goFunc
        go func() {
            defer p.waitGroup.Done()
            err := goFunc()
            if err != nil {
                p.errors <- err
            }
        }()
    }
}

// Wait waits for all specified tasks in the GoPoo to complete, and returns any collected errors that occurred.
func (p *GoPool) Wait() (errors []error) {
    go func() {
        p.waitGroup.Wait()
        close(p.errors)
    }()
    for err := range p.errors {
        errors = append(errors, err)
    }
    return errors
}

Here is an example of how it might be used:

func DoThings()  {
    var thingA int
    var thingB string
    var thingC *Thing

    pool := gopool.New()
    pool.Run(func() (err error) {
        thingA, err = FetchThingA()
        return err
    })
    pool.Run(func() (err error) {
        thingB = FetchThingB()
        return nil
    })
    pool.Run(func() (err error) {
        thingC, err = FetchThingC()
        return err
    })
    errs := pool.Wait()
    if len(errs) > 0 {
        // Handle errs
    }
    // Use each of the fetched things
}

This utility seems pretty useful, but I've not seen anyone write about it. Have I missed a major problem here, or is there a better way to handle this?


texts: Reading a sequence of characters and dynamically splitting into multiple arrays

texts:
I am trying to read a sequence of random characters, integers and symbols from the standard inputstream, split it into 3 separate arrays (uppercase, lowercase and numeric) and print them in that order using standard Java API and JDK7.

Is there any other(better) way of dong the same?

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String characters = bufferedReader.readLine();

char[] chars = characters.toCharArray();
List<Character> characterList = new ArrayList<>(chars.length);

for (char c : chars) {
    if (Character.isUpperCase(c)) {
        characterList.add(c);
    } else if (Character.isLowerCase(c)) {
        characterList.add(c);
    } else if (Character.isDigit(c)) {
        characterList.add(c);
    }
}

StringBuilder uppercaseStringBuilder = new StringBuilder();
StringBuilder lowercaseStringBuilder = new StringBuilder();
StringBuilder numericStringBuilder = new StringBuilder();

for (Character character : characterList) {
    if (Character.isUpperCase(character)) {
        uppercaseStringBuilder.append(character);
    } else if (Character.isLowerCase(character)) {
        lowercaseStringBuilder.append(character);
    } else if (Character.isDigit(character)) {
        numericStringBuilder.append(character);
    }
}

char[] uppercaseChars = uppercaseStringBuilder.toString().toCharArray();
char[] lowercaseChars = lowercaseStringBuilder.toString().toCharArray();
char[] numericChars = numericStringBuilder.toString().toCharArray();

for (char uc : uppercaseChars) {
    System.out.print(uc);
}

System.out.println();

for (char lc : lowercaseChars) {
    System.out.print(lc);
}

System.out.println();

for (char nos : numericChars) {
    System.out.print(nos);
}
}


texts: Regex to match phone numbers, with comments

texts:
Regular expressions are one of the worst aspects of debugging hell. Since they are contained in string literals, It's hard to comment how they work when the expressions are fairly long.

I have the following regular expression:

\b\d{3}[-.]?\d{3}[-.]?\d{4}\b

Source: RegExr.com

I commented it like this:

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String regexStr = "";

        regexStr += "\\b";     //Begin match at the word boundary(whitespace boundary)
        regexStr += "\\d{3}";  //Match three digits
        regexStr += "[-.]?";   //Optional - Match dash or dot
        regexStr += "\\d{3}";  //Match three digits
        regexStr += "[-.]?";   //Optional - Match dash or dot
        regexStr += "\\d{4}";  //Match four digits
        regexStr += "\\b";     //End match at the word boundary(whitespace boundary)

        if (args[0].matches(regexStr)) {
            System.out.println("Match!");
        } else {
            System.out.println("No match.");
        }
    }
}

What would be the best way to go about commenting regular expressions to make them readable for beginners? Is there a better way than what I have shown?


texts:
I need to parse a simple JSON string (flat JSON, no hierarchy) for keys and values, and there is a system constraint that I cannot use any built-in JSON library and can only read a string once due to latency requirements. I need to use Python 2.7.x series and cannot use a higher version.

Currently, my major concern for below code is, I still do a bit more than one pass string parsing, since I need to go backward/forward to remove unnecessary characters around a word, which is what wordBeautify does.

This is a follow-up to "Json String Parsing"

def wordBeautify(word1, beginIndex, endIndex):
    noMeaningChars=[' ', '"', '{', ',', ':','}']
    while word1[beginIndex] in noMeaningChars:
        beginIndex+=1
    while word1[endIndex] in noMeaningChars:
        endIndex-=1
    return (beginIndex,endIndex+1)

def parseElegant2(str1):

    keyStr=''
    valueStr=''
    beginWord = False
    isKey=True
    beginIndex=0
    endIndex=0

    for i in range(len(str1)):

        if str1[i]==':':
            endIndex=i-1
            (x,y) = wordBeautify(str1, beginIndex, endIndex)
            keyStr=str1[x:y]
            print "key string " + keyStr
            beginIndex=i+1
        elif str1[i]==',' or str1[i]=='}':
            endIndex=i
            (x,y) = wordBeautify(str1, beginIndex, endIndex)
            valueStr=str1[x:y]
            beginIndex=i+1
            print "value string " + valueStr
            print 'key and value, '+ keyStr, valueStr

def parseElegant(str1):

    keyStr=''
    valueStr=''
    beginWord = False
    isKey=True
    beginIndex=0
    endIndex=0

    for i in range(len(str1)):

        if str1[i] == '"' and beginWord==False:
            beginWord=True
            beginIndex = i+1
        elif str1[i] == '"' and beginWord==True:
            beginWord=False
            endIndex=i
            if beginIndex<endIndex:
                print "get word, " + str1[beginIndex:endIndex]
        elif str1[i]==':':
            keyStr=str1[beginIndex:endIndex]
        elif str1[i]==',':
            valueStr=str1[beginIndex:endIndex]
            print 'key and value, '+ keyStr, valueStr

if __name__ == "__main__":

    #JSONString = '{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"]}'
    JSONString1 = '{ "id": "1", "name": "A green door", "price": "12.50", "tags": "home green"}'
    JSONString2 = '{ "id": 1, "name": "A green door", "price": 12.50, "tags": "home green"}'

    parseElegant2(JSONString1)
    parseElegant2(JSONString2)


texts:
I'm implementing rsa and aes classes in java, but i have some trouble with the rsa implementation.
Since i have two keys in asymetric encryption, with two different types, i've made two differents methods, one for each. Is there a better/cleaner way to do that?

private static byte[] doCrypto(
        int cipherMode,
        PublicKey publicKey,
        byte[] inputBytes)
        throws CryptoException {
    Cipher cipher;
    byte[] outputBytes;
    try {
        cipher = Cipher.getInstance("RSA");
        cipher.init(cipherMode, publicKey);
        outputBytes = cipher.doFinal(inputBytes);
    } catch (NoSuchPaddingException
            | NoSuchAlgorithmException
            | InvalidKeyException
            | BadPaddingException
            | IllegalBlockSizeException ex) {
        throw new CryptoException("Error doCrypto", ex);
    }
    return outputBytes;
}

private static byte[] doCrypto(
        int cipherMode,
        PrivateKey privateKey,
        byte[] inputBytes)
        throws CryptoException {
    Cipher cipher;
    byte[] outputBytes;
    try {
        cipher = Cipher.getInstance("RSA");
        cipher.init(cipherMode, privateKey);
        outputBytes = cipher.doFinal(inputBytes);
    } catch (NoSuchPaddingException
            | NoSuchAlgorithmException
            | InvalidKeyException
            | BadPaddingException
            | IllegalBlockSizeException ex) {
        throw new CryptoException("Error doCrypto", ex);
    }
    return outputBytes;
}


texts:
Previous question:

Database input script

I'd like this new question reviewed.

    <?php
$mysqli =  new mysqli('localhost','root','','yaztor');
if($mysqli->connect_errno >0){
    die( "problem with the connection");

    }

function fetchTableFieldCount($mysqli , $databaseName , $tableName ) {
    $sql = "SELECT COUNT(`COLUMN_NAME`) AS FieldCount FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`= '$databaseName'  AND `TABLE_NAME`= '$tableName' ";

    if ( ! ( $stmt = $mysqli->prepare($sql) ) ) {
      die("There is an error with mysql preparation statement".$mysqli->error);
    }

    if ( ! $stmt->execute() ) {
      echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    $res = $stmt->get_result();

    if ( $row = $res->fetch_array() ) {
      return $row['FieldCount'];
    }

    return 0;
  }

   function fetchTableFieldName($mysqli , $databaseName , $tableName ) {
    $sql = "SELECT `COLUMN_NAME`  FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`= '$databaseName'  AND `TABLE_NAME`= '$tableName' ";

    if ( ! ( $stmt = $mysqli->prepare($sql) ) ) {
      die("There is an error with mysql preparation statement".$mysqli->error);
    }

    if ( ! $stmt->execute() ) {
      echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    $res = $stmt->get_result();

    while( $row = $res->fetch_array() ) {
     $array []= $row['COLUMN_NAME'];
    }
    return $array;
    return 0;
  }
    function updateDataIntoTable($mysqli, $tableName, $databaseName, $array ,$idFeildName , $idFeildValue) {

        if( ! $tableCoulmnsNames = fetchTableFieldName($mysqli , $databaseName , $tableName ) ){
            die("Error Fetching Table Information");
            }
        $tableColumnsCount = count($tableCoulmnsNames);

        $dataArrayCount    = count($array);

        if ( $tableColumnsCount != $dataArrayCount ) {
          die("Data array does not match table columns count");
        }

        if ( 0 == $dataArrayCount ) {
          return;
        }
          array_push($array,$idFeildValue);

          for ( $i = 0; $i < sizeof($array); $i++ ) {
          $string         =  gettype($array[$i]);
          //taking the first letter; example:  string = s, integer = i
          $a_param_type[] =  $string[0];
        }

        for($i=0;$i<$tableColumnsCount;$i++){
            $tableCoulmnsNames[$i] = "`" . $tableCoulmnsNames[$i] ."`";
        }

        $sql = " UPDATE `$databaseName`.`$tableName` SET ";
        $sql .= implode($tableCoulmnsNames , ' = ?  , ' );
        $sql .= ' = ? ';
        $sql .=" WHERE `$tableName`.`$idFeildName` = ? ";
        echo $sql;
         if ( ! $stmt = $mysqli->prepare($sql) ) {
          die("error in preparation " . $mysqli->error);
        }

         //puting data element type
         array_unshift($array, implode($a_param_type));

         //refrensing values
         for($i=0;$i<sizeof($array) ;$i++){
            $array[$i] = & $array[$i];
            }

        call_user_func_array(array($stmt, 'bind_param'), $array);

          if ( ! $stmt->execute() ) {
          die("Error in executing the query:  " . $mysqli->error);
        }
        return 1;
        }
      $array = array(10, 5 ,"name", "desc", "text", "12-1-2014 01:00", "1");
      updateDataIntoTable($mysqli, "table", "database", $array ,"idFeildname" , $idFeildValue)

    ?>


texts: Building a frequency dictionary from a Pandas dataframe

texts:
I need to make a frequency dictionary from a pandas series (from the 'amino_acid' column in dataframe below) that also adds an adjacent row for each entry in the dictionary (from 'templates' column).

    templates   amino_acid
0   118         CAWSVGQYSNQPQHF
1   635         CASSLRGNQPQHF
2   468         CASSHGTAYEQYF
3   239         CASSLDRLSSGEQYF
4   51          CSVEDGPRGTQYF

My current approach of iterating through the dataframe seems to be inefficient and even an anti-pattern. How can I improve the efficiency/use best practice for doing this?

My current approach:

sequence_counts = {}
seqs= list(zip(df.amino_acid, df.templates))

for seq in seqs:
    if seq[0] not in sequence_counts:
        sequence_counts[seq[0]] = 0
    sequence_counts[seq[0]] += seq[1]

I've seen people the below way, but can't figure out how to adjust it to add each respective 'templates' entry:

sequence_counts = df['amino_acid'].value_counts().to_dict()

Any help/feedback would be greatly appreciated! :)


texts: Abstract the (duplicate?) behavior between "sort" and "replace"

texts:
I have written these two functions that have a similar process.  The first is meant to "split" a string on a given character and the second is meant to "replace-all" instances of a character in a given string.  The behavior between the two seems very similar - can you think of a good way to abstract that behavior into a third, reusable, function?  (which could be executed by calling, for example, (where-found sought-letter searchee-string thing-to-do)).

(defun split (separator splittee)
  (let ((next-index (position separator splittee)))
    (if next-index
      (cons (subseq splittee 0 next-index) (split separator (subseq splittee (1+ next-index))))
      (list splittee))))

(defun replace-all (replacand replacee replacor)
  (let ((next-index (position replacand replacee)))
    (if next-index
      (concatenate 'string (subseq replacee 0 next-index) replacor (replace-all replacand (subseq replacee (1+ next-index)) replacor))
      replacee)))

What do you think?  Is this better than the original code, or is it too complicated?

(defun where-found (sought-letter the-string to-do-onroute to-do-on-leaf)
  (let ((next-index (position sought-letter the-string)))
    (if next-index
      (apply to-do-onroute
         (list (subseq the-string 0 next-index)
           (subseq the-string (1+ next-index))))
      (apply to-do-on-leaf (list the-string)))))

(defun split (separator splittee)
  (where-found separator splittee
           (lambda (pre-string post-string) (cons pre-string (split separator post-string)))
           (lambda (leaf-string) (list leaf-string))))

(defun replace-all (to-be-replaced-string the-patient-string the-replacement-string)
  (where-found to-be-replaced-string the-patient-string
           (lambda (pre-string post-string)
         (format t "pre: ~a post: ~a the-replacement-string: ~a ~%" pre-string post-string the-replacement-string)
         (concatenate 'string pre-string the-replacement-string (replace-all to-be-replaced-string post-string the-replacement-string)))
           (lambda (leaf-string) leaf-string)))

(format t "the cat is here: ~a ~%" (replace-all #\Space "the cat is here" ""))
(format t "the cat is here: ~a ~%" (split #\Space "the cat is here"))


texts: Calculating top position of elements based on their heights

texts:
I have a data representing several elements (that could be rendered at some point as div), composed of y position (property top) and its height (property height).

These elements are always positioned vertically one next/on-top of each others based on their order.

At the moment I am using the following script to calculate their top position accordingly to their height, script works fine but I kindly ask you your revision in order to improve if possible:

Adjustment for speed as I would need interaction over thousand of objects.
Possibility of an alternative approach to solve this problem if you know any.

Example here, please look at the console for final result
http://jsbin.com/xamagidebe/1/

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

    <title></title>
    <style>
    </style>
    <script>
        window.app = {
            data: [
                    { id: 'h', order: 0, top: null, height: 10 },
                    { id: 'c', order: 1, top: null, height: 20 },
                    { id: 'f', order: 2, top: null, height: 30 }
            ],
            start: function () {
                this.data.sort(function (a, b) {
                    if (b.order > a.order) {
                        return 1;
                    }
                });
                var len = this.data.length;
                var i = 0;
                var x = 0;
                var sum = 0;
                while (i < len) {
                    var item = this.data[i];
                    while (x < len) {
                        var itemX = this.data[x];
                        if (itemX.order < item.order) {
                            sum += itemX.height;
                        }
                        x++;
                    }
                    item.top = sum;
                    i++;
                    sum = 0;
                    x = 0;
                }
                this.data.sort(function (a, b) {
                    if (a.order > b.order) {
                        return 1;
                    }
                });
                console.log('after', this.data);
            }
        };

    </script>
</head>
<body onload="window.app.start();">

</body>
</html>


texts:
I have a very simple view that handles touch events and draws accordingly. It's nothing significant, but it does use a bit more CPU than I would like (35%). Again, it is the bare minimum (<90 lines), but I can't really think of a simpler way to draw using user input. What would you change?

import UIKit

class DrawView: UIView {

    var mainImageView = UIImageView()

    var tempImageView = UIImageView()

    var r = CGFloat(0)
    var g = CGFloat(0)
    var b = CGFloat(0)
    var a = CGFloat(1)

    var lineWidth = CGFloat(5)

    var dot = true
    var lastPoint = CGPoint.zeroPoint

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.backgroundColor = UIColor.clearColor()
        self.multipleTouchEnabled = false
        mainImageView.frame = self.frame
        tempImageView.frame = self.frame
        self.addSubview(mainImageView)
        self.addSubview(tempImageView)
    }

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        dot = true
        if let touch = touches.first as? UITouch {
            lastPoint = touch.locationInView(self)
        }
    }

    func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {
        UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0)
        let context = UIGraphicsGetCurrentContext()
        tempImageView.image?.drawInRect(self.frame)

        CGContextMoveToPoint(context, fromPoint.x, fromPoint.y)
        CGContextAddLineToPoint(context, toPoint.x, toPoint.y)

        CGContextSetLineCap(context, kCGLineCapRound)
        CGContextSetLineWidth(context, lineWidth)
        CGContextSetRGBStrokeColor(context, r, g, b, a)
        CGContextSetBlendMode(context, kCGBlendModeNormal)

        CGContextStrokePath(context)

        tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }

    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
        dot = false
        if let touch = touches.first as? UITouch {
            let currentPoint = touch.locationInView(self)
            drawLineFrom(lastPoint, toPoint: currentPoint)
            lastPoint = currentPoint
        }
    }

    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
        if dot {
            drawLineFrom(lastPoint, toPoint: lastPoint)
        }

        UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0)
        mainImageView.image?.drawInRect(self.frame, blendMode: kCGBlendModeNormal, alpha: a)
        tempImageView.image?.drawInRect(self.frame, blendMode: kCGBlendModeNormal, alpha: a)
        mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        tempImageView.image = nil
    }

    func setColor(color: UIColor) {
        let components = CGColorGetComponents(color.CGColor)
        r = components[0]
        g = components[1]
        b = components[2]
    }

    func erase() {
        mainImageView.image = nil
    }

}


texts:
So I made a version for the 0/1 knapsack problem myself (using matrix dynamic programming algorithm). Given a list of items with name, value, and weight, my function computes correctly the optimal value with total weight <= allowed weight.

I don't know if my code is clean and pythonic enough, I would greatly appreciate it if you give me some comments, thanks.

def knapsack(W, items):
    """
    Given a list of items with name, value and weight.
    Return the optimal value with total weight <= allowed weight and
    list of picked items.
    """
    n = len(items)
    k = [[0 for x in range(W+1)] for x in range(n+1)]

    for i in range(n+1):
        for w in range(W+1):
            if i == 0 or w == 0:
                k[i][w] = 0
            elif items[i-1][2] <= w:
                k[i][w] = max(items[i-1][1] + k[i-1][w-items[i-1][2]], k[i-1][w])
            else:
                k[i][w] = k[i-1][w]

    picked = []
    set_trace(k, n, W, items, picked)
    return k[n][W], picked

# find which item are picked
def set_trace(k, n, W, items, picked):
    for i in range(n, 0, -1):
        if k[i][W] != k[i-1][W]:
            picked.append(items[i-1])
            set_trace(k, i-1, W-items[i-1][2], items, picked)
            break

if __name__ == '__main__':
    items = [('A', 1, 1), ('B', 4, 3), ('C', 5, 4), ('D', 7, 5)]
    max_value,  picked = knapsack(7, items)
    print("Maximum value:", max_value)
    print("Name", "Value", "Weight")
    for item in reversed(picked):
        print(item[0], ' '*2, item[1], ' '*3, item[2])

Output:

Maximum value: 9
Name Value Weight
B    4     3
C    5     4


texts: How can I better my URL checker program?

texts:
I made a LinkChecker program which checks URLs from a text file and outputs status into another file like this:

http://valid-url.com;OK
http://invalid-url.com;The remote server returned an error: (404) Not Found.

I have about 1400 URLs in the input file and it takes about 12 minutes to run.

I made it work. In what ways can I achieve rightness and fastness?

public class LinkChecker
{
    static void Main()
    {
        string line = string.Empty;
        string inputFile = @"D:\tmp\links.txt";
        StreamReader file = new StreamReader(inputFile);
        string outputFile = @"D:\tmp\out.txt";

        ClearOutputFile(outputFile);

        while(!string.IsNullOrEmpty(line = file.ReadLine()))
        {
            string currentUrlAndStatus = CheckURL(line);
            if(!string.IsNullOrEmpty(currentUrlAndStatus))
            {
                WriteToFile(currentUrlStatus, outputFile);
            }
        }
    }

    private static string CheckURL(string url)
    {
        string status = string.Empty;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "HEAD";
        request.Proxy = null;

        try
        {
            using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                status = response.StatusCode.ToString();
            }
        }
        catch (WebException ex)
        {
            status = ex.Status;
        }

        return url + ";" + status;
    }

    private static void ClearOutputFile(string file)
    {
        using (Filestream fileStream = File.Open(file, FileMode.Open)
        {
            fileStream.SetLength(0);
        }
    }

    private static void WriteToFile(string message, string filename)
    {
        using(var writer = new StreamWriter(filename, true))
        {
            writer.WriteLine(message);
        }
    }
}


texts:
I am working on a Roman numerals calculator. For an input validity test I'm using this function:

bool isValidRomanNumeral(string& roman){
    // no test for one-digit Roman numeral
    if (roman.size() == 1) return true;
    for(size_t i=0; i<roman.size()-1; i++){
        // each more significant digit is either >= previous digit (II, VI, etc)
        if(toArab(to_string(roman[i])) >= toArab(to_string(roman[i+1])) ||
           // or 5 times smaller than previous digit (IV, XL, CD, etc)
           5*toArab(to_string(roman[i])) == toArab(to_string(roman[i+1])) ||
           // or 10 times smaller than previous digit (IX, XC, CM, etc)
           10*toArab(to_string(roman[i])) == toArab(to_string(roman[i+1])));
        else return false;
    }
    return true;}

Function: int toArab(string roman)

int toArab(string s){
 map<char, int> roman;
 roman['M'] = 1000;
 roman['D'] = 500;
 roman['C'] = 100;
 roman['L'] = 50;
 roman['X'] = 10;
 roman['V'] = 5;
 roman['I'] = 1;
 int res = 0;
 for(int i=0; i<s.size()-1; ++i){
    if(roman[s[i]] < roman[s[i+1]]) res -= roman[s[i]];
    else res += roman[s[i]];
 }
 res += roman[s[s.size()-1]];
 return res;}

Is there something else that can be done for optimization? Is there a better way to check for Roman numeral validity?


texts: Changing state of a light (Uncle Bob's light switch problem)

texts:
I watched Robert Martin's programming 101 video. I'll explain what problem he talks about in the video for those of you who haven't watched it.

Robert Martin is in his house and shows a light switch. If this switch goes up, a light is on. If switch goes down, the light is off. He wrote a code to handle it. This is simple but the situation is getting more complicated when he shows second, third and fourth light switch. All of them change state of the same light. Each of them is dependent on the others. He also shows how to handle it in a code.

Robert Martin explains that this code is not the best solution because there can be a situation when two people come to the same room and they want to turn the light on. He demonstrated that the code he has written doesn't work well because the light doesn't change its state. It's happening because a computer doesn't see simultaneous events. One of them occurs first. That's happening when two people want to turn on the light. It happens simultaneously only from human perspective. For a computer one person changes state of the light first so in fact the state of the light is changed twice. Fortunately Uncle Bob shows how to solve this problem. He measures time elapsed from the last light state change. If the next change is happening in 500 ms, he rejects it. Now when two people want to turn the light on the light is actually on.

Unfortunately implementing above solution breaks a case when one person quickly turns on and turns off the light. Because the second change is happening in 500 ms it is rejected. So it is not possible to quickly turn on and turn off the light. Uncle Bob didn't show how to solve this problem. He left it as a homework.

It took me long to figure it out how can I solve this but finally I've came to a working solution. I'm not sure though if my solution is good or maybe I only think it is good. Can you tell me if I solved the problem correctly or there is a better solution?

Uncle Bob's code looks like this:

void lightLogic() {
    boolean a = switchA.isUp();
    boolean b = switchB.isUp();
    boolean c = switchC.isUp();
    boolean d = switchD.isUp();
    int currentSwitchState = 0;

    int base=10;
    if (a) currentSwitchState += base*base*base;
    if (b) currentSwitchState += base*base;
    if (c) currentSwitchState += base;
    if (d) currentSwitchState += 1;

    int currentTime = millis();
    if (currentSwitchState != lastSwitchState) {
        if (currentTime - lastChangeTime > 500) {
            light.state = !light.state;
            lastChangeTime = currentTime;
        }
    }

    lastSwitchState = currentSwitchState;

}

I introduced a new variable called penultimateSwitchState and I check if the current state of the light equals to penultimate state. If yes, I know that the same switch has been used to change light state so I accept that change:

void lightLogic() {
    boolean a = switchA.isUp();
    boolean b = switchB.isUp();
    boolean c = switchC.isUp();
    boolean d = switchD.isUp();
    int currentSwitchState = 0;

    int base=10;
    if (a) currentSwitchState += base*base*base;
    if (b) currentSwitchState += base*base;
    if (c) currentSwitchState += base;
    if (d) currentSwitchState += 1;

    int currentTime = millis();
    if (currentSwitchState != lastSwitchState) {
      if ((currentTime - lastChangeTime > 500) || (penultimateSwitchState == currentSwitchState)) {
        light.state = !light.state;
        lastChangeTime = currentTime;
      }
      penultimateSwitchState = lastSwitchState;
    }

    lastSwitchState = currentSwitchState;
  }
}


texts:
I am trying to print all the strings given in a N x N Boggle board. Its basically a N x N scrabble-like board where words can be made from a position - horizontally, vertically and diagonally.

Here is my naive implementation. Is this correct? Any hints on optimizations? Any other useful links?

public class BoggleSolver {

    private void solve(String prefix, int i, int j, char[][] Board, boolean[][] marker, int N)
    {
        if ((i < 0) || (j < 0) || (i >= N) || (j >= N)) return;

        if (marker[i][j] == true) return;

        String s = prefix + Character.toString(Board[i][j]);

        // TODO Fictional dictionary that can tell us if
        // a string is a legal word
        if (dict.HasWord(s)) System.out.println(s);

        // Mark current index and traverse horizontal,vertical
        // and diagonal
        marker[i][j] = true;

        solve(s, i, j + 1, Board, marker, N);
        solve(s, i + 1, j, Board, marker, N);
        solve(s, i + 1, j + 1, Board, marker, N);
    }

    public void solve(char[][] Board, int N)
    {
        boolean[][] marker = new boolean[N][N];

        solve("", 0, 0, Board, marker, N);
    }
    public static void main(String[] args) {

        // TODO make board and call solve(board, N)
    }

}


texts:
My code does what I need it to do, but I think I am missing the "right" way to do this with comparing the arrays. Essentially what I need this to do is compare a textbox entry against two different arrays and redirect based on which value matches.

Protected void Button1_Click(object sender, EventArgs e)
{
      string[] str1 = new string[] {"87002", "87001", "87005"};
      string[] str2 = new string[] {"97002", "97003", "97004"};

      for (int i = 0; i < str1.Length; i++)
      {
          string comp1 = str1[i];
          if (comp1 == TextBox1.Text.ToString())
          {
              Response.Redirect("Page1.aspx");
          }
      }

      for (int i = 0; i < str2.Length; i++)
      {
          string comp2 = str2[i];
          if (comp2 == TextBox1.Text.ToString())
          {
              Response.Redirect("Page2.aspx");
          }
      }
      Response.Redirect("Unknown.aspx");
}


texts: Detect loop in linked list (Floyd cycle finding algorithm)

texts:
I have written this code Floyd Cycle finding algorithm. The methods I have used are createLoop() , doesLoopExist(), lengthOfLoop() and insert().
I want to optimise this code and improve using advanced C++.

#include <iostream>

template <class T>
class LinkedList
{
  struct Node
  {
    T data;
    Node * next;
    Node(T value) : data(value), next(nullptr) {}
  };
  Node *head;

public:
  LinkedList() : head(nullptr) {}
  ~LinkedList();
  void insert(T);
  void createLoop(int);
  bool doesLoopExist();
  int lengthOfLoop();
};

template <class T>
void LinkedList<T>::insert(T data)
{
  Node *node = new Node(data);
  Node *tmp = head;
  if(tmp == nullptr)
  {
    head = node;
  }
  else
  {
    while(tmp->next != nullptr)
    {
      tmp = tmp->next;
    }
    tmp->next = node;
  }
}

template <class T>
void LinkedList<T>::createLoop(int n)
{
  Node *tmp = head;
  Node *tail = head;
  for(int i = 0; i < n-1; i++)
  {
    tmp = tmp->next;
  }

  while(tail->next != nullptr)
  {
    tail = tail->next;
  }
  tail->next = tmp;
}

template <class T>
bool LinkedList<T>::doesLoopExist()
{
  Node *slowPtr = head;
  Node *fastPtr = head;

  while(slowPtr && fastPtr && fastPtr->next)
  {
    slowPtr = slowPtr->next;
    fastPtr = fastPtr->next->next;

    if(slowPtr == fastPtr)
    {
      return true;
    }
  }
  return false;
}

template <class T>
int LinkedList<T>::lengthOfLoop()
{
  int count = 0, loopExist = 0;
  Node *slowPtr = head;
  Node *fastPtr = head;
  while(slowPtr && fastPtr && fastPtr->next)
  {
    slowPtr = slowPtr->next;
    fastPtr = fastPtr->next->next;

    if(slowPtr == fastPtr)
    {
      loopExist = 1;
      break;
    }
  }
  if(loopExist)
  {
    fastPtr = fastPtr->next;
    count++;
    while(slowPtr != fastPtr)
    {
      fastPtr = fastPtr->next;
      count++;
    }
    return count;
  }
  return 0;
}

template <class T>
LinkedList<T>::~LinkedList()
{
  Node *tmp = nullptr;
  while(head)
  {
    tmp = head;
    head = head->next;
    delete tmp;
  }
  head = nullptr;
}

int main()
{
  LinkedList<char> ll1;
  ll1.insert('p');
  ll1.insert('r');
  ll1.insert('o');
  ll1.insert('g');
  ll1.insert('r');
  ll1.insert('a');
  ll1.insert('m');
  ll1.insert('m');
  ll1.insert('e');
  ll1.insert('r');

  int nodeNumber = 5;
  //Node number starts from 1

  ll1.createLoop(nodeNumber);
  bool result = ll1.doesLoopExist();
  if(result == true)
  {
    std::cout <<"Loop exist in the Linked List\n";
  }
  else
  {
    std::cout <<"Loop does not exist in the Linked List\n";
  }

  int len = ll1.lengthOfLoop();
  std::cout << "Length of Loop is " << len <<"\n";

  return 0;
}


texts:
I have a units of measure library that I added string formatting to. Here is sample code:

[Test]
public void FormatSpeed()
{
    var speed = Speed.FromMetresPerSecond(1.2);
    using (Thread.CurrentThread.UsingTempCulture(CultureInfo.InvariantCulture))
    {
        Assert.AreEqual("1.20\u00A0m/s", speed.ToString("F2"));
        Assert.AreEqual("1.20 m⋅s⁻¹", speed.ToString("F2 m⋅s⁻¹"));
        Assert.AreEqual("1.2\u00A0m/s", speed.ToString());
        Assert.AreEqual("1.2\u00A0m⋅s⁻¹", speed.ToString("m⋅s⁻¹"));
        Assert.AreEqual("1200\u00A0mm⋅s⁻¹", speed.ToString("mm⋅s⁻¹"));
        Assert.AreEqual("4.32\u00A0km/h", speed.ToString(SpeedUnit.KilometresPerHour));
        Assert.AreEqual("4.3\u00A0km/h", speed.ToString("F1", SpeedUnit.KilometresPerHour));
    }

    var sv = CultureInfo.GetCultureInfo("sv-SE");
    Assert.AreEqual("1,20\u00A0m/s", speed.ToString("F2", sv));
    Assert.AreEqual("1,20 m⋅s⁻¹", speed.ToString("F2 m⋅s⁻¹", sv));
    Assert.AreEqual("1,2\u00A0m/s", speed.ToString(sv));
    Assert.AreEqual("1,2\u00A0m⋅s⁻¹", speed.ToString("m⋅s⁻¹", sv));
    Assert.AreEqual("1200\u00A0mm⋅s⁻¹", speed.ToString("mm⋅s⁻¹", sv));
    Assert.AreEqual("4,32\u00A0km/h", speed.ToString(SpeedUnit.KilometresPerHour, sv));
    Assert.AreEqual("4,3\u00A0km/h", speed.ToString("F1", SpeedUnit.KilometresPerHour, sv));
}

[Test]
public void FormatAngle()
{
    var angle = Angle.FromDegrees(1.2);
    using (Thread.CurrentThread.UsingTempCulture(CultureInfo.InvariantCulture))
    {
        Assert.AreEqual("0.020943951023932\u00A0rad", angle.ToString());
        Assert.AreEqual("1.200°", angle.ToString("F3°"));
        Assert.AreEqual("1.2°", angle.ToString(AngleUnit.Degrees));
        Assert.AreEqual(" 1.2 ° ", angle.ToString(" F1 ° "));
        Assert.AreEqual(" 0.02 rad", angle.ToString(" F2 "));
        Assert.AreEqual("1.200°", angle.ToString("F3", AngleUnit.Degrees));
        Assert.AreEqual("0.02\u00A0rad", angle.ToString("F2", AngleUnit.Radians));
    }

    var sv = CultureInfo.GetCultureInfo("sv-SE");
    Assert.AreEqual("0,020943951023932\u00A0rad", angle.ToString(sv));
    Assert.AreEqual("1,200°", angle.ToString("F3°", sv));
    Assert.AreEqual("1,2°", angle.ToString(AngleUnit.Degrees, sv));
    Assert.AreEqual(" 1,2 ° ", angle.ToString(" F1 ° ", sv));
    Assert.AreEqual(" 0,02 rad", angle.ToString(" F2 ", sv));
    Assert.AreEqual("1,200°", angle.ToString("F3", AngleUnit.Degrees, sv));
    Assert.AreEqual("0,02\u00A0rad", angle.ToString("F2", AngleUnit.Radians, sv));
}

1) What overloads make sense and what are missing if any?

2) I'm really not sure about if adding composite formats like F2 m⋅s⁻¹ where F2 is for the scalar value and m⋅s⁻¹is for the unit is a good idea.

3) Is nobreaking space \u00A0 the best choice?


texts: Loading and parsing WinForms menus using LINQ

texts:
I'm refactoring a WinForms utility program for building and testing regular expressions. The program has a menu item which lists the RegexOptions enumeration, allows the user to checkmark the items they want, and then those settings are applied during regex testing.

I'm rather new to LINQ, and I'd like to learn the best way to do this.  At present the differences between .Cast<> and .OfType<>, .Where() and .Any() and .All() are rather ambiguous to me.

This is the code I'm using to load the menu-

menuRegexOptions.MenuItems.AddRange(
    Enum
    .GetValues(typeof(RegexOptions))
    .Cast<RegexOptions>()
    .Where(
        s => s != RegexOptions.None
    )
    .Select(
        p => new MenuItem(null, option_Click)
        {
            Text = p.ToString(),
            Tag = p
        })
    .ToArray()
    );

It works and is readable, but I'm keen to know if I've missed any fundamentals or can make it more efficient.

To determine the current Regex setting, the checkmarked menu items must be combined using a bitwise OR operation.  The best solution I could come up with is-

public RegexOptions SelectedRegexOptions
{
    get
    {
        RegexOptions options = RegexOptions.None;

        mnuRegexOptions.MenuItems
            .Cast<MenuItem>()
            .Where(
                x => x.Checked
            )
            .ToList()
            .ForEach(
                s => {
                    options |= (RegexOptions)s.Tag;
                }
            );

        return options;
    }
}

It works, but it feels like I should be able to do the != operation internally to the LINQ and then simply return the result, without the need for the external options variable.

Is there a better way?


texts:
My code works perfectly but it is redundant. How does one condense this? How do you use the =! operator? Any help would be greatly appreciated.

$("#about").click(function(){
  $( ".home" ).hide();
  $( ".headr" ).show();
  $( ".about" ).show();
  $( ".skills" ).hide();
  $( ".experience" ).hide();
  $( ".education" ).hide();
  $( ".examples" ).hide();
  console.log("about clicked");
});

$("#skills").click(function(){
  $( ".home" ).hide();
  $( ".headr" ).show();
  $( ".about" ).hide();
  $( ".skills" ).show();
  $( ".experience" ).hide();
  $( ".education" ).hide();
  $( ".examples" ).hide();
  console.log("skills clicked");
});

$("#experience").click(function(){
  $( ".home" ).hide();
  $( ".headr" ).show();
  $( ".about" ).hide();
  $( ".skills" ).hide();
  $( ".experience" ).show();
  $( ".education" ).hide();
  $( ".examples" ).hide();
  console.log("experience clicked");
});

$("#education").click(function(){
  $( ".home" ).hide();
  $( ".headr" ).show();
  $( ".about" ).hide();
  $( ".skills" ).hide();
  $( ".experience" ).hide();
  $( ".education" ).show();
  $( ".examples" ).hide();
  console.log("education clicked");
});

$("#examples").click(function(){
  $( ".home" ).hide();
  $( ".headr" ).show();
  $( ".about" ).hide();
  $( ".skills" ).hide();
  $( ".experience" ).hide();
  $( ".education" ).hide();
  $( ".examples" ).show();
  console.log("examples clicked");
});


texts: Drag and drop selected array items in Javascript

texts:
I've written a function that moves selected items from a list into a new position. I've found that in order to do this, I need to retain the original 'index structure' of the array. The way I've done this is, instead of splicing the array right away, I set the elements to null, then later traverse the list backwards and splice the null elements. I don't know if this is the best way of doing this, but I thought I would post it here to see if anyone else has an idea of how to better accomplish this.

https://jsfiddle.net/g407pjbk/1/

function drag_and_drop(list, before_index){
    const selected = [];

    for(let index in list){
        const item = list[index];

        if(item.selected){
            selected.push(item);

            // Set elements to null in order to retain indecies
            list[index] = null;
        }
    }

    // Insert selected items
    list.splice(before_index, 0, ...selected);

    // Backwards traverse and splice remaining null elements
    for(let i=list.length-1;i>=0;i--){
        if(list[i] == null)
            list.splice(i, 1);
    }

    return list;
}


texts:
I have been working on a linked list for some while now and started out with this.

Is my code clean? Or is there some way to make it better and more readable?

The reason for this question is for me to be a better programmer. I would love to get one step further for making more clean code.

my class:

using namespace std;

class Node
{

public:
    int nX;
    Node *next;
    //constructor
    Node(){ head = NULL; }          //Initialising head to NULL
    void addValueLeft(int nVal);
    void addValueRight(int nVal);
    void deleteValueLeft();
    void deleteValueRight();
    void printList();
private:
    Node *head;   //a pointer to the first Node
};

my main:

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace std;
    //creating a new object
    Node list;

    list.addValueLeft(5);
    list.addValueLeft(6);
    list.addVaueRight(8);
    list.deleteValueRight();
    list.printList();

    return 0;
}

my functions:

    void Node::addValueLeft(int nVal)
    {
        Node *newNode = new Node;
        if(!head)
        {
            newNode->nX = nVal;
            newNode->next = NULL;
            head = newNode;
        }
        else
        {
            newNode->nX = nVal;
            newNode->next = head;
            head = newNode;
        }
    }

    void Node::printList()
    {
        if(!head)       //list is empty - nothing to print
        {
            //cout << "nothing to print - list empty " << endl;
        }
        else
        {
            Node *tempNode = new Node;
            tempNode = head;
            while(tempNode)
            {
                cout << tempNode-> nX << endl;
                tempNode = tempNode->next;
            }
        }
    }

    void Node::addValueRight(int nVal)
    {
        Node *tempNode1 = new Node;

        if(!head)                   //List is empty
        {
            tempNode1 -> nX   = nVal;
            tempNode1 -> next = head;
            head = tempNode1;
        }
        else
        {
            tempNode1 = head;
            while(tempNode1 -> next != NULL)        //Go to last Node
            {
                tempNode1 = tempNode1->next;

            }
            Node *tempNode2 = new Node;         //create temp node
            tempNode2 -> nX = nVal;
            tempNode2 -> next = NULL;
            tempNode1 -> next = tempNode2;   //tempNode1 will be last Node
    }
    }

    void Node::deleteValueLeft()
    {
        if(!head)       //list is empty - Nothing to Delete
        {
            //cout << " deleteValueLeft:  Nothing to delete" << endl;
        }
        else
        {
            head = head->next;
        }
    }

    void Node::deleteValueRight()
    {
        if(head == NULL)    //Nothing to delete
        {
            //cout << "Nothing to delete " << endl;
        }
        else
        {
            Node *tempNode1 = new Node;
            Node *oldNode = new Node;
            tempNode1 = head;
            if(tempNode1->next == NULL) //only one element
            {
                head = NULL;
            }
            else
            {
                while(tempNode1->next!=NULL)        //Go to last Node
                {
                    oldNode = tempNode1;
                    tempNode1 = tempNode1->next;

                }
                oldNode->next = NULL;
            }
        }

    }


texts:
Using Rails 4 and a simple form, I'm rendering a couple of forms outside of their native controllers. Rather than scattering initialisers through my controllers, I wondered if it is cleaner to do the following:

<%= simple_form_for @event_submission || EventSubmission.new do |f| %>


texts: Should I pass a list of objects or an object to a domain object method?

texts:
I am developing a registration portal for a gym.  When a user registers; a list of sports are recommended based on their age; sex; fitness level etc.  Here is the tables in the database:

CREATE TABLE Person (ID int, name varchar(100), dateofbirth datetime, Gender char(1), primary key (ID))
CREATE TABLE Sport (ID int, description varchar(30), primary key (ID))
CREATE TABLE PersonCanPlaySport (Person ID int references Person(ID), SportID int references Sport(ID), PRIMARY KEY (SportID, PersonID))

The tables show what sports a person can participate in. Now see the class below:

public class Person
{
   public List<Sport> Sports;

   public Person()
   {
     Sports = new List<Sport>();
   }

   public void AddSports(List<Sports> allSports)
   {
      Sports.Clear();
      ((List<Sport>)Sports).AddRange(allSports
      .Where(sport => sport.CanPlay(this)));
   }

}

This works very well.  However, in this question: https://softwareengineering.stackexchange.com/questions/361040/can-two-objects-have-multiple-types-of-relationships (under question comments); a user critics the design but does not really explain why.  What is "wrong" with the design? Should I be passing single Sport objects to Person.AddSports similar to how James does it in his answer here: https://stackoverflow.com/questions/1103693/how-to-model-a-many-to-many-relationship-in-code/1103862?noredirect=1#comment81696466_1103862?