Comments

You should use // comments for single-line comments.

I am not sure you are using comments properly. Comments shouldn't explain how, it should explain why.

/* Prototype for drop_Balls, int parameter is number of balls being dropped */
void drop_balls(int);

One can see that this is a prototype. void drop_balls(int number_of_balls); would probably provide as much information in a more compact way.

/* Return the number of balls that will be dropped */
return num_balls;

This does not look like a useful comment to me.

/* Keeps track of how many balls landed where */
int ball_count[21];

A bit of explanation on the 21 here would be useful... but it is not provided.

This leads me to the next section:

Magic numbers

You probably don't want to have hard-coded numbers all over the place. You could create a constant with value 21 and then:

starting_point = 10 would become starting_point = N /2.
for(x = 0; x < 20; x+2) would become for(x = 0; x < N; x+2).
int ball_place = -10; would become int ball_place = - N/2;

Code organisation

It would probably be better now to call srand in rand_balls as it shouldn't be its responsibility. You can do it from main() if you want.

Define variable in the smallest possible scope. For instance:

for(int ball_num = 0; ball_num < num_balls; ball_num++ )

Also, how is this loop:

for(starting_point = 10; starting_point > 0; starting_point--)

supposed to behave?  Don't we always have the variable set to 0 or -1 at the end?


Correcting punctuation spacing in a string

I would split it into three stages, and two concepts.

Conceptually, split the problem into:

String manipulation (reading and writing)
Logical problems (what exists and what needs doing)

The stages the process might be split into:

The first stage involves reading the string, parsing it from beginning to end, recording the logical aspects of what exists.
The second stage involves manipulating the logical record that represents the tokens, transforming it from a representation of what exists, to a representation of what string manipulations are required.
The third stage is executing the string manipulation.


You can move helper methods to ApplicationHelper and simply include it in Application controller, so your code will look like:

ApplicationController:

class ApplicationController < ActionController::Base
  include ApplicationHelper
  protect_from_forgery with: :exception

  private
    def current_role
        current_role = current_user.nil? ? 'Not logged in' : Role.find(current_user.role_id).name
    end

    def require_new_operation_permission
      check_permission('representative', 'agent')
    end

    def check_permission(*roles)
      unless roles.include? current_role
        flash[:alert] = "Access denied"
        redirect_back(fallback_location: authenticated_root_path)
      end
    end
end

ApplicationHelper:

module ApplicationHelper
  # Roles detection helpers
  def is_admin?
    current_role == 'admin' ? true : false
  end

  def is_representative?
    current_role == 'representative' ? true : false
  end

  def is_shipper?
    current_role == 'shipper' ? true : false
  end

  def is_agent?
    current_role == 'agent' ? true : false
  end

  def is_pricing_representative?
    current_role == 'pricing_representative' ? true : false
  end

  # Devise helpers
  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def resource_class
    User
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end

  # Operation helpers
  def is_operation_completed?(operation_id)
    GeneralCargoInfo.find_by(operation_id: operation_id).nil? ? false : true
  end

  # FCL-EXW helpers
  def is_fcl_exw_info_stage_completed?(operation_id)
    FclExwCargoInfo.find_by(operation_id: operation_id).nil? ? false : true
  end

  def is_fcl_exw?(operation_id)
    Operation.find(operation_id).modality == 'FCL - EXW' ? true : false
  end

  def is_fcl_exw_info_requested?(operation_id)
    Operation.find(operation_id).fcl_exw_info_requested
  end

  def is_fcl_exw_info_confirmed?(operation_id)
    Operation.find(operation_id).fcl_exw_info_confirmed
  end

  def is_fcl_exw_quotation_confirmed?(operation_id)
    Operation.find(operation_id).fcl_exw_quotation_confirmed
  end
end


Summation and product functions using functional paradigm

The start parameter of accumulate is a bit misleading.
My first thought was that start is the first element of the sequence,
but it's an accumulated value.
A more common name is acc or accum.

Reassigning function parameter is considered a bad practice,
in any language as far as I remember.
It's basically reusing an input variable for one additional purpose.
start is an input to your function,
but when you reassign it, it becomes something else:
instead of being just the input,
now it carries the result of a calculation.
When you look at your function body,
the variable start is sometimes the input,
sometimes the result of a local calculation.
This duality in purpose can be confusing and can lead to errors.
It's cleaner to assign the mutated value to a completely new local variable.

In this version, acc always has the same value,
there can be no confusion and misuse, it's perfectly clear:

def accumulate(combiner, acc, n, term):
    """Return the result of combining the first n terms in a sequence."""
    if n == 0:
        return acc
    else:
        next_acc = combiner(term(n), acc)
        return accumulate(combiner, next_acc, n-1, term)

The benefit may not be obvious in this simple function,
but I hope you see the truth in the principle of not reusing parameter variables.
In a longer, more complicated function the benefits would become more clear.

In languages that have out-parameters,
re-assignment of parameters forces me to double-check the signature.
Although Python doesn't have out-parameters,
I still review code like this with suspicion,
in case the author may have mistakenly believed that the re-assigned value will produce a side effect outside the function.
This may sound a bit paranoid, but I've seen this kind of thing happen more than once.
By not re-assigning parameters,
all suspicions are cleared, and the code is easier to review.

For the record, I was tempted to suggest to drop the else clause there,
to simplify to:

def accumulate(combiner, acc, n, term):
    """Return the result of combining the first n terms in a sequence."""
    if n == 0:
        return acc
    next_acc = combiner(term(n), acc)
    return accumulate(combiner, next_acc, n-1, term)

But then, most functional languages return the last evaluation,
and explicit return statements are not recommended,
which makes if-else necessary.
For example the Scala solution would look something like this:

def accumulate(combiner, acc, n, term): Int = {
    if (n == 0) {
        acc
    } else {
        val nextAcc = combiner(term(n), acc)
        accumulate(combiner, nextAcc, n-1, term)
    }
}

So using the explicit else clause is closer to the spirit of functional programming, so I'd leave that as you did.


Sendgrid + Mako email templates quick code review

Here a few things I spotted (not necessarily design related):

vars is a builtin, and should be avoided as a variable name.  Many template systems call this the context (what you are calling vars), so that's probably a better name.
Defaulting function parameters to mutable objects (as you do in the line below) is dangerous (can produce unexpected results, if you're not familiar with how python handles function-param defaults).  See Why are default arguments evaluated at definition time in Python? For more information.

def __init__(self, addr_from, subject,context={},text="",

Instead, you should do something like this:

def __init__(self, addr_from, subject, context=None, text="",
             temp_path=None, temp_filename=None):
    context = context or {}

I'm not sure the if temp_path ... / return "" is the best design.  It took me a bit longer than it should to figure out why you were doing that.  One alternative would be to move the conditional into the __init__ function, so it doesn't look like an error is being handled with return "".


My first observation was - without actually reading anything - WOW that's a lot of code for such a simple task.

Then after the first read-through I was confused because I couldn't say if this was due to over-engineering or under-engineering.

It looks over-engineered because it includes a lot of (possibly unnecessary?) functionality (things like a "huge" menu system and Unicode normalization) just for demonstrating Caesar's. OTOH it looks under-engineered, because there is a lot of very verbose code and repetition.

I'll concentrate on the actually encryption class first.

A glaring problem here, is that you are missing the point of object-oriented programming. Having a class that you just instantiate to do one thing and then destroy it again isn't really the point of OOP.

It would be more sensible to have a class that, once instantiated, is used multiple times. Something like this:

CaesarCypher cypher = new CaesarCypher();

System.out.println(cyhper.encrypt("Example"));
System.out.println(cyhper.decrypt("Fybnqmf"));

The next problem would be the interface. Passing the information if you want to encrypt or decrypt as a String is very problematic, especially since those strings are tightly coupled to your menu.

Imagine this were a real production encryption system: The menu is changed in some way (for example, menu items are renumbered or translated), but the developer doing it doesn't know that requires changing the encryption class, or there is simply a small typo in one of the strings, then there will be no way to know something is wrong. The class doesn't report any errors, instead it just sends out everything unencrypted, which is potentially catastrophic.

Instead you should be using a parameter that only allows two possible values to represent encryption and decryption, for example a boolean or an enumeration:

enum CyperDirection { ENCRYPT, DECRYPT; }

Or use two separate methods as I did in the example above.

And even is you do use a String, then you shouldn't be calculating the "integerDependOnAction" inside the loop, but just once at the start.

The ALPHABET variable should actually be a constant (a final static field) in the class.

On to the actual algorithm:

A StringBuilder isn't really needed here. Internally a StringBuilder is just a char array, that is "automatically" extended if needed. But since you know how long the resulting string will be you don't need the automatic extending, so either at least initialize the StringBuilder with a capacity (new StringBuilder(userSentence.length())) or (because you are working character by character anyway) just use a char array of the correct length.

Your outer loop would be nicer as for (int i = 0; i < userSentence.length(); i++) { - just as you did in the inner loop. And don't forget proper formatting: a space after the for keyword and before the opening bracket.

Inside the loop you have a bug: the condition j == 25 can never be true.

In the end the class could look something like this:

class CaesarCypher {
    private static final char[] ALPHABET = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

    private int shift;

    // This is just an example, why not to use a "one time" class: You can
    // configure it - in this case by allowing a different size shift.
    public CaesarCypher(int shift) {
        if (shift <= 0) {
            throw new IllegalArgumentException("shift must be a positive integer greater than zero.");
        }
        this.shift = shift;
    }

    public CaesarCypher() {
        this(1);
    }

    public String encrypt(String text) {
        return translate(text, this.shift);
    }

    public String decrypt(String text) {
        return translate(text, -this.shift);
    }

    private String normalize(String text) {
        return Normalizer.normalize(text, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "").toLowerCase();
    }

    private String translate(String text, int shiftBy) {

        String normalizedText = normalize(text);

        char[] result = new char[normalizedText.length()];

        for (int i = 0; i < normalizedText.length(); i++) {
            for (int j = 0; j < ALPHABET.length; j++) {
                if (normalizedText.charAt(i) == ALPHABET[j]) {
                    result[i] = ALPHABET[(j + shiftBy) % ALPHABET.length];
                    break;
                }
            }
            // 0 is the default value for char. If the current element of the
            // result array is still zero, then original character wasn't in the
            // ALPHABET. In this case just use the original character.
            if (result[i] == 0) {
                result[i] = normalizedText.charAt(i);
            }
        }

        return new String(result);
    }
}

Finally a few short words the menu system: The nested ifs and long conditions ((cypherMethod.equals("1") || cypherMethod.equals("caesarcypher"))) makes the code very unreadable.

If the goal of this exercise was to show case the Caesar's cypher, then you may want to "cut back" on the menu system and use tests to demonstrate your code.

But if you consider the menu part of the exercise then you should consider maybe building a "proper" small framework to make the menu system more readable and maintainable.


Linear in space

Both are linear in space.

The first one is linear because the StringBuilder makes a copy of the string.

The second one is linear because toCharArray makes a copy of the string.  We know it can't use the backing array of the string, because the string is immutable.  Clearly you can modify the character array.  We can ignore the swap variable (c), as it is either constant space or

We can consider a Java compiler (even if none currently work this way) that would release the backing array to the toCharArray, but we can't guarantee that.  Because the calling code may want to use the string after calling this method.  So the assumption in the method is that we are creating a new array.

If the input is a string and the output is a different string (and we can't change the original string, so it has to be different), then linear time is the best we could possibly do.  So even without the intermediate variable, these would still be linear in space.  Both create new strings.

Linear in time

Both are linear in time.

The first one does \$n\$ iterations with one append operation per iteration.  The append operations should be constant time.  There may be occasional copy operations that can be amortized to be constant time per append operation or linear time overall.  That's \$\mathcal{O}(n)\$.

The second one does \$\frac{n}{2}\$ iterations with two array assignments per iteration.  That's also linear, \$\mathcal{O}(n)\$.  Because \$\frac{n}{2}\$ grows linearly with \$n\$ and two is a constant.

Constant space

To have a method be constant in space, it needs to return the same memory that brings the input.  E.g.

public void reverse(char[] chars) {
    for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }
}

This is constant in space and linear in time.  But it neither takes nor returns a string.

Constant space and time

There's a sort of backwards way of reversing a string in constant time and space.

class ReversedString {

    private String string;

    public ReversedString(String string) {
        this.string = string;
    }

    public char charAt(int index) {
        return string.charAt(string.length() - 1 - index);
    }

}

But we wouldn't be able to just use this as a string without creating a new string.  The only operation that works (so far) is charAt.  We might be able to make other operations work, but not all of them.  In particular, a toString would be linear in time and space, just like the original methods.  Because it would have to make a new string of the same length.


The for-case paradigm is an anti-pattern, you shouldn't use it. One alternative would be to initialize the array in a static block (without for-switch), another would be to use an enum. I would prefer the second approach. Both approaches would save you the call of TileMaker.setTile().
Your indent style is not customary in Java, and it's always best to go with what most programmers of a language are used to (opening curly bracket on the same line).
Your variable names are not very clear. What is the difference between posX and x? And what is sx?
Get rid of unused fields. If you don't need mapSize, don't save it.
Move magic numbers out of your code into static fields.
I would create a separate class for the parsing of the file.


Trim leading zeroes from second component of a string

The biggest thing I can see, which may or may not be an issue, is the manner in which you process the strings.

    if (code.Contains('.'))
    {
        var prefix = code.Split('.')[0];
        var subCode = code.Split('.')[1].TrimStart('0');
        codes.Add(prefix + '.' + subCode);
    }
    else
    {
        codes.Add(code);
    }

This could be rewritten as:

var codeSections = code.Split('.');
var code = codeSections[0];

if (codeSections.Length == 2)
    code += "." + codeSections[1].TrimStart('0');

codes.Add(code);

This saves you LoC, and probably makes it faster. (You could also possible make this a StringBuilder as well.) And in my opinion, this is more readable/concise/descriptive.

Another alternative:

code = code.Replace(".0", ".");

Both should have the same effect on the cases you provided.

However, if, for whatever reason, one of the cases ends up as 46.00, then the second method will only make it 46.0. Choose that method with great caution.

As the OP pointed out in an edit that should have been a comment, this code can all be done as LINQ:

var codes = codesWithSubCodes.ConvertAll(code => code.Replace(".0", "."));


The class unfortunately violates the Single Responsibility Principle because it has to deal with logging as well as expiring access.

You could use the Decorator Pattern here and split the authorization and logging into separate classes as follows:

public interface IAccessWidget
{
   string AccessReason { get; }
   void SetAccessReason(string reason);
   void ExecuteOperation(Action operation, Action onPermissionExpired, Action<Exception> onError);
}

public class AccessWidget
{
    private readonly TimeSpan _permissionDuration;
    private DateTime _permissionExpiry = DateTime.MinValue;

    public string AccessReason { get; private set; }

    public AccessWidget(TimeSpan permissionDuration)
    {
        _permissionDuration = permissionDuration;
    }

    private bool CheckPermission()
    {
        return DateTime.UtcNow < _permissionExpiry;
    }

    public void SetAccessReason(string reason)
    {
        AccessReason = reason;
        _permissionExpiry = DateTime.UtcNow.Add(_permissionDuration);
    }

    public void ExecuteOperation(Action operation, Action onPermissionExpired, Action<Exception> onError)
    {
        if(CheckPermission())
            onPermissionExpired();
        try
        {
            operation();
        }
        catch(Exception exception)
        {
            onError(exception);
        }
    }
}

public class LoggingAccessWidget : IAccessWidget
{
    private readonly IAuditDatabase _auditDatabase;
    private readonly IAccessWidget _widget;

    public string AccessReason { get { return _widget.AccessReason; } }

    public LoggingAccessWidget(IAccessWidget widget, IAuditDatabase auditDatabase)
    {
        _widget = widget;
        _auditDatabase = auditDatabase;
    }

    public void SetAccessReason(string reason)
    {
       _widget.SetAccessReason(reason);
    }

    public void ExecuteOperation(Action operation, Action onPermissionExpired, Action<Exception> onError)
    {
        _auditDatabase.Log(_widget.AccessReason);
        _widget.ExecuteOperation(operation, onPermissionExpired, onError);
    }
}


Group by lastName and variable firstName

If you have a simple groupBy function, and group by a string key with format [lastName]|[firstNameKey or firstName], it'd be cleaner. The following is my version of the code:

// FUNCTIONS
const groupBy = (list, key) => {
  return list.reduce((current, value) => {
    (current[key(value)] = current[key(value)] || []).push(value);
    return current;
  }, {});
};

const mapDictionary =
  (str) => str
  .split(';')
  .map((val, idx) => {
    return {
      grp: idx + 1,
      val: val
    };
  })
  .reduce((current, group) => {
    const groupResult = group.val
      .split(',').reduce((gr, name) => {
        gr[name.trim().toLowerCase()] = group.grp;
        return gr;
      }, {});
    return {
      ...current,
      ...groupResult
    };
  }, {});

const groupDuplicate = (people, dictionary) => {
  return Object.values(groupBy(people, (person) => `${person.lastName}|${dictionary[person.firstName.toLowerCase()] || person.firstName}`));
};

// TEST CASE
const FIRST_NAME_DICTIONARY =
  "Robert, Bob, Bobby; Liz, Elizabeth, Beth; Tom, Thomas";

const people = [{
    firstName: "robert",
    lastName: "smith"
  },
  {
    firstName: "Liz",
    lastName: "thomas"
  },
  {
    firstName: "robert",
    lastName: "smith"
  },
  {
    firstName: "Thomas",
    lastName: "hardin"
  },
  {
    firstName: "Elizabeth",
    lastName: "thomas"
  },
  {
    firstName: "bob",
    lastName: "smith"
  },
  {
    firstName: "Bobby",
    lastName: "smith"
  },
  {
    firstName: "ryan",
    lastName: "roberts"
  },
  {
    firstName: "bob",
    lastName: "wallace"
  },
  {
    firstName: "bobby",
    lastName: "smith"
  },
  {
    firstName: "beth",
    lastName: "roberts"
  },
  {
    firstName: "beth",
    lastName: "thomas"
  },
  {
    firstName: "Tom",
    lastName: "hardin"
  },
];

const result = groupDuplicate(people, mapDictionary(FIRST_NAME_DICTIONARY));

// PRINT RESULT
console.log(result)


Returning information about searches performed by a user

The code is readable enough and to the point, there is not much to improve. I would just extract date retrieval into its own function so there is no risk of slightly mistyping the format, for instance; and change the formating of the output dict to improve readability:

import datetime
from accounts.models import UserProfile

def extract_date(request, parameter, fmt='%Y-%m-%d'):
    date = request.GET.get(parameter)
    return datetime.datetime.strptime(date, fmt)

def get_search_data(request):
    if request.user.is_authenticated():
        user_email = request.user.email
        user_profile = UserProfile.objects.get(user=request.user)
        user_phone = user_profile.phone_number
    else:
        user_email = ''
        user_phone = ''

    search_date = datetime.datetime.now()
    rent_starts = extract_date(request, 'date_start')
    rent_ends = extract_date(request, 'date_end')
    rent_duration = rent_ends - rent_starts
    days_till_rent_start = rent_starts - search_date

    return {'search_data': {
        'user_email': user_email,
        'user_phone': user_phone,
        'search_date': search_date.strftime('%Y-%m-%d'),
        'rent_duration': rent_duration.days,
        'days_till_rent_start': days_till_rent_start.days,
    }}

However, given that this function does not interact with your models (except to retrieve a phone number that could have been passed to a template earlier on), I'm wondering why you perform this computation server side. All the necessary informations are already available to the client and javascript's Date objects can perform the same kind of manipulations than what you're doing with datetime.


I don't think speed should be your primary concern in this case. The only thing I could come up with as an improvement is to change consonants:

from string import ascii_lowercase

VOWELS = ("a", "e", "i", "u", "o", "y", "w")
CONSONANTS = tuple(char for char in ascii_lowercase if char not in VOWELS)
# These can be constants because they're always the same (at least for the latin alphabet).

Also, you don't handle the case where string is not lowercase. To account for that:

def pig_latin(string):
    string = string.lower()
    if string[-1] in CONSONANTS:
        string = string[1:] + string[0] + "ay"
    else:
        string = string + "way"
    return string

As @Ludisposed suggested, you don't actually have to convert the entire string to lowercase, if string[-1].lower() in CONSONANTS would do.


'fit for purpose' depends on what exactly that purpose is. Do you want to register the time of birth (as the Value property suggests), or only the date (as the class name seems to imply)? Does it need to handle birth dates before 0 A.D.? Does it need to reject non-existing dates (depending on actual historical data)?
If this class is meant to store a date only (not a time component), then it makes more sense to give it Year, Month and Day properties, rather than a Value property that exposes a time component.
DateTime.MinValue is the default value of DateTime, but why does that make it an invalid birth-date?
It may be useful to provide (explicit or implicit) conversions operators from and to DateTime, and perhaps parsing methods, depending on where and how this class is meant to be used. However...
...the purpose of this class seems very narrow. Judging from your other posts, you are thinking about creating many such 'value' types? That's a lot of work (at least in C#), but what problem does it solve? Where's the added value? Are you worried that someone may accidentally assign an expiry-date to a birth-date field? Remember, all that extra code needs to be maintained, and there's a cost associated with that.

My impression is that yes, you are over-engineering this. I suspect that you'll find more value in writing automated tests (which, when done properly, should have caught that >= operator bug, and should catch expiry-date/birth-date mixups just as well) than in adding this sort of complexity. C# requires too much boiler-plate to make this approach viable, so unless lives are at stake I wouldn't bother.

EDIT: A few more notes:

In C# 7, ReferenceEquals(a, null) can be written more succinctly as a is null.
The null check in CompareTo uses the overloaded != operator, but you might as well use a reference check directly.
Why are the Equals methods not using Comparison? The same goes for the != operator: why doesn't it do Comparison(dateOfBirth1, dateOfBirth2) != 0?


Data Explorer query that makes bar graphs

I'll answer your main questions:

Can I refactor it so that the list of when like then statements occurs only once? (Preferably without complicating the code too much.)

Yes, but not at the expense of complicating the code. In SEDE we unfortunately don't have the permission needed to create user-defined functions.

I have introduced two concepts. One is a string with the comma separated words to select the posts your interested in. This string can then be STRING_SPLIT and each value gets transformed in the right hand side of the LIKE expression.

The other concept is a temporary table that holds the phrase and a bar value. That allows for a join on Posts.Title with a LIKE expression to add the bar value column to a title from the posts row.

By introducing common table expressions the functional steps to obtain the right sets can be broken up, making the final projection a breeze.

Are there any optimizations I can make? So far, I've been using top # statements to keep things from taking too long.

On Super User this doesn't run too long, the execution plan looks like this:

and I can't think of any optimizations within the limited options we have within SEDE. I did add an extra where clause when selecting from the Posts table to make sure only questions are queried, as they only have titles.

Without further ado here is my optimized version of the query

-- selection of titles, comma separated
declare @selection nvarchar(250) = 'library,tool,book,tutorial'

-- table to hold the phrases to go in each bar
create table #titles (phrase nvarchar(50), value int);
-- add the phrase and which bar
insert into #titles values ('open source',0)
insert into #titles values ('recommend',1)
insert into #titles values ('free',2)
insert into #titles values ('good',2)
insert into #titles values ('best',2)
insert into #titles values ('better',2)
insert into #titles values ('any',2)
insert into #titles values ('what%should',3)
insert into #titles values ('which%should', 3)
insert into #titles values ('is there',3)
insert into #titles values ('looking for',4)

-- the Common Table Expressions to make our life easier
;with
-- the questions to be considered from the posts table
questions as (
  select distinct
         id
       , title
  from posts
  inner join string_split(@selection,',') -- gives us a table
     -- do a case insensitive like with a proper collate
     on title like concat('%',value ,'%') collate SQL_Latin1_General_CP1_CI_AS
  where posttypeid = 1 -- only questions (this reduces the set drastically)
  and closeddate is null
  and deletiondate is null
),
-- for each qualifying row add the bars to with it
titlecategories as (
  select distinct id
       , title
       , coalesce(
           value,
           (select max(value) + 1 from #titles) -- title has no matching value
         ) value
  from questions q
  left outer join #titles t
    -- do a case insensitive like
    on title like concat('%', t.phrase ,'%') collate SQL_Latin1_General_CP1_CI_AS
),
-- make sure each post only appears once
categories as (
  select id
       , min(title) title
       , min(value) value -- lower is better is idea ....
  from titlecategories
  group by id
)

-- final projection, partition and order by over value
select top 1500
       value
     , left(title, 25) title
     , ROW_NUMBER() OVER (
        PARTITION BY(value)
        ORDER BY (value)
       ) AS Number
from categories
order by value
       , Number

I did notice that if I leave out the top statement, I get some glitches in the graph but I'm unable to pinpoint what is causing that. For now I write that off on the used library on the Stack Exchange Data Explorer.


It's not very relevant for traversal, but a dict-of-sets may be a better overall structure than a dict-of-lists, as it would let you check for edge existence between two random nodes in amortized constant time, as opposed to worst case linear on the number of edges.
Using sets instead of lists for things like visited_nodes is bound to have a significant impact on performance for larger graphs though.
Another point to consider, since you are building an iterator, is to make your function return, well, an iterator of course! You can always materialize them calling list on the return, but for traversals of huge graphs it may spare you a generous amount of memory.

I'm going to skip the making it a class part, but with graph being a dict-of-iterables, and the above points in mind, you could implement depth-first iteration as:

def _dfs_iter(graph, node, visited_nodes):
    if node in visited_nodes:
        raise StopIteration

    visited_nodes.add(node)
    yield node

    for next_node in graph[node]:
        for n in _dfs_iter(graph, next_node, visited_nodes):
            yield n

def dfs_iter(graph, node):
    assert node in graph
    visited_nodes = set()
    return _dfs_iter(graph, node, visited_nodes)

There is no native Python data structure really well suited to create a FIFO queue. There is deque in collections, but it is a little obscure language feature, and also not ideally suited, so I'm going to pass on using it. Your implementation using a list and removing items from the front will lead to a terrible worse case performance, probably quadratic in the number of nodes. At the cost of not releasing the memory early, I think it is better to never remove items from the queue, and use an indexing pointer.

With the same caveats as before, you could do breadth-first iteration as:

def bfs_iter(graph, node):
    assert node in graph

    fifo_index = 0
    fifo_queue = [node]
    scheduled_nodes = set(fifo_queue)

    while fifo_index < len(fifo_queue):
        node = fifo_queue[fifo_index]
        fifo_index += 1
        fifo_queue.extend([n for n in graph[node] if n not in scheduled_nodes])
        scheduled_nodes.update(graph[node])
        yield node

Note that I'm keeping duplicate accounting on scheduled_nodes, both in fifo_queue and scheduled_nodes. This is to have the ordering of the FIFO queue and the fast membership check of a hash table. You could get rid of scheduled_nodes by checking against membership in fifo_queue, but you will again get quadratic performance, not a good thing.

A simple test on this graph:

6 - 0 - 1
| / | \ |
5   4 - 3 - 2 - 7

seems to yield correct results:

if __name__ == '__main__':

    graph = {0: set([1, 4, 5, 6,]),
             1: set([0, 3,]),
             2: set([3, 7]),
             3: set([0, 1, 2, 3, 4,]),
             4: set([0, 3,]),
             5: set([0, 6,]),
             6: set([0, 5,]),
             7: set([2,]),
             }
    assert list(dfs_iter(graph, 0)) == [0, 1, 3, 2, 7, 4, 5, 6]
    assert list(bfs_iter(graph, 0)) == [0, 1, 4, 5, 6, 3, 2, 7]

Note that, since we are using sets, the exact order of iteration over the connected nodes is implementation dependent, so a failure form the above tests doesn't necessarily mean that something is broken in the algorithm.


The implementation looks good, I just have a few suggestions.
Single-responsibility principle
The method encrypt seems to have a lot of responsibility:

Reads the input from the user
Encrypts the input
Outputs the result to the console

One definition of SRP is "A class should have only one reason to change". But there are many reasons for KamasutraCipher to change:

The input may come from System.in, file, database, etc.
The library StdIn changes.
The output needs to go to a file, etc.
The output needs to be formatted nicely for the user
etc..

The only responsibility of KamasutraCipher should be to encrypt (or decrypt) a string and return the result.
The interface can be refactored from this:
public class KamasutraCipher {
    public static void encrypt(String s, String t)
}

To:
public class KamasutraCipher {
    public KamasutraCipher(String key1, String key2)
    public String encrypt(String s)
}

Now the only reason for KamasutraCipher to change is for optimizations or if the Kamasutra algorithm changes, but the latter is not going to happen soon.
All the logic for requesting the input and producing the output is pushed to the main.
Strings are immutable
In Java strings are immutable objects, and any modification to a string creates a new string. Therefore this part:
String temp = word;
word = temp.substring(0,i) + String.valueOf(t.charAt(j)) + temp.substring(i+1);

Can be changed to:
word = word.substring(0,i) + t.charAt(j) + word.substring(i+1);

Optimization
The complexity of the method encrypt is O(m*n) where m is the length of the input string and n is the length of the key. (ignoring the methods of String and the while loop).
A more efficient way would be to use a map to store the string keys. For example, given the string keys ABC and FGH, the map would contain:

A -> F
B -> G
C -> H
F -> A
G -> B
H -> C

The method encrypt then becomes a simple lookup on the map, reducing the complexity  to O(m):
public String encrypt(String s) {
    StringBuilder sb = new StringBuilder(s.length());
    for (int i = 0; i < s.length(); i++) {
        Character c = s.charAt(i);
        sb.append(keyMap.get(c));
    }
    return sb.toString();
}

SpringBuilder lets us save some memory by creating the result string more efficiently. keyMap is created in the constructor because the keys don't change after initialization.
Input validation

any letter in standard input must appear in exactly one of them (keys)

As mentioned by others this is a requirement that needs to be handled, possibly in the method encrypt.
For the exceptions you can use IllegalArgumentException instead of RuntimeException.
Refactored code
public class KamasutraCipher {

    private final Map<Character,Character> keyMap;

    public KamasutraCipher(String key1, String key2) {
        if (key1.length() != key2.length()) {
            throw new IllegalArgumentException("The key lengths must be equal");
        }
        keyMap = new HashMap<>();
        for (int i = 0; i < key1.length(); i++) {
            keyMap.put(key1.charAt(i), key2.charAt(i));
            keyMap.put(key2.charAt(i), key1.charAt(i));
        }
    }

    public String encrypt(String s) {
        StringBuilder sb = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);
            if(!keyMap.containsKey(c)) {
                throw new IllegalArgumentException(String.format("'%c' is not in the keys", c));
            }
            sb.append(keyMap.get(c));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        KamasutraCipher cipher = new KamasutraCipher(args[0], args[1]);
        while (!StdIn.isEmpty()) {
            String input = StdIn.readString();
            System.out.println(cipher.encrypt(input));
        }
    }
}


Here's one way, that uses the method Fixnum#divmod to advantage:

COINS = [["H", 50], ["Q", 25], ["D", 10], ["N", 5], ["P", 1]]

def change(amount)
  raise ArgumentError, 'Only non-negative integers permitted' unless
    amount.is_a?(Fixnum) && amount >= 0
  return [] if amount.zero?
  COINS.map do |label, value|
    nbr, amount = amount.divmod(value)
    [nbr, label]
  end
end

change(260) #=> [[5, "H"], [0, "Q"], [1, "D"], [0, "N"], [0, "P"]]
change(95)  #=> [[1, "H"], [1, "Q"], [2, "D"], [0, "N"], [0, "P"]]
change(100) #=> [[2, "H"], [0, "Q"], [0, "D"], [0, "N"], [0, "P"]]
change(80)  #=> [[1, "H"], [1, "Q"], [0, "D"], [1, "N"], [0, "P"]]
change(45)  #=> [[0, "H"], [1, "Q"], [2, "D"], [0, "N"], [0, "P"]]
change(16)  #=> [[0, "H"], [0, "Q"], [1, "D"], [1, "N"], [1, "P"]]
change(1)   #=> [[0, "H"], [0, "Q"], [0, "D"], [0, "N"], [1, "P"]]
change(0)   #=> []
change(-3)  #=> ArgumentError: Only non-negative integers permitted...
change(1.2) #=> ArgumentError: Only non-negative integers permitted...
change('c') #=> ArgumentError: Only non-negative integers permitted...


I'm afraid that your second question ("Is this secure?") is one that you're not likely to get a good answer on here at Code Review. What you seem to be trying to do here is to design a cryptographic protocol, and cryptanalysis requires very specific expertise that I don't think any of the regulars here possess. I certainly don't. Also, to comment on the security of a protocol we have to see the whole protocol. The code in the question doesn't seem to have any defence against man-in-the-middle attacks, or any message authentication. But no doubt you plan to handle those problems elsewhere in your protocol.

However, I do have a couple of comments based on what you're shown us here:

The documentation for PKCS#1 v1.5 says, "If you are designing a new protocol, consider using the more robust PKCS#1 OAEP." Did you consider this?
The code says that the sentinel argument to PKCS115_Cipher.decrypt "is for verification", but in fact you are specifically warned in the documentation not to use it for verification: "you should not explicitly check if the returned value is the sentinel or not".

The usual advice when it comes to designing cryptographic protocols is "don't do it—use an industry standard instead". So in your use case ("encrypt the communication between the server and the client") I would use the TLS (Transport Layer Security) protocol via the built-in ssl module.


Bear in mind that code inside the function called by finally must not allow exceptions to propagate out, or you end up with problems when the destructor is called while cleaning up an exception in the calling code. You might want to put a catch(...) block in the finally_type destructor for that reason.

I agree that the C++98 solution is much uglier, to the point of not being usable. C++98 is never going to be able to capture arbitrary code for execution later. I'm not so sure this is a problem though, since I expect the cleanup code to have to be specialised only per-type, not per-usage. I want the class to be responsible for cleaning itself up, not the client of the class, since the latter can lead to mistakes or redundancy. The most idiomatic solution is to put this cleanup code in the destructor.

Edit: If you have to support a non-RAII class with an arbitrary cleanup method, then you can make a scoped holder that will call the method for you. It proved more fiddly than I expected, here's the best I could come up with:

class ScopedAction {
 public:
   virtual ~ScopedAction() = 0;
};

ScopedAction::~ScopedAction() {
}

template<class T, class Arg1, void (T::* p)(Arg1)>
class SpecialisedScopedAction : public ScopedAction {
 public:
   SpecialisedScopedAction(T &target, Arg1 &arg) : target_(target), arg_(arg) { }
   ~SpecialisedScopedAction() {
      try {
         (target_.*p)(arg_);
      }
      catch (...)
         {}
   }

 private:
   T &target_;
   Arg1 &arg_;
};

class ScopedActionHolder {
 public:
   ScopedActionHolder(ScopedAction * action) : action_(action) {}
   ~ScopedActionHolder() {
      delete action_;
   }

 private:
   ScopedAction * action_;
};

template<class T, class Arg1, void (T::* fn)(Arg1)>
ScopedAction * makeScopedAction(T & t, Arg1 & arg) {
   return new SpecialisedScopedAction<T, Arg1, fn>(t, arg);
}

Using the following non-RAII class:

enum TransactionState {
   COMMIT,
   ROLLBACK
};

class DBConnection {
 public:
   void finish(TransactionState state) {
      if (state == COMMIT) {
         cout << "committing transaction" << endl;
      } else {
         cout << "rolling back transaction" << endl;
      }
   }
};

You can make a scoped object that calls the finish method, binding in a parameter from local scope like this:

void test() {
   DBConnection conn;
   TransactionState tstate = ROLLBACK;

   ScopedActionHolder cleanup(makeScopedAction<DBConnection, TransactionState, &DBConnection::finish>(conn, tstate));

   cout << "Doing something" << endl;
   tstate = COMMIT;
}

Having to specify the types as template arguments even though they're implicit in the member function pointer type is annoying, I was hoping to work around this but I've run out of time. Also, the syntax is non-obvious and it'll need a new overload of the makeScopedAction function for every different number of method parameters that needs to be supported.

Come to think about it, std::functional or boost::lambda may both be of some help here.


C# Convert BLOB to jpg, resize, then back to BLOB

Welcome to CodeReview! I hope you get some good feedback.
Absolute paths
string ID = Request.QueryString["id"];
string imageFile = "\\\\server\\c$\\inetpub\\wwwroot\\web-app\\images\\" + ID+ ".jpg";

This has a few issues. First, it's typical for a server to be in a "jail" where it shouldn't have access to the filesystem at large, and should only access data from its own local directory. This is for security purposes. Though I haven't done this in a long time, it seems the ASP.NET way of safely accessing such paths is MapPath.
Second: it's crucially important that you do some validation on ID. In its current state a hacker could easily construct a path navigation exploit where the ID contains ..\..\.. (etc) to explore the rest of the filesystem if the server is misconfigured.
Managing your connection
If connection is an SqlConnection, it implements IDisposable, and as such you should put it in a using. The same is true of SqlCommand.
Add-with-value
You should prefer AddWithValue over a separated Add/.Value assignment here;
sqlCommand.Parameters.Add("@ID", SqlDbType.VarChar);
sqlCommand.Parameters["@ID"].Value = ID;

Read-in-loop
This:
while (dr.Read())
{
    byteImage = (byte[])dr["BLOB"];
}

should probably not use a loop. Since it seems you expect only one row returned,

Read() once;
assert that it returned true;
assign byteImage;
Read() again;
assert that it returned false.

Streamed image creation
GetResizedImage creates a memory stream. It should not. Response already has an OutputStream, and you should be writing to that directly. The one thing to double-check with this approach is that Content-Length is still set correctly, which is probably only possible if BufferOutput is enabled.
Avoiding files
As to your original question, which I never really addressed:

Is there anything I can change here to skip saving an image on the server and just display it so it doesn't use up a ton of resources?

Yes! As long as you get an image from the database, you always Save() it to the disc. However, this file is only used if the server name is approved. Move your save within the name check, and fewer cases will require disc I/O.
Even further: if this is the only code that touches that file, that file should not exist at all and you should not be doing a round trip to the disc. Once you have your img, pass that to GetResizedImage instead of a path string.
Bug?
There is a mechanism here:
imageFile = HttpRuntime.AppDomainAppPath + "PERSON.GIF";

which looks like it's supposed to substitute a default image if none is returned from the database. However, that file is never used. This logic needs to be rearranged so that it is. If you get back a null from the database, load this file into your byteImage.


Searching for files in a specified directory

To improve readability I would try and break the code down into more functions and redefine your pre-determined text values as globals, such that you can save space in the actual function. Responses can be represented by a dictionary value with boolean/text key value pairs (or exception/text). Also certain UI options can be stored in a dictionary, with links to their associated functions.

# using 3 quotes mean you don't need to specify newlines
dir_tools_menu = '''
Which search characteristics would you like to use?
1. Search by name: N
2. Search by extension: E
3. Search by size: S
\tPlease enter your choice: '''
dir_tools_options = {"n":ui_search_by_name,
                     "e":ui_search_by_extention,
                     "s":ui_search_by_size}
error_response = {WindowsError:"Oops! Access denied.",
                  ValueError:"Enter an numeric value."}
# add number of files for true
files_found_response = {False:"No file(s) found",
                        True:"{} file(s) found"}
# add filename
file_found_response = {False:"File {} not found",
                       True:"File {} found"}
file_exists_response ={ False:"Path does not exist.",
                         True:"Path Found"}
# add choice for true
valid_ui_response = {False:"Invalid choice.",
                      True:"You choose {}."}

Now that we have a collection of text values lets make a function to standardize print outputs, such that you don't have to write all those stars everywhere, and you can feel assured that they will produce even length lines.

line_length = 40
# or you can have a funky pattern like "`-._.-'-._...
line_pad = "*"*line_length

def my_print(text, *params):
    # len(params) must match the count of "{}" in the text so this will not crash
    # Perhaps add a check to assert this case
    message = text.format(*params)
    offset = line_length/2 - len(message)/2
    if offset > 0 and offset + len(message) < line_length:
        print(line_pad[:offset] + message + line_pad[offset+len(message):])
    # in the case that a line is larger than the formatting, you can just print the line.
    # its gonna look gross regardless
    else:
        print(message)

Lets also make a simple yes/no function.

yes = ("yes", "y","1")
no = ("no", "n", "0")
def ask_yes_no(question):
    answer = ''
    while not answer in yes + no:
        answer = input(question).lower()
        if not answer in yes + no:
            my_print(valid_ui_response[False])
        else:
            my_print(valid_ui_response[True], return_to_menu)
            # True - yes, False - no
            return answer in yes

Now your main method boils down to..

quit_question = "Quit Dir Tools? "

def dir_tools(file_path):
    if os.path.exists(file_path):
        my_print(file_exists_response[True] )
    else:
        my_print(file_exists_response[False])
        return
    quit_dir_tools = False
    while not quit_dir_tools:
        answer = input(dir_tools_menu).lower()
        if answer not in dir_tools_options:
            my_print(valid_ui_response[False])
        else:
            my_print(valid_ui_response[True],answer)
            dir_tools_options[answer](file_path)
        quit_dir_tools = ask_yes_no(quit_question)

Now for the actual important functions.. I'll just do one example to show the try catch responses,..

ui_sbn_question = 'Enter file name: '
return_question = "Return to main menu? "

def ui_search_by_name(file_path):
    return_to_menu = False
    while not return_to_menu:
        name = input(ui_sbn_question)
        try:
            sbn_response = search_by_name(name, file_path)
            if not sbn_response:
                my_print(file_found_response[False], name)
            else:
                my_print(file_found_response[True], name)
                # assuming that this isnt a boolean
                my_print(sbn_response)
        except WindowsError:
            my_print(error_response[WindowsError])
        return_to_menu = ask_yes_no(return_question)


Find the first repeating sequence in digits of pi

How do I make it simpler and faster?

A more efficient approach:

Iterate on pi with a sliding window of size n.
Save each sequence (and the starting position) in a lookup map
Return as soon as you find a match in the lookup map

Something like this:
def repeats(n):
    lookup = {}
    pi_s = str(pi)[2:]
    for i in range(n, len(pi_s)):
        start = i - n
        seq = pi_s[start:i]
        if seq in lookup:
            return list(map(int, seq)), lookup[seq], start
        lookup[seq] = start

For n=5 this runs in 0.001 seconds, while your approach takes ~40 seconds.
For n=10 and 1 million digits, this approach finds ([4, 3, 9, 2, 3, 6, 6, 4, 8, 4], 182104, 240478) in ~50 seconds. The slowest part now seems to be str(pi), which generates the digits. Once the digits are generated, searching for the sequence takes less than a second.
Review

Naming: the function name repeats is a bit ambiguous, it sounds like how many times n appears in the sequence. A better name could be first_repeating_sequence_of.
Edge case: for bigger n, more digits of pi are required, otherwise no matches are found. Consider passing the max number of digits of pi as an argument so the caller is aware of this limit.


This is missing the point. It is not about promises. You are right that if done correctly, you'll get a nice flat structure, but not if you inline all your code. This would be true if you weren't using promises as well. What you should do is split your code into smaller building blocks, and the nice structure will follow.

Also, be wary of your variable names:

// check if password matches
if (compareResult) {

Why not rename "compareResult" "passwordIsCorrect" and get rid of the comment?

// find the user
User.findOne({

That comment is useless.

Basically all the comments can be removed. Try to explain yourself with code instead, and only comment what can't be explained with code.

Just a quick example of the type of refactoring I would do:

routes.login = (req, res) => {
    let inpEmail = req.body.email.toLowerCase();
    let inpPassword = req.body.password;

    User.findOne({email: inpEmail})
        .exec()
        .then((user) => {
            if(user.isLocked && Date.now < user.lockExpiry){
                return blabla();
            }else if(!user.emailVerified){
                return requireEmailVerification();
            }else{
                return login(user, inpPassword);
            }
        })
        .then(() => {
            // Probably res.send() here
        })
        .catch((err) => {
            //some logic here
        });
};

function login(user, pw){
    return bcrypt.compare(pw, user.passwordHash)
        .then(passwordIsCorrect => {
            if(passwordIsCorrect){
                return setLastLoginAndDoSomeLogic(user);
            }

            return incrementLoginFailureCountAndDoSomeLogic(user);
        });
}

function setLastLoginAndDoSomeLogic(user){
    return setLastLogin(user)
        .then(() => {
            //some logic here
        })
        .catch((err) => {
            //some logic here
        });
}

function incrementLoginFailureCountAndDoSomeLogic(user){
    return setLoginFailureCount(user, user.loginFailureCount + 1)
        .then(() => {
            //some logic here
        })
        .catch((err) => {
            //some logic here
        });
}


Not using return values of TryParse

The method receives several parameters as string,
and parses them to other types such as DateTime or int.
It's surprising to see calls to TryParse,
and using the value in the out parameters without checking the returned value.

The code basically assumes that the string values are of the correct format.
But if that assumption is always true,
that fact should be at least documented,
but it would be even better to pass the real types instead of string values.
If the assumption is not guaranteed to be true,
then the program may crash.

Repetitive code

The parameter parsing code (string values to DateTime or int) are repetitive, and take at least 2 lines per value.
It would be better to add some helper functions to simplify this,
so that you could write like this:

DateTime _dateFrom = parseDateTime(dateFrom).Date;
DateTime _dateTo = parseDateTime(dateTo);

Pointless initializers

Here, it's pointless to initialize countries with an empty list when it's going to be reassigned right after:

var countries = new List<Country>();

countries = _countryRepository.GetAll().ToList();

The same goes for events.

Single responsibility principle

This method is doing too much,
that's why it's so long.
It would be better to split it up to smaller logical units.

Statements with side effects?

What are these for?

_regionRepository.GetAll().ToList();
_storeRepository.GetAll().ToList();
_askoTillRepository.GetAll().ToList();

It looks like loading objects, converting them to List, and doing nothing with the values.
What's going on here?
At the minimum this should be documented (with comments).

Group related statements together

It's hard to read when related statements are not grouped together, for example:

var events = new List<Event>();

// more than 10 lines of code ...

events = _cache.Get<List<Event>>("eventsChache");

// some code ...

events = events == null ? new List<Event>() : events;

It's hard to follow how the events variable is used when there are unrelated statements in between.

Local variable or field?

The variable names use an inconsistent mix of styles,
which makes the code harder to read.
For example, some local variables have a _ prefix,
others do not.
Some variables defined outside the method also have _ prefix.
Those should probably be properties instead.

Use var more

You used var at some places, but not at others.
For example Dictionary<int, List<Event>> eventsForPos = new Dictionary<int, List<Event>>(); is really tedious and a good candidate for using var.

Bug?

This condition looks like a bug:

x.DateTo <= _dateTo || !x.DateTo.HasValue

If x.DateTo doesn't have a value, won't x.DateTo <= _dateTo crash?
It should be safer if you flip that condition:

!x.DateTo.HasValue || x.DateTo <= _dateTo

Simpler foreach

This can be written simpler:

foreach (Event e in forEvets)
{
    if (eventsForPos.ContainsKey(e.PosTillId))
    {
        eventsForPos[e.PosTillId].Add(e);
    }
    else
    {
        eventsForPos[e.PosTillId] = new List<Event>() { e };
    }
}

Like this:

foreach (Event e in forEvets)
{
    if (!eventsForPos.ContainsKey(e.PosTillId))
    {
        eventsForPos[e.PosTillId] = new List<Event>();
    }
    eventsForPos[e.PosTillId].Add(e);
}

And btw there's a typo in forEvets.

Group case statements with same body together

Instead of this:

switch ((PageDetailType)_pageDetailType)
{
    case PageDetailType.CountriesDetail:
        break;
    case PageDetailType.CountryDetail:
        res = ModelHelper.GetGraphStatusesCountry(countries, _countryId);
        break;
    case PageDetailType.RegionDetail:
        res = ModelHelper.GetGraphStatusesRegion(countries, _regionId);
        break;
    case PageDetailType.StoreDetail:
        res = ModelHelper.GetGraphStatusesStore(countries, _storeId);
        break;
    case PageDetailType.TillDetail:
        break;
    default:
        break;
}

It would be better like this:

switch ((PageDetailType)_pageDetailType)
{
    case PageDetailType.CountryDetail:
        res = ModelHelper.GetGraphStatusesCountry(countries, _countryId);
        break;
    case PageDetailType.RegionDetail:
        res = ModelHelper.GetGraphStatusesRegion(countries, _regionId);
        break;
    case PageDetailType.StoreDetail:
        res = ModelHelper.GetGraphStatusesStore(countries, _storeId);
        break;
    case PageDetailType.CountriesDetail:
    case PageDetailType.TillDetail:
    default:
        break;
}


Preferably, you would generate a random salt. Add a function to generate random salt, then be sure to call it in your constructor. If a user discovers you salt, that is a major security hole right now.

In my opinion, it would be best to separate this class into a separate file for easier use in multiple situations. Also, a separate file with useful functions like generating salt could be useful.

Your code is relatively secure, but you need a random salt generator. Otherwise, your code looks good.


Since this is all the code you posted, I'm going to assume you're only using these functions in the place they're defined, so the later code would be best. It's more readable and doesn't include unnecessary identifiers.

Your question is really about anonymous functions, not closures. To answer this question, you should ask yourself, "do I plan on using these functions elsewhere"? Since anonymous functions, by definition, are not bound to an identifier, they will be inaccessible everywhere except where they are defined.

This is the version that I would recommend:

$(function () {

    var game = function () {
        var gamevar1, gamevar2, ...;
        action1: function (arg) {
            doAction1();
        }

        action2: function (arg) {
            doAction2();
        }
    }

    //when a msg is received [action,param]
    game.msg[0](msg[1]);
}


Program to check if in line are doubled words

Here are some suggestions:

Keep file handlers in one function.

First off, the get_text_file() and lines_list() methods:

def get_text_file(self):
    file = open('C:/Users/PC/Documents/skychallenge_skyphrase_input.txt', 'r')
    return file

def lines_list(self):
    text = self.get_text_file()
    line_list = text.readlines()
    return [line.split() for line in line_list]

It's generally a bad idea to pass files outside of a function... it poses some questions: Who will close the file? When? And how? Instead, open and close it in the same function so that the file can be contained.
Since the lines_list() method is only reading text off from get_text_file() (and nothing else), it may be better to simply write one function which reads handles and reads lines off the file. (The splitting of lines, line.split(), can be done in phrases_validation().)

With these points in mind, we could define get_text_lines() as:

def get_text_lines(self):
    with open('C:/Users/PC/Documents/skychallenge_skyphrase_input.txt', 'r') as file:
        line_list = file.readlines()

    return line_list

Notice that the use of the with statement. This automatically closes the file when the block-scope is exited.

Using the above function implies modifying phrases_validation():

def phrases_validation(self):
    # ...
    for line in get_text_lines():   # call function here
        # ...
        words = line.split()        # split lines here
        for word in words:          # iterate through split line here
            # ...

The Validation Algorithm

I've tried annotating the meat of your phrases_validation:

# iterate through lines...
for line in get_text_lines():

    new_line = []  # container to store 1s and 0s

    # iterate through words...
    words = line.split()
    for word in words:

        exam = line.count(word)

        # append 0 if word is duplicated
        if exam > 1:
            new_line.append(0)

        # append 1 if word is not duplicated
        else:
            new_line.append(1)

    # increment validated_phrases if no duplicates
    if 0 in new_line:
        validated_phrases += 0
    else:
        validated_phrases += 1

Some general suggestions:

Opt for readability. Since only 0 and 1 are being used, this implies a binary domain, and thus can be substituted with False and True respectively.
validated_phrases += 0 This can be removed since nothing is added. Simply do

if 0 not in new_line:
    validated_phrases += 1

Some possible improvements to the algorithm:

Using the any built-in function.

The any built-in function takes a list and tests for truth. If any of the elements are Truthy, any returns True, else False. Your inner loop can make use of the any function:

for line in get_text_lines():
    words = line.split()

    has_duplicates = any(words.count(word) > 1 for word in words)
    if not has_duplicates:
        validated_phrases += 1

Here, a comprehension was used: words.count(word) > 1 for word in words.

This generates an iterable of True/False values: True if words.count(word) > 1 and False otherwise. We then check whether there are any duplicates and if not, increment validated_phrases.

(To keep track of the number of duplicates, you can use the sum function instead. This will add the True values, counting the number of duplicates.)

Using the set class.

Indeed, there are a couple more ways to check for duplicates. list.count has a time-complexity with an upper-bound of \$O(n)\$ (with \$n\$ being the length of the list), i.e. it searches the entire list, which may be slow when the list grows to sizes of thousands or millions.

One other way to check for duplicates would be to obtain a container of unique words, and check whether it has the same length as the list of words in the line. We can use set to obtain the unique words.

for line in get_text_lines():
    words = line.split()

    unique_words = set(words)
    has_duplicates = len(unique_words) != len(words)
    if not has_duplicates:
        validated_phrases += 1,

I'm not entirely sure about the complexity of set(words) but the len function has a time complexity of \$O(1)\$ which can be really fast in the long run.

Using the collections.Counter class.

Another way that might be of interest would be to use Counter from the collections module.

for line in get_text_lines():
    words = line.split()

    counter = Counter(words)
    has_duplicates = any(counter[word] != 1 for word in counter)
    if not has_duplicates:
        validated_phrases += 1

(For this, remember to add from collections import Counter at the top of your script.)

Try not to rely on __str__.

In your code, the main algorithm, phrases_validation(), is only called when str(text) or text__str__() is called (this is implicitly called by print(text)).

It's creative... but prefer to directly call phrases_validation():

validator = SkyphrasesValidation()
print(validator.phrases_validation())

(And call str() on it if needed.) This is more explicit to readers that you're calling the phrases_validation() method.

Generally, the __str__ magic method should be overloaded when you're trying to display a class' members contents. Unfortunately, SkyphrasesValidation doesn't have any members.

The variable name text can be interpreted in several ways. Is it a text file? A string?  Consider a more descriptive name instead. (validator was used in the example above.)

Class?

The class could have been substituted with one/two functions. But sticking with a class... since the self argument is rarely used, consider making the methods static or instead, place get_text_lines() outside of the class and pass the lines of text to phrases_validation() as an argument.

Hope this helps!


A Tumbler, or a format-preserving-encryption shuffle

Part of code review is challenging assumptions, so to begin with I'd like to challenge the motivation for this code.

You say you want to avoid "Storing the UID (unique id) in the table along with the id". Why would you have two? Any one of those is enough to uniquely identify a row - they are both unique, after all. If you mean the surrogate key (serial number, UUID or similar) and the business key (for example username), then it absolutely makes sense to store both of them in the same table. Surrogate keys have been discussed for decades, but the industry consensus nowadays seems to be:

The business key should be exposed to end users. That is, a user should know their own username and employee number, even if these are created by the system.
Tables should have a surrogate key, and this key should not be exposed to end users. This does not just include direct user interfaces, but also for example URLs. The reason for this is to be sure that the surrogate key remains an implementation detail which could later be changed, such as when moving from a guessable serial number to a UUID.

You also want to avoid a "[c]omplex and costly algorithm". Version-4 UUIDs are probably the cheapest unguessable surrogate keys you can get your hands on these days without massive implementation effort, as long as you use pretty much any database other than MySQL - PostgreSQL has them, as does the major closed-source databases.

The last reason is related to unguessable IDs, already discussed above.

All in all it looks like implementing v4 UUIDs in MySQL is probably the cheapest option if you must use that database, otherwise you can just use an existing, safe, fast and F/LOSS solution.

That said, some suggestions for the Python code:

__init__ takes an optional rounds parameter, but the only place that's used it's called shuffling_method, which seems inconsistent. Changing the number of rounds doesn't constitute changing the "method".
Rather than assigning u and v at the same time you can save one operation by assigning u first and reusing its value to define v.
Naming is incredibly important for maintainability. I basically have to read the entire code block to guess what a, b, c, m, u, v and x mean. A good variable name is better than a good comment, and will allow the reader to understand a piece of code with as little context as possible.
Having twinned methods encrypt and _encrypt, decrypt and _decrypt is a code smell. If they are doing the same thing, why are they not one method? If they are doing different things, why are they named effectively the same?
There are four different Jenkins hash functions, but it's not obvious which one this is. That would be very helpful for someone trying to verify the implementation.
This comes under the category of implementing your own crypto, since you're trying to make the sequence non-guessable. This hash function looks fairly niche based on the Wikipedia article, and it even looks like the Jenkins hash without an additional secret is guessable.


Assume any Win32 call that returns a handle allocates a struct with malloc. And assume DeleteObject (DestroyWindow etc) frees allocated memory. you should call DeleteObject every time you creare a GDI object.

Calling CreateSolidBrush twice, and losing the first handle without calling Deleteobject on it causes a resource leak.

Since you are using C++ the correct way to do it is RAII. see http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

This site has a good tutorial with clear windows programming examples on the subject.
http://www.relisoft.com/book/win/index.htm

This is a good open source library (MIT licence), that you can use in your project directly. Or you can look at gdi.h in the source.
http://win32-framework.sourceforge.net/index.htm


It probably doesn't matter, but the first element of that path can be ifmxdev______ or ifmxdev_x_x_x with that regex.

I suggest you use use the Unicode property alnum, which is [A-Za-z0-9] - \w without the underscore

qr{ \A /ifmxdev (?:_\p{alnum}+)? /files /file\.\d{4} \z }x


Convert uppercase characters to lowercase and insert a space where each uppercase character used to be

Thanks for sharing the code.

This is quite good for a first attempt (except the bug).

Things to consider:

Odd ball solution

This means that you do the same thing in different ways.

use of variable vs direct array access

when you handle the first letter you directly access it using array index access sToArray[0] whereas for all the other letters you first put the actual char into a local variable currentChar but you do not use it in the if statement. You should do the same at all places.
similar logic that could be the same

this is a bit trickier and may need some experience, but:
The difference between the handling of the first letter and all the other letters is that you don't put a space before it. Having in mind that there is an empty string ("") in Java putting that instead of the space is just a configuration, a different value to use and not a different behavior needing different instructions (or their order). Including point 1 your code could look like this:
(I intentionally kept your bug!)

String amendTheSentence(String s) {
    StringBuilder modifiedString = new StringBuilder();
    char[] sToArray = s.toCharArray();
    String separator = "";
    char currentChar = sToArray[0];

    if (Character.isUpperCase(currentChar)) {
        currentChar = Character.toLowerCase(currentChar);
        modifiedString.append(separator );
    }
    modifiedString.append(currentChar);

    for (int i = 1; i < sToArray.length; i++) {
        String separator = " ";
        char currentChar = sToArray[i];

        if (Character.isUpperCase(currentChar)) {
            currentChar = Character.toLowerCase(currentChar);
            modifiedString.append(separator);
        }
        modifiedString.append(currentChar);
    }
    return modifiedString.toString();
}

Now you have 4 lines which are repeated exactly the same before the loop and inside the loop. This 4 lines can be extracted to a parameterized method:

private void convertAndAppendTo(StringBuilder modifiedString, char currentChar,
                                String separator){
    if (Character.isUpperCase(currentChar)) {
        currentChar = Character.toLowerCase(currentChar);
        modifiedString.append(separator );
    }
    modifiedString.append(currentChar);
}

and your original method changes to this:

String amendTheSentence(String s) {
    StringBuilder modifiedString = new StringBuilder();
    char[] sToArray = s.toCharArray();
    convertAndAppendTo(modifiedString,  sToArray[0], "");

    for (int i = 1; i < sToArray.length; i++) {
        convertAndAppendTo(modifiedString,  sToArray[i], " ");
    }
    return modifiedString.toString();
}

Magic numbers

In your code the 0 is a magic number and should be declared as a constant with a meaningful name like this:

private static final int FIRST_LETTER_INDEX = 0;

String amendTheSentence(String s) {
    StringBuilder modifiedString = new StringBuilder();
    char[] sToArray = s.toCharArray();
    convertAndAppendTo(modifiedString,  sToArray[FIRST_LETTER_INDEX], "");
// ...

I for myself would also tread literal strings as magic numbers and convert them into constants:

private static final int FIRST_LETTER_INDEX = 0;
private static final String FIRST_SEPARATOR = "";
private static final String INTER_WORD_SEPARATOR = " ";

String amendTheSentence(String s) {
    StringBuilder modifiedString = new StringBuilder();
    char[] sToArray = s.toCharArray();
    convertAndAppendTo(modifiedString,  sToArray[FIRST_LETTER_INDEX], FIRST_SEPARATOR);
// ...

Naming

Finding good names is the hardest part in programming. So always take your time to think carefully of your identifier names.

Get your names from the problem domain, not from the technical solution.

You have a variable sToArray that stores the individual chars. The name tells something about the type of the variable but it should tell something about its purpose instead. So a better name might be individualLetters or just letters.


I want to know if I should delete this script and make a new one with prepared statements.

Yes, definitely.
This set of functions is just unacceptable, being so bad on so many levels.

There will be dozens to hundreds connections made in your script, not just "2 connections" for starter, as your code will connect anew every time it executes a query.
There is, as you rightfully noted, no support for prepared statements, which is a disaster alone. That escaping routine is based on the false notion that mysqli_real_escape_string's purpose is to protect you from SQL injection. Well, it's but a grave delusion.
error reporting is completely flawed. What a site user is supposed to do with a blank page telling them that a column not found?
a DBRead() function is silly. All its purpose is to save you a typing of two words. Seriously? And this trifle gain at the expense of making a gibberish out of the powerful language of SQL.

To show 2 records from a table (as it's stated in the code as opposed to the question title) you need only two lines with vanilla PDO, so you better stick with it:

$sql = 'SELECT * FROM publicacao ORDER BY id DESC LIMIT 2';
$dadosUN = $pdo->query($sql)->fetchAll();
?>
<?php foreach ($dadosUN as $UN): ?>

//some html here to display the records

<?php endforeach ?>


BoltDB Lookup and Add methods and advice on unit testing

I think the code could benefit a struct for the database instead of global state.
You can use a New method instead of init() where you pass in the params, which would differet from test and production.
I also demonstrated that you can keep the connection open and reuse it within the struct. If you prefer a lazy approach, you can omit this and create a the connection in each call if you want.
type Database struct {
   bucketName string
   boltDB *bolt.DB
}

func New(dbName, bucketName string, opts *bolt.Options) (db *Database, error) {
   db, err := bolt.Open(dbName, 0600, opts)
   return &Database{
      boltDb: db,
      bucketName: bucketName
   }, nil
}

func(db *Database) Lookup(path string) (url string, ok bool) { // lookup logic }
func(db *Database) RegisterUrl(path, url string) error { //register logic}
```


It looks like all your tests follow the pattern

if s_command[0] == "$xxxxx" and s_command[1] == "yyyyy":

So what you can do is create a tuple of the first two elements of s_command:

instr = tuple(s_command[:2])

Then, you can do

if instr == ("$xxxxx", "yyyyy"):

Next, you can use a dictionary to collect all your instructions in one place:

Instructions = {
    ("$out", ">>"): do_out,
    ("$inp", "<<"): do_inp,
    ("$assignint", "<<"): do_assignint,
    ...
}

Then you would define a number of functions, one for each instruction, such as

def do_inp(s_command):
    inp = raw_input(s_command[2])

and call your methods with

Instructions[instr](s_command)


PDO insert data through transaction method

Your code is all right from the performance point of view.

But again, you are doing the double work with your homegrown wrapper. For the life of me I won't understand a wrapper that makes your life harder.

So again, a code with vanilla PDO instance in $this->db

$stmt = $this->db->prepare('INSERT INTO books_pre
    (title, author, publication, container, tmp_no, created_by, created_at)
    VALUES (:B, :C, :D, :E, :A, :user_id, now())');

try {
    $this->db->beginTransaction();
    foreach(data as $i => $row) {
        // skip the first two lines
        if ($i == 0 or $i == 1) {
            continue;
        }
        $row['user_id'] = $_SESSION['user_id'];
        $stmt->execute($row);
    }
    $this->db->commit();
} catch (Exception $e) {
    $this->db->rollback();
    throw new $e;
}

Given you already have an associative array we can use its keys as placeholder names.

PDO's execute() method can accept an associative array with data, for example

$stmt = $pdo->prepare("SELECT * FROM t WHERE id=:id");
$stmt->execute(['id'] => $id);

As you can see, we are sending an array directly into execute(), which  keys that must match placeholder names. Given your array already have keys, I just used them as placeholder names in the query.

However, it'a a matter of taste and you can keep use your bind() calls instead.

An important note, there should be no such thing like echo "Failed: " in your code. Always just throw an error and let it be echoed by PHP.

On a side note, a comment like this

    // Start transaction
    $this->db->beginTransaction();

makes very little sense. Do not write comments that just duplicate a code below. Use comments to explain something not that obvious.


One empty interface could be considered a code smell, but can sometimes be useful for reflection purposes. Having two is nonsensical. An interface defines a contract that the type has to adhere to. Where's the contract here? I fail to see how these two types belong to the same inheritance tree. "Type" members also set off alarm bells in my head. They're usually an indication that there are missing interfaces. You could then just inspect the actual type, if you really had to.

I would go with something more like this.

public interface IMessagePacket
{
    string Message { get; }
}

public interface IStatusPacket
{
    bool Status { get; }
}

[Serializable]
public struct ServerChatIncomingMessagePacket : IMessagePacket
{
    public readonly string text;

    public string Message
    {
        get { return text; }
    }

    public ServerChatIncomingMessagePacket(string text)
    {
        this.text = text;
    }
}

[Serializable]
public struct ServerAccountAnswerLoginPacket : IStatusPacket
{
    public readonly bool success;

    public bool Status
    {
         get { return success; }
    }

    public ServerAccountAnswerLoginPacket(bool success)
    {
        this.success = success;
    }
}

This allows us to define behavior of the types. We could easily implement an OutGoingMessagePacket that implements IMessagePacket, or a LogOffPacket that implements IStatusPacket.

On another note, in your original implementation, you never used the parameter you passed to ServerAccountAnswerLoginPacket's constructor, or it's related private readonly field.


Project Euler 42 - finding triangle number V2

Possible problem

private static string[] ReturnStringArray(string fileLocation)
{
    StreamReader sr = new StreamReader(fileLocation);
    string[] words = sr.ReadLine().Split(',');
    return words;
}

With this method you don't read the whole file but only the first line in the textfile. Usually project Euler problem don't involve only one line of anything but rather some 10k of something.

In the first 5 lines of code I would change 3 variables/method names

        int numberTriangleWords = 0;
        string[] words = ReturnStringArray("p042_words.txt");
        int[] triangleNumbers = BuildTriangleNumber();

The problem is about getting the number of triangle words.

int numberOfTriangleWords = 0

You are reading a text file as words.

string[] words = ReadFileAsWords("p042_words.txt");

You are creating / building an array of numbers

int[] triangleNumbers = BuildTriangleNumbers();

This is just nitpicking on the naming, but naming is a very important part of writing good readable and maintainable code.

This method

    private static bool IsWordTriangleNumber(int wordVal, int[] triangleNumbers)
    {
        return (triangleNumbers.Contains(wordVal));
    }

isn't used anywhere. You should delete it.

    private static int[] BuildTriangleNumber()
    {
        int triangleNumberValue = 0;
        int[] triangleNumbers = new int[50];

        for (int i = 0; i < 50; i++)
        {
            if (i == 0)
                triangleNumbers[i] = triangleNumberValue;
            else
            {
                triangleNumberValue += i;
                triangleNumbers[i] = triangleNumberValue;
            }
        }
        return triangleNumbers;
    }

Because triangleNumbers is an array of the int struct, the items are initialized using default(T) which for an int is 0. Therefor if you just let the loop start at 1 you wouldn't need the check if (i == 0) at all which would also remove the braceless single line statement after the if.
I would like to encourage you to always use braces {} to make your code less error prone. Saving a few milliseconds by omitting them can lead to problems later on which patching can take a lot of time.

    private static int[] BuildTriangleNumber()
    {
        int triangleNumberValue = 0;
        int[] triangleNumbers = new int[50];

        for (int i = 1; i < 50; i++)
        {
            triangleNumberValue += i;
            triangleNumbers[i] = triangleNumberValue;
        }
        return triangleNumbers;
    }

I like the overloading of the GetScore() method, but the GetScore(char) method can be improved.

    private static int GetScore(char letter)
    {
        var start = char.IsLower(letter) ? 'a' : 'A';
        var score = (int)letter - (int)start + 1;
        if (score < 0 || score > 26) return 0;
        return score;
    }

There is no need to first assign a or A to start and then later on cast it to an int. The int value of a == 97 and of A == 65. So using these values should speed the whole thing up.

Edit Based on @Caridorc's comment
I have extracted these values to private static reaonly variables using a naming scheme which isn't legit by the meaning of the c# naming guidelines but looks better with the underscore in it.

    private static int ASCIIValue_a = 97;
    private static int ASCIIValue_A = 65;
    private static int GetScore(char letter)
    {
        var start = char.IsLower(letter) ? ASCIIValue_a : ASCIIValue_A;
        var score = (int)letter - start + 1;
        if (score < 0 || score > 26) return 0;
        return score;
    }


Custom ResponseModel for Spring Controller - ResponseEntity

To start, I think what you have there looks pretty straight forward.  It also looks very neatly written.  From just what I can see here, it would appear the largest gain from your "base" model is that it removes extraneous data from traveling out to the user.  The largest loss (potentially), is that it utilizes inheritance and theoretically forces those 4 properties onto every inherited result.  That being said, here's some reasoning...

Disclaimer :) Inheritance may be the perfect solution for what you've got going here in the long run.  But from the limited view here, it feels heavy handed.  It should also be noted that I haven't written Java an about 9 years and I'm currently a C/F# programmer.

Two things stand out to me.  First, the use of properties and private fields.  This contract appears to be immutable.  Could the fields just become public and final and lose the setters?  It doesn't appear to do much except to protect inherited members from accessing those values directly.  It would also reduce the amount of code in the class (#1 reason).  I can't see from here what the benefit of them being private is.  The notion that an inherited class would have no real access to it's base class raises a red flag.

This leads to the second thing.  Consider removing the inheritance.  Inheritance is always great until it's not.  You contract is simple enough that it wouldn't suffer this problem today, but several inherited types later it might.  The challenge with inheritance (especially with data), is that it forces everything to be the same shape.  The upside, is that inheritance is never really required to solve a problem.  It's just something we do... just because, usually.

You could consider a setup like this (pseudo code):

public class TransactionResponseModel { ... }

public class BalanceInquiryResponseModel {
    public BalanceInquiryResponseModel(TransactionResponseModel transactionResponseModel, BalanceInquiryResponse balanceInquiryResponse) {
    ...
    }

    public final TransactionalResponseModel TransactionalResponse;
    public final BalanceInquiryReponse InquiryResponse;
}

Inheriting doesn't really force anything, because the next developer might simply choose not to inherit.  Here you get all the same shapes and data without the class coupling and hierarchy.  Which is, in my experience, totally worth it.  When the response model comes that doesn't fit the same shape as your base classes, you won't have to setup a new inherited structure, modify your current one, or even care for that matter.  New data, new shape, no problem.

There are lot's of articles available on the un-benefits of inheritance:

Gooooooooogle

Hope this information is helpful.


Selecting variable amount of vector elements in C++

You can avoid problems related to variadic macros and problems related to C-style variadic functions altogether by creating a function that takes an std::initializer_list directly:

template<class T>
std::vector<T> select(const std::vector<T>& vec, std::initializer_list<std::size_t> indices)
{
    std::vector<T> ret;
    for (std::size_t ind: indices)
    {
        ret.push_back(vec.at(ind));
    }
    return ret;
}

Moreover, it is the easiest to read of the three implementations.


Calculation of trigonometric sine function

Do not use power and factorial. Notice that

  $$x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \ldots = x(1 - \frac{x^2}{2*3}(1 - \frac{x^2}{4*5}(1 - \frac{x^2}{6*7}(1 - \ldots))) \ldots) $$

Now calculate it backwards from the innermost term:

  <!-- sin(x) = x(1 - (x^2/2*3)(1 - (x^2/4*5)(1 - (x^2/6*7)))) -->
  <xsl:template name="sin">
    <xsl:param name="degrees" />
    <xsl:param name="radians" select="$degrees * $PI div 180" />
    <xsl:param name="iter" select="31" />
    <xsl:param name="result" select="1" />

    <xsl:variable name="term" select="($radians * $radians) div (($iter - 1) * $iter)" />

    <xsl:choose>
      <xsl:when test="$iter &gt; 2">
        <xsl:call-template name="sin">
          <xsl:with-param name="radians" select="$radians" />
          <xsl:with-param name="iter" select="$iter - 2" />
          <xsl:with-param name="result" select="1 - ($term * $result)" />
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise><xsl:value-of select="$radians * $result" /></xsl:otherwise>
    </xsl:choose>
  </xsl:template>


Insert values into two different but similar tables

Declare a method:

public void InsertInto(string table) {
  string myConnection = "datasource=localhost; port=3306; username=root;password=root";
  string insert = "insert into budget." + table + " (name, suma) values (@name, @price);";

  using (var conDataBase = new MySqlConnection(myConnection))
  using (var cmdDataBase = new MySqlCommand(iterpti, conDataBase)) {
    cmdDataBase.Parameters.AddWithValue("@name", name);
    cmdDataBase.Parameters.AddWithValue("@price", suma);
    conDataBase.Open();
    cmdDataBase.ExecuteNonQuery();
    MessageBox.Show("Saved");
  }
}

And change your code to call the method:

if (comboBox4.SelectedItem.ToString() == "Salary") {
    InsertInto("salary");
}
if (comboBox4.SelectedItem.ToString() == "Other") {
    InsertInto("other");
}

Declaring a method that does what you want and then calling the method multiple times instead of repeating your code multiple times is the standard way to avoid duplicating code. This principle is known as encapsulation and is very necessary for writing clean, readable, and reusable code. You should get used to using this technique whenever possible.

More info: https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)


jQuery buttons to show/hide info and search

The first thing that comes to my mind is that what you're trying to do is handling all of the click events in just one handler function! Don't!

Use delegate event listeners instead:

$(document)
    .on("click", ".info-icon, .info-tab", function(e) {
       e.stopPropagation();
       // Deal with .info-icon or .info-tab
    })
    .on("click", ".search-icon, .search-tab", function(e) {
       e.stopPropagation();
       // Deal with .search-icon or .search-tab
    })
    .on("click", function(e) {
       // Other clicks
    });

Secondarily, define CSS classes list .info-tab-open and .search-tab-open like these:

.info-tab-open {
    max-height: 200px;
}

(And remember: using magic numbers is bad, especially when styling with JavaScript.)

So you'll end up doing this instead:

var $infoTab = $(".info-tab");
if ($infoTab.hasClass("info-tab-open")) {
    $infoTab.removeClass("info-tab-open");
} else {
    var $searchTab = $(".search-tab");
    if ($searchTab.hasClass("search-tab-open")) {
        $searchTab.removeClass("search-tab-open");
        setTimeout(..., 300);
    } else {
        $infoTab.addClass("info-tab-open");
    }
}

Third: since the handler's code is basically the same and repeating code is a code smell, you'll probably be better off if you use a factory function for the handler:

function toggler(selectedClass, otherClass) {
    return function(e) {
        e.stopPropagation();
        var $selectedTab = $("." + selectedClass);
        if ($selectedTab.hasClass(selectedClass + "-open")) {
            $selectedTab.removeClass(selectedClass + "-open");
        } else {
            var $otherTab = $("." + otherClass);
            if ($otherTab.hasClass(otherClass + "-open")) {
                $otherTab.removeClass(otherClass + "-open");
                setTimeout(..., 300);
            } else {
                $selectedTab.addClass(selectedClass + "-open");
            }
        }
    };
}

$(document)
    .on("click", ".info-icon, .info-tab", toggler("info-tab", "search-tab"))
    .on("click", ".search-icon, .search-tab", toggler("search-tab", "info-tab"))
    .on("click", function() {
        $(".info-tab").removeClass("info-tab-open");
        $(".search-tab").removeClass("search-tab-open");
    });


More Pythonic version of finding substring with one glob-like expression

Language interpretation

  Should one be able to escape escapes? –  icktoofay Jun 21 at 23:47

  No, one should not :) –  ProfHase85 Jun 22 at 8:26

I agree with @icktoofay's suggestion.  In the absence of any indication to the contrary, I would assume that any backslash in the globlike expression should cause the following character to be interpreted literally.  That means that \\ (a pair of backslashes) should be interpreted as one literal backslash.

In general, any sane language that has an escaping mechanism must also have a way to let you specify a literal sequence of characters that looks like an escape.  Examples:

String literals in C and Python: \\ is a literal backslash.
printf() format strings: %% produces a literal % character in the output.
HTML and XML: &amp; is a literal &.
LDAP search filters: \5c matches a literal \.

If it were not possible to escape escapes, how would one search for a literal \* (backslash, asterisk) in the text?  Based on norms established by C string literals, I would expect the globlike expression \\\* to accomplish that goal.

With that interpretation,

re.split(r'(?<!\\)\*', ss)

is insufficient for the task. The interpretation should depend on whether there are an even or odd number of backslashes preceding the asterisk.

Search technique

Anything other than a one-pass search is likely doomed to failure.  If you search for literal substrings, you are likely to have problems handling overlapping sequences.  Even if you fix the overlap problem, you would likely still have problems dealing with repeating substrings in the pattern.  If there are multiple wildcards in the pattern, you would also need to support backtracking.

In short, I don't recommend that approach at all.

Driver

   for line in open(sys.argv[1]).read().splitlines():
       if line:
           print is_ss(*line.split(','))

I recommend using fileinput.input() so that the program will read its data from either stdin or a given filename.

Personally, I would also prefer not to read in the entire file at once, for scalability.

I would consider it good practice to limit split() to two elements.  The problem is silent on how a third comma on the line should be interpreted, but I would treat it as a literal character in the globlike expression (even if it will always result in a match failure).

I would also decompose the problem differently.  is_ss(s, ss) (confusingly named function and parameters, by the way) is responsible for interpreting ss as a pattern, performing the match, and returning "true" or "false".  That's actually two or three separate tasks.

Suggested solution

Since matching individual substrings is a problematic strategy, and writing a pattern matcher from scratch seems like it would be tedious, I've chosen to translate globs into regular expressions.  The trick is to escape everything except unescaped asterisks.

As a bonus, obtaining a regular expression converts the task to a solved problem.  The performance characteristics of regular expression matching in Python are well known.  Pushing the responsibility of performing the match to the main loop is also a benefit, in my opinion.

import fileinput
import itertools
import os
import re

def globlike_to_re(expr):
    def unescaped_globlike_to_re(expr):
        '''Convert a globlike expression to a regex pattern.  The expr
        parameter is guaranteed to contain no backslashes, unless it is the
        last character.  Therefore, any asterisk in expr means "match
        anything", and everything else is taken literally.'''
        return r'.*'.join(re.escape(literal) for literal in expr.split('*'))

    # [glob, literal, glob, literal, ..., glob]
    pairs = re.split(r'\\(.)', expr)

    lang = itertools.cycle([unescaped_globlike_to_re, re.escape])
    return re.compile(''.join(interp(expr) for interp, expr in zip(lang, pairs)))

for line in fileinput.input():
    haystack, needle = line.rstrip(os.linesep).split(',', 2)
    print 'true' if globlike_to_re(needle).search(haystack) else 'false'


More efficient conversion of tab-formatted nested data structure to json

I have not programmed in python but you should be able to do this in one shot. In pseudo-code it should be something like so:

function parseJsonInput (file)
   var parsedJson= {};
   var parentStack = [parsedJson]
   for each line in file
     var data = parseLine(line) //return key,value,level. null if not avail for each field

     //leaf item process it by adding it to its current parent
     if data.value is not null
        var currentParent = parentStack.getLastElement()
        currentParent[data.key] = data.value
        var nextLineLevel = parseLine( peekNextLine() ).level; //peek next line level
        if nextLineLevel = data.level - 1
          parentStack.pop() //done processing child, about to go back to parent
     else
        //group node, push it as the new parent and keep on processing.
        //created more variable than needed for clarity
        var currentParent = parentStack.getLastElement()
        currentParent[data.key] = {}
        var newParent = currentParent[data.key]
        parentStack.push( newParent )
   endfor

    return parsedJson;

end function

I haven't tried that but that should work give or take few bugs. But the basic idea as I mentioned in the comment is to transverse the file iteratively as a tree structure using iterative post-tree-transversal method. I'm not sure if the 'peekNextLine' is available to you, if not then you would need another variable to keep track of the last level processed and strategically insert that logic there -- I started doing this, but figured it might be confusing at first. Let me know if there is some issues. I can help. If I have time I can even write a quick javascript version for you to learn from.


Double event listener for single function

The only suggestion I have is..

"click scroll".split(" ") ... why? what was that person thinking?

['click', 'scroll'].forEach() is both faster and shorter.

Aside from that, looks great!