Finding the prime factors of a number in Python 2 I’ve created a function that takes a number and, if it’s prime, tells you so, or if it’s composite, gives you the prime factors of the number (and if it’s 1, tells you that it’s neither).
Theoretically it should work for an infinitely large number, but at 8 digits it starts to slow down significantly, particularly if the prime factors are large. I’m fairly new at Python, so I’d welcome any feedback, especially on how to make it faster.
I’m aware that there are things I could have done more efficiently from the start — some of which I’ve become aware from looking at other Python questions in this same vein on this site — but while I would find advice like ‘this bit’s ill-conceived, rip it out and write something else entirely’ helpful, I’d prefer best-practices things, and ways to make it faster without totally changing the premises (as it were).
I haven’t annotated it because (as far as I’m aware), it’s fairly basic; any old hack could write this, but obviously I can annotate if you’d like.
Thanks!
Here’s the code (in Python 2):
import math
def prime_factors(y):
 n = y
 def is_prime(x):
    count = 0
    if x > 1:
      for i in range(2, x):
        if x % i != 0:
          count += 1
        else:
          return False
          break
    else:
        return True
    if count != 0:
        return True
    if x == 2:
      return True
 def make_p_lst(x):
   z = []
   for i in range(2, x):
     if is_prime(i) == True:
       z.append(i)
   return z

 c = 0
 c = int(math.sqrt(y) + 1)
 prime_lst = []
 prime_lst = make_p_lst(c)
 p = is_prime(y)
 if p == True and y != 1:
   print '%s is prime.' % (y)
   return 'Thus, its\' only factors are 1 and itself.'
 elif y != 1:
   print '%s is composite, here are its\' prime factors: ' % (y)
   factors_lst = []
   while is_prime(y) != True:
      for i in prime_lst:
        if y % i == 0:
          y = y/i
          factors_lst.append(i)
   factors_lst.append(y)
   factors_lst.sort()
   if factors_lst[0] == 1:
     factors_lst.remove(1)
   n = factors_lst
   return n
 else:
   return '1 is neither prime nor composite.'
print prime_factors(871)

(Obligatory) Python 2 is end of life it is advised to upgrade to Python 3.
You should always indent with 4 spaces in Python. This makes it easier for me to read what is inside prime_factors and what is outside of it.
It's common to surround top level functions (prime_factors) with 2 empty lines, and other functions (is_prime, make_p_lst) with one empty line.

Otherwise your whitespace is good. Here is what it'd look like with these fixed.
import math

def prime_factors(y):
    def is_prime(x):
        count = 0
        if x > 1:
            for i in range(2, x):
                if x % i != 0:
                    count += 1
                else:
                    return False
                    break
        else:
            return True
        if count != 0:
            return True
        if x == 2:
            return True

    def make_p_lst(x):
        z = []
        for i in range(2, x):
            if is_prime(i) == True:
                z.append(i)
        return z

    n = y
    c = 0
    c = int(math.sqrt(y) + 1)
    prime_lst = []
    prime_lst = make_p_lst(c)
    p = is_prime(y)
    if p == True and y != 1:
        print '%s is prime.' % (y)
        return 'Thus, its\' only factors are 1 and itself.'
    elif y != 1:
        print '%s is composite, here are its\' prime factors: ' % (y)
        factors_lst = []
        while is_prime(y) != True:
            for i in prime_lst:
                if y % i == 0:
                    y = y / i
                    factors_lst.append(i)
        factors_lst.append(y)
        factors_lst.sort()
        if factors_lst[0] == 1:
            factors_lst.remove(1)
        n = factors_lst
        return n
    else:
        return '1 is neither prime nor composite.'

print prime_factors(871)

You don't need is_prime or make_p_lst to be inside prime_factors. This is making your code harder to read as it's not immediately apparent that you are not using them as closures.

All code after a return will not run. This means the break in is_prime will not run.

Your is_prime function doesn't handle 0 and 1 correctly.
>>> [(i, is_prime(i)) for i in range(6)]
[(0, True), (1, True), (2, True), (3, True), (4, False), (5, True)]

Since it's not already we can change your code to be simpler by removing all the count parts.
Then we can just special case 0 and 1.
def is_prime(x):
    if x <= 1:
        return False

    for i in range(2, x):
        if x % i == 0:
            return False
    return True

In make_p_lst you shouldn't do if is_prime(i) == True instead you should just use if is_prime(i).

In prime_factors you shouldn't do while is_prime(y) != True instead you should just use while not is_prime(y).

We can simplify the code by using a list comprehension. This is just syntactic sugar for building the list as your are now.

You don't need to initialize a value and then assign it.

c = 0
c = int(math.sqrt(y) + 1)
prime_lst = []
prime_lst = make_p_lst(c)

You can just remove the first of each.
c = int(math.sqrt(y) + 1)
prime_lst = make_p_lst(c)

By fixing is_prime we don't need the and y != 1 check.

Getting the prime factors should be put into a function.

Many of your variable names are hard to understand or follow.
You should really use better names than x, i, c, y, etc.
Additionally I prefer using plurals to denote a list of items.
For example the following is much easier to read.
for prime in primes:
    # do something with prime

Because I changed is_prime to make 1 no longer return True, the code to get the prime factors no longer works for 1. However we can fix that by moving the while loop into the for loop.
Then we can merge it with the if.
This has the benefit that we don't have to loop through prime_lst multiple times and we won't call is_prime.

def is_prime(number):
    if number <= 1:
        return False
    for divisor in range(2, number):
        if number % divisor == 0:
            return False
    return True

def primes_below(limit):
    return [number for number in range(2, limit) if is_prime(number)]

def get_prime_factors(number):
    if number == 0:
        return []
    primes = primes_below(int(number ** 0.5 + 1))
    factors = []
    for prime in primes:
        while number % prime == 0:
            number /= prime
            factors.append(prime)
    if number != 1:
        factors.append(number)
    return factors

def prime_factors(number):
    prime = is_prime(number)
    if prime:
        print '%s is prime.' % (number)
        return 'Thus, its\' only factors are 1 and itself.'
    elif number != 1:
        print '%s is composite, here are its\' prime factors: ' % (number)
        return get_prime_factors(number)
    else:
        return '1 is neither prime nor composite.'

print prime_factors(871)

At this point it'd be good to rethink how your code works.
prime_factors sometimes returns the prime factors. However other times it returns a string.
It also prints to the screen which is not helpful if I only want the prime factors.
Your function prime_factors should do no string manipulation.
This means it should return a list of prime factors and only a list of prime factors.

0 would return an empty list.
1 would return an empty list.
2 would return 2.
4 would return 2 and 2.

And so we can see get_prime_factors is what should actually be prime_factors.
And so we can change main to use only get_prime_factors and only print.
Returning from main is not a good idea.
def is_prime(number):
    if number <= 1:
        return False
    for divisor in range(2, number):
        if number % divisor == 0:
            return False
    return True

def primes_below(limit):
    return [number for number in range(2, limit) if is_prime(number)]

def prime_factors(number):
    if number == 0:
        return []
    primes = primes_below(int(number ** 0.5 + 1))
    factors = []
    for prime in primes:
        while number % prime == 0:
            number /= prime
            factors.append(prime)
    if number != 1:
        factors.append(number)
    return factors

def main(number):
    factors = prime_factors(number)
    if not factors:
        print '1 is neither prime nor composite.'
    elif len(factors) == 1:
        print '%s is prime.' % (number)
        print 'Thus, its only factors are 1 and itself.'
    else:
        print '%s is composite, here are its prime factors: ' % (number)
        print factors

if __name__ == '__main__':
    main(871)


Convert two collections of different objects into a single collection I am combining two lists of separate objects into a single combined list. The below code works perfectly but it is not the most elegant or efficient solution. Is there a better solution?

var articles = context.Articles.Where(a => a.Author.ID == authorID).ToList();
var reviews = context.Reviews.Where(a => a.Author.ID == authorID).ToList();

var items = articles.ConvertAll(x => new ItemViewModel(x.ID, x.Title, x.Summary, "article", x.PublishDate)).Union(reviews.ConvertAll(r => new ItemViewModel(r.ID, r.Title, r.Summary, "review", r.PublishDate))).Take(20).OrderByDescending(i => i.publishDate);

Let's start with some sensible line continuation and indentation so we can see what's actually going on here.

var articles = context.Articles.Where(a => a.Author.ID == authorID).ToList();
var reviews = context.Reviews.Where(a => a.Author.ID == authorID).ToList();

var items = articles.ConvertAll(x => new ItemViewModel(x.ID, x.Title, x.Summary, "article", x.PublishDate))
    .Union(reviews.ConvertAll(r => new ItemViewModel(r.ID, r.Title, r.Summary, "review", r.PublishDate))
    ).Take(20)
    .OrderByDescending(i => i.publishDate));

Not perfect, but better. Remember, it's not necessary to cram all those lambdas onto a single line.

Is there a reason you're calling ToList()? That forces the execution of the query. If this is hitting a database with a lot of records, that could be potentially expensive.

You could also potentially clean up the second query a bit by moving the "converts" to the the prior queries.

var articles = context.Articles.Where(a => a.Author.ID == authorID)
    .ConvertAll(x => new ItemViewModel(x.ID, x.Title, x.Summary, "article", x.PublishDate));

var reviews = context.Reviews.Where(a => a.Author.ID == authorID)
    .ConvertAll(r => new ItemViewModel(r.ID, r.Title, r.Summary, "review", r.PublishDate));

var items = articles.Union(reviews)
    .Take(20)
    .OrderByDescending(i => i.publishDate));

Which shows us a potential opportunity to extract a method to remove the duplication.

Lastly, are you sure this does what you intend it to do? You didn't tell us exactly what you're trying to accomplish, but usually I would want to sort the results prior to selecting the top x results. I can't recall off the top of my head which order of Take and OrderBy would produce the correct results, but you should definitely double check that you're getting the information that you think you are.

*You might need to work on the Union syntax a bit. I'm not sitting in front of my IDE, so I didn't try to compile it.


Determine the ratio of the contents of a pot to the (metal) volume of of the pot This is my first Python project, so:

create a pot with dimensions (radius, thickness of wall, thickness of base, height), fill it with food (to a specific height). Determine the ratio between the volume of the food and the volume of the (metal in the) pot.

I am aware that this code does not take handles, rims, dents and other funny stuff into consideration.

import math
pi = math.pi
class Pot:
    """create a pot with contents, determine the ratio between the contents and the pot"""

    def __init__(self,inner_radius,wall_width,base_thickness,height,content_height):
        self.wall_width = wall_width
        self.inner_radius = inner_radius
        self.outer_radius = self.inner_radius + self.wall_width
        self.base_thickness = base_thickness
        self.height = height
        self.content_height = content_height

    def get_cylinder_volume(self,radius,height):
        cylinder_volume = pi * (radius ** 2) * height
        return cylinder_volume

    def get_pot_wall(self):
        inner_cylinder = self.get_cylinder_volume(self.inner_radius,self.height)
        outer_cylinder = self.get_cylinder_volume(self.outer_radius,self.height)
        pot_wall = outer_cylinder - inner_cylinder
        return pot_wall

    def get_pot_base(self):
        pot_base = self.get_cylinder_volume(self.inner_radius,self.base_thickness)
        return pot_base

    def get_pot_volume(self):
        pot_volume = self.get_pot_base() + self.get_pot_wall()
        return pot_volume

    def get_content(self):
        content = self.get_cylinder_volume(self.inner_radius,self.content_height)
        return content

    def get_ratio(self):
        ratio = self.get_content()/self.get_pot_volume()
        return ratio

    def check_ratio(self,desired):
        if (self.get_ratio() < desired):
            print ("too small")
        else:
            print (self.get_ratio())

You could get rid of many temporary variables, by returning the result right away:

import math
pi = math.pi
class Pot:
    """create a pot with contents, determine the ratio between the contents and the pot"""

    def __init__(self,inner_radius,wall_width,base_thickness,height,content_height):
        self.wall_width = wall_width
        self.inner_radius = inner_radius
        self.outer_radius = self.inner_radius + self.wall_width
        self.base_thickness = base_thickness
        self.height = height
        self.content_height = content_height

    def get_cylinder_volume(self,radius,height):
        return pi * (radius ** 2) * height

    def get_pot_wall(self):
        inner_cylinder = self.get_cylinder_volume(self.inner_radius,self.height)
        outer_cylinder = self.get_cylinder_volume(self.outer_radius,self.height)
        return outer_cylinder - inner_cylinder

    def get_pot_base(self):
        return self.get_cylinder_volume(self.inner_radius,self.base_thickness)

    def get_pot_volume(self):
        return self.get_pot_base() + self.get_pot_wall()

    def get_content(self):
        return self.get_cylinder_volume(self.inner_radius,self.content_height)

    def get_ratio(self):
        return self.get_content()/self.get_pot_volume()

    def check_ratio(self,desired):
        if (self.get_ratio() < desired):
            print ("too small")
        else:
            print (self.get_ratio())

Also, many of your variables are already determined when you initialize the class. Unless you want to change the shape of the pot on the fly (for this I would create a new instance of Pot with the new dimensions), the only thing I would expect to change is the amount of content in the pot. So, pot_wall, pot_base, pot_volume can all be calculated in init and set to variables of the instance:

def __init__(self,inner_radius,wall_width,base_thickness,height,content_height):
        self.inner_radius = inner_radius
        self.content_height = content_height
        outer_radius = inner_radius + wall_width

        self.pot_volume = self.get_cylinder_volume(inner_radius,base_thickness) + self.get_cylinder_volume(outer_radius,height) - self.get_cylinder_volume(inner_radius,height)

...

def get_ratio(self):
    return self.get_content()/self.pot_volume

This would allow you to get rid of get_pot_wall, get_pot_base, get_pot_volume. Or at least the first two, if this is too much inline calculation for you.


hl7 parser with fparsec I have a little experience working with .hl7 data (format for transmitting health data), so I decided to try and write an .hl7 parser using fparsec.

A standard .hl7 segment is a single line with:

First 3 chars are the header
Next 5 chars are the separators (typically |^~\&)
Fields / repetitions delimited by pipes

A segment has fields or repetitions (repeating fields).  A field can have components.   A component can have sub-components.

Sample .hl7 message header:

MSH|^~\\&|Location|SendingApp|DateTimeOfMessage

I am looking for feedback on data design (the types) and the functions.

type Subcomponent = {value:string; position:int}
type Component = {subcomponents: Subcomponent list; position:int}
type SingleField = {components: Component list; position:int}
type Field = Repetitions of SingleField list | SingleField of SingleField
type Segment = { name:string; fields:Field list; }
type Hl7Message = { segments:Segment list }

let hl7Seps = "|^~\\&"

let normalChar = noneOf hl7Seps

let unescape c = match c with
                    | 'F' -> '|'
                    | 'R' -> '~'
                    | 'S' -> '^'
                    | 'T' -> '&'
                    | 'E' -> '\\'
                    | c -> c

let escapedChar = attempt (pchar '\\' >>. anyChar |>> unescape .>> skipChar '\\') <|> pchar '\\'

let pHl7Element = manyChars (normalChar <|> escapedChar)

let pcomp = sepBy pHl7Element (pchar '&') |>> (fun vals -> List.mapi (fun i s -> {value = s; position = i}) vals)

let pfield = sepBy pcomp (pchar '^') |>> (fun comps -> List.mapi (fun i c -> {subcomponents = c; position = i}) comps)

let pRepsOrField = sepBy pfield (pchar '~') |>> (fun fields -> match fields.Length with
                                                                | 0 | 1 -> SingleField {components = fields.Item 0; position = 0}
                                                                | _ -> Repetitions (List.mapi (fun i c -> {components = c; position = i}) fields))

let pheader = anyString 3 |>> (fun name -> name)

let pSegment = pipe2 pheader (sepBy pRepsOrField (pchar '|')) (fun name repsOrFields -> {name = name; fields = repsOrFields})

test pSegment "EVN|A&1^B^C|123~456~789"

I am not really familiar with Fparsec, but a few of your functions could be simplified, or written better:

For example :

let pcomp = sepBy pHl7Element (pchar '&') |>> (fun vals -> List.mapi (fun i s -> {value = s; position = i}) vals)

Using partial application, it could be written as :

let pcomp = sepBy pHl7Element (pchar '&') |>> (List.mapi (fun i s -> { value = s; position = i }))

And the one after it:

// Before
let pfield = sepBy pcomp (pchar '^') |>> (fun comps -> List.mapi (fun i c -> {subcomponents = c; position = i}) comps)
// After
let pfield = sepBy pcomp (pchar '^') |>> (List.mapi (fun i c -> { subcomponents = c; position = i }))

Also, (fun x -> x) could be simply replaced by id.

let pheader = anyString 3 |>> id

On other matters, there is a potential bug in your code : in your pRepsOrField function, you're matching field.Length with 0 then extracting the first item, which will crash your code. Using the Length property to find out the length is .. unusual. You don't even need it. Pattern matching with lists based on length in F# is usually done this way:

match fields with
| [] -> // do something
| [ c ] ->  SingleField { components = c; position = 0 }
| _ -> Repetitions(List.mapi (fun i c -> { components = c; position = i }) fields))

Now you don't have to use extra methods/properties to get the length and and the first item. It is all right there ...


Neatest way of including a header and footer on every page I just got into Object Oriented Programming, and it made me think about certain code how I can make them as efficient as possible.

Right now I am just including my header and footer like the following:

PHP

require_once 'core/init.php';

require_once 'includes/header.php';

//Big block of content goes here

require_once 'includes/footer.php';

I wonder if this is the neatest / most efficient way of doing that?

If you are working in PHP use a framework that has MVC such as Laravel(up and coming and popular), Symphony, Yii, Codeigniter(defunct), etc.

Each of them will enable you to use some reuse mechanism.

Laravel itself uses a template PHP called blade. There are several other template mechanism such as Twig that enables you to template your views to even add more granular way and cleaner.

If its a single file system that you must what you are doing is fine because you are using require_once it enables you to call other files and you can modify that file and it will reflect any other files that references it.


Particle in Cell: efficient data structure handling I am building a simulation where you have 'Agents' distributed over a rather large landscape. Because the number of Agents is small, compared to the size of the landscape, I use the PIC approach where the landscape is divided into rather large cells and every cell can contain multiple agents - in contrast to a classical grid based approach. This should speed up spatial analysis.

I am asking whether there is a way to improve the code I came up with:

Agents contain an iterator to the node in the cell and a ptr to the cell containing the node

class Agent;

typedef std::list <Agent*> CELL;

class Agent {
  public:
  //...stuff...
    CELL::iterator cell_iter;
    CELL*cell_ptr;
};

class Grid {
  public:
    Grid(int dimx,int dimy,int cellsize);
    CELL *GetCell(double x,double y);
 private:
    std::vector <std::vector<CELL>> grid_;
    int dimx_,dimy_,cellsize_,ncellx_,ncelly_;
};

To add a new individual:

std::list <Agent> population;
//..stuff...
Agent seed(pos_x,pos_y,seed_type,10.1); // create a local agent
population.push_back(std::move(seed));
Agent *agent=&population.back()
CELL *cell=GetCell(agent->x_,agent->y_); // get the cell for the agents pos
cell->push_back(agent); // add the agents ptr to the cell
agent->cell_ptr=cell; // save the agents cell to the agent
agent->cell_iter=--cell->end(); // save an iterator to the actual node

To delete an individual

auto iter=population.begin();
//...stuff...
(*iter).cell_ptr->erase((*iter).cell_iter); // erase the ptr to the agent from the cell
iter=population.erase(iter);

If you have move push_back then you should also have emplace_back.

population.emplace_back(pos_x,pos_y,seed_type,10.1);

Erasing the individual means moving everyone that comes after. If you don't care about order then do a swap with back:

auto iter=population.begin();
//...stuff...
(*iter).cell_ptr->erase((*iter).cell_iter); // erase the ptr to the agent from the cell
std::swap(*iter, population.back());
population.pop_back();
//doesn't invalidate iter


Reduce code handling start and end datepickers I have a select with 3 options and two datepickers, a start and an end date. Based on the option selected, the date end date can either be any future date or limited to a 30 day date range. In the jsFiddle provided below, when Option 1 is selected, the date range is restricted to 30 days. If either Option 2 or Option 3 are selected, the end date can be any future date.

Here is a complete working jsFiddle with the complete code.

I haven't run into any issues with the code below.  I'm just wondering if anyone has any suggestions on how I could go about reducing it as it just seems too "bulky".

$('#startDate, #endDate').datepicker({
    beforeShow: setDateRange,
    dateFormat: "mm/dd/yy",
    firstDay: 1,
    changeFirstDay: false,
    onChange: function() { $(this).valid(); },
    onSelect: function() {
        if (this.id == 'startDate') {
            var date = $('#startDate').datepicker('getDate');
            if (date) { date.setDate(date.getDate() + 1); }
            $('#endDate').datepicker('option', 'minDate', date);
        }
    }
});

function setDateRange(input) {
    var min = null, dateMin = min, dateMax = null, dayRange = 30;
    var opt = $('#select1'), start = $('#startDate'), end = $('#endDate');
    if (opt.val() == '1') {
        if (input.id == 'startDate') {
            if ($('#endDate').datepicker('getDate') != null) {
                dateMax = $('#endDate').datepicker('getDate');
                dateMin = $('#endDate').datepicker('getDate');
                dateMin.setDate(dateMin.getDate() - dayRange);
                if (dateMin < min) { dateMin = min; }
            }
        } else if (input.id == 'endDate') {
            dateMin = $('#startDate').datepicker('getDate');
            dateMax = new Date(dateMin.getFullYear(),
                dateMin.getMonth(), dateMin.getDate() + 30);
            if ($('#startDate').datepicker('getDate') != null) {
                var rangeMax = new Date(dateMin.getFullYear(),
                    dateMin.getMonth(), dateMin.getDate() + dayRange);
                if (rangeMax < dateMax) { dateMax = rangeMax; }
            }
        }
    } else if (opt.val() != '1') {
        if (input.id == 'startDate') {
            if ($('#endDate').datepicker('getDate') != null) {
                dateMin = null;
            }
        } else if (input.id == 'endDate') {
            dateMin = $('#startDate').datepicker('getDate');
            dateMax = null;
            if ($('#startDate').datepicker('getDate') != null) { dateMax = null; }
        }
    }
    return {
        minDate: dateMin,
        maxDate: dateMax
    };
}

I posted this on Stack Overflow a couple months back when I was initially trying to figure out how to get it working. The post goes into a little more detail on the option selections but I have since added on to it some. For example, the code above now includes an onSelect when the datepickers are initialized.

If anyone has any suggestions on how I could go about improving this, please let me know.

From a once over;

This code does not do what the tin says:

// If selected start date is later than currently selected
// end date, set end date to start date + 1 day
var date = $('#startDate').datepicker('getDate');
if (date) { date.setDate(date.getDate() + 1); }

what this actually does is always set the first possible date to startdate + 1
Not sure about this :)

<option value="2">Any Future Date</option>
<option value="3">Any Future Date</option>

The continued checks for input.id are a good indication that perhaps you need 2 distinct functions
The id's 1 and 2 are rather meaningless, they could be meaningful strings, or even better they could be function names that need to be executed.
There a number of non-sensical assignments like here:

dateMax = null;
if ($('#startDate').datepicker('getDate') != null) { dateMax = null; }

if you set dateMax already to null, then why would you set dateMax again to null?
Your code dies when the user tries to select an end date without first selecting first a starting date in 30 days mode with Cannot read property 'getFullYear' of null because you are indeed trying to calculate on an empty field..
I am not sure why in 30 day mode the start date is impacted by the end date, especially since clearing out the end date opens up the calendar again.

All in all, I would go with something like this:

$('#startDate, #endDate').datepicker({
    beforeShow: setDateRange,
    dateFormat: "mm/dd/yy",
    firstDay: 1,
    changeFirstDay: false,
    onChange: function () {
        $(this).valid();
    }
});

var dateLogic = {

    addDays: function addDays(initialDate, dayCount) {
        var newDate = new Date(initialDate);
        newDate.setDate(newDate.getDate() + dayCount);
        return newDate;
    },
    openWide: {
        minDate: null,
        maxDate: null
    },
    futureDays: {
        startDate: function startDateFutureDays(currentStart, currentEnd) {
            return !currentEnd ? dateLogic.openWide : {
                minDate: null,
                maxDate: dateLogic.addDays(currentEnd, -1)
            }
        },
        endDate: function endDateFutureDays(currentStart) {
            return {
                minDate: currentStart,
                maxDate: null
            }
        }
    },
    thirtyDays: {
        startDate: function startDateThirtyDays(currentStart, currentEnd) {
            return !currentEnd ? dateLogic.openWide : {
                maxDate: currentEnd,
                minDate: dateLogic.addDays(currentEnd, -30)
            };
        },
        endDate: function endDateThirtyDays(currentStart) {
            return !currentStart ? dateLogic.openWide : {
                minDate: currentStart,
                maxDate: dateLogic.addDays(currentStart, 30)
            }
        }
    }
};

function setDateRange(input) {

    var opt = $('#select1'),
        startDate = $('#startDate').datepicker('getDate'),
        endDate = $('#endDate').datepicker('getDate');

    return dateLogic[opt.val()][input.id](startDate, endDate);
}

$('#select1').change(function () {
    $('#startDate, #endDate').val('');
    $('#startDate, #endDate').removeAttr('disabled');
});

You can play with this on http://jsfiddle.net/konijn_gmail_com/rc0kr718/


Loading and converting data from CSV My application imports a CSV file and parses each row, turning it into an object in my code.

The speed for a 500,000 row x 68 column takes 2+ minutes to read. I've narrowed down the bottleneck to the part where the strings are being converted into their respective types using the converter I created. I need some pointers on how I can optimize my code.

This is the code I use to load:

public static void Load(object target, string[] fields, bool supressErrors)
{
    Type targetType = target.GetType();
    PropertyInfo[] properties = targetType.GetProperties();

    foreach (PropertyInfo property in properties)
    {
        object[] attributes = property.GetCustomAttributes(typeof(CSVPositionAttribute), false);

        if (attributes.Length > 0)
        {
            CSVPositionAttribute positionAttr = (CSVPositionAttribute)attributes[0];

            int position = positionAttr.Position;
            try
            {
                object data = fields[position];

                if (positionAttr.DataTransform != string.Empty)
                {
                    MethodInfo method = targetType.GetMethod(positionAttr.DataTransform);
                    data = method.Invoke(target, new object[] { data });
                }
                var prop = property.PropertyType;

                //bottleneck here:
                if (prop == typeof(string))
                {
                    property.SetValue(target, CheckAndConvert.CheckString(data), null);
                }
                else if (prop == typeof(int))
                {
                    property.SetValue(target, CheckAndConvert.CheckInt(data.ToString()), null);
                }
                else if (prop == typeof(double))
                {
                    property.SetValue(target, CheckAndConvert.CheckDouble(data.ToString()), null);
                }
                else if (prop == typeof(long))
                {
                    property.SetValue(target, CheckAndConvert.CheckLong(data.ToString()), null);
                }
                else if (prop == typeof(bool))
                {
                    property.SetValue(target, CheckAndConvert.CheckBool(data.ToString()), null);
                }

            }
            catch(Exception e)
            {
                if (!supressErrors)
                    throw;
            }
        }
    }
}

This is part of the code I use to convert each cell:

public class CheckAndConvert
{
    public static int CheckInt(string input)
    {
        int convertedInput = 0;
        double convertedInput2 = 0;

        if (int.TryParse(input, out convertedInput))
        {
            return convertedInput;
        }
        else if (double.TryParse(input, out convertedInput2))
        {
            return (int)convertedInput2;
        }
        else
        {
            return 0;
        }
    }
    public static double CheckDouble(string input)
    {
        double convertedInput = 0;
        int convertedInput2 = 0;
        if (double.TryParse(input, out convertedInput))
        {
            return convertedInput;
        }
        else if (int.TryParse(input, out convertedInput2))
        {
            return convertedInput2;
        }
        else
        {
            return 0;
        }
    }
    public static bool CheckBool(string input)
    {
        bool convertedInput = true;
        if (bool.TryParse(input, out convertedInput))
        {
            return convertedInput;
        }
        else
        {
            return true;
        }
    }
    public static string CheckString(object input)
    {
        if (input == null)
        {
            return "";
        }
        else
        {
            return input.ToString();
        }
    }

}

There's a few ways you could improve your CheckAndConvert class and functions.

Design Suggestions

Fluency - It's not a requirement by any means but fluency helps readability. CheckAndConvert.CheckInt is almost a sentence, perhaps something shorter Parse.Int or Parse.Bool.
Naming Simplicity - On the lines of the previous suggestion, your class/function names imply that it's doing more than simply parsing a given value. You're checking if the parse succeeds but then returning a default value if it fails. The user of this function needs not to know about the check part at all. And the word check is repeated (class and function name). Programmers don't typically like redundancy.
Naming Accuracy - CheckInt and CheckDouble they check each other if their primary data type TryParse fails. In the case of CheckDouble I don't think it's ever going to be true for the second if-statement. In the case of CheckInt since int.TryParse can fail on decimals that you want to be integers I would just always use double.TryParse with a cast. (Remember: Cast truncates and Convert.ToInt32 rounds).

I would be surprised if any of the above suggestions other than maybe the removal of int.TryParse would actually improve performance but it would still make for some cleaner simpler code.

Performance

If you've narrowed down that the parsing of values into their respective properties is the time consumer research alternative ways to parse numbers (they're ugly but claim they're faster) additionally this might be helpful for possibly speeding up your SetValue calls (be warned it's a long read).

Link Information

The parse numbers link decribes parsing the string yourself as .Parse uses CultureInfo and stuff that can slows it down.
The SetValue link describes research into using delegates for method calls in reflection and shows some promising performance boosts that I've used myself.


Compare JS files and pick according to requirement Problem Statement:

Extract the filename and read if filename has jQuery on it, put them aside.
Second step will be to check one more and see if any jQuery files has ui in the filename.

Input:

script_ref1 = """<script type="text/javascript" src="js/jquery-1.9.1.min.js"/>
    <script type="text/javascript" src="js/jquery-migrate-1.2.1.min.js"/>
    <script type="text/javascript" src="js/jquery-ui.min.js"/>
    <script type="text/javascript" src="js/abc_bsub.js"/>
    <script type="text/javascript" src="js/abc_core.js"/>
    <script type="text/javascript" src="js/abc_explore.js"/>
    <script type="text/javascript" src="js/abc_qaa.js"/>"""

OR

script_ref2 = """<script type="text/javascript" src="js/jquery-1.9.1.min.js"/>
    <script type="text/javascript" src="js/jquery-migrate-1.2.1.min.js"/>
    <script type="text/javascript" src="js/abc_bsub.js"/>
    <script type="text/javascript" src="js/abc_core.js"/>
    <script type="text/javascript" src="js/abc_explore.js"/>
    <script type="text/javascript" src="js/abc_qaa.js"/>"""

And:

div_attr_info = {"data-js":"jquery-1.8.1.min.js, jquery-ui-1.2.min.js, custom1.js, custom2.js"}

Output:

for script_ref1

doc_js: [' custom1.js', ' custom2.js']

for script_ref2

doc_js: [' jquery-ui-1.2.min.js', ' custom1.js', ' custom2.js']

Algorithm:

Set jquery_flag and jquery_ui_flag flag to False.
Extracting specific src attributes from script tags.
Iterate on step2 result.
Set jquery_flag to True because jquery is substring in the file list.
Check ui is substring or not. and set jquery_ui_flag according to it.
Get JS file list from the dictionary for comparison.
Iterate and Do comparison.
Print result.

Can the code be improved or optimized? Can I reduce the runtime?

jquery_flag = False
jquery_ui_flag = False
for ii in re.findall('src="js/([^"]*jquery[^"]*)"', script_ref):
    jquery_flag = True
    if "ui" in ii:
        jquery_ui_flag = True

tmp = div_attr_info["data-js"].split(",")
doc_js = []

for ii in tmp:
    if jquery_ui_flag and "jquery" in ii:
        pass
    elif jquery_flag and not jquery_ui_flag and "jquery" in ii and "ui" not in ii:
        pass
    else:
        doc_js.append(ii)

print "doc_js:", doc_js

Since your post is a little unclear to me, I'm just going to point out a few small things that could be improved quiet a bit.

The program logic could be separated out into different functions. This allows for easy re-usability.
You should flesh out this program with comments for clarity. There are two types of comments, regular comments, and docstrings. Regular comments start with a # character, followed by a description. Docstrings describe functions and classes, like so.

def my_function(args):
    """
    This is a docstring. Put a description
    of your function here.
    """
    ...

class MyClass(object):
    """
    Put a description of your class here.
    """
    ...

You have some bad variable names, like ii, or tmp. Variable names should generally describe what the variable's purpose is.

There's not much for me to review, but if you want me to cover anything else, just mention it in the comments, and I'll see if I can cover it.


Split IEnumerable by predicate In order to divide an IEnumerable in C# by a predicate, I implemented the following (in a static class):

public static IEnumerable<IEnumerable<T>> SplitBeforeIf<T>(this IEnumerable<T> input, Func<T, bool> pred)
{
    //This exists to store the predicate satisfier, which I kept as
    //the first T in the inner IEnumerable (except, maybe the first one).
    T predSatis = default(T);
    while(input.Any())
    {
        var temp = input.TakeWhile(v => !pred(v));
        //I was told that the below is the best test for default-ness.
        //(I assume that pred(default(T)) is always false.)
        if(predSatis == null || predSatis.Equals(default(T)))
            yield return temp;
        else
            yield return (new List<T>{predSatis}).Concat(temp);

        input = input.SkipWhile(v => !pred(v));
        predSatis = input.FirstOrDefault();
        input = input.Skip(1);
    }
    if(predSatis != null && !predSatis.Equals(default(T)))
        yield return new List<T>{predSatis};
}

This returns as follows:

new List<int>{1,2,3,4,5}.SplitBeforeIf(v => v % 2 == 0) gives {{1}, {2,3}, {4,5}}
new List<int>{6,1,2,3,4,5}.SplitBeforeIf(v => v % 2 == 0) gives {{}, {6, 1}, {2,3}, {4, 5}}
new List<int>{1,2,3,4,5,6}.SplitBeforeIf(v => v % 2 == 0) gives {{1}, {2,3}, {4,5}, {6}}.

I have 3 questions (besides any other comments on the code):

I see that, despite my best efforts, this is \$O(n^2)\$. Why? Can this be improved for a generic IEnumerable?
This does not support a stateful predicate or a stateful IEnumerable input. Can this be remedied?
This looks awfully like Clojure's partition-by. How does Clojure avoid the first issue (it may also have the second, but functional programming dislikes state anyway)?

Being a little pedantic about these things, I also would prefer solutions that don't accumulate values into another data structure (just to see if full laziness is possible).

So I thought I'd try this out with a test enumerable.

public class NumberValues : IEnumerable<int>
{
    public NumberValues(int startValue, int endValue)
    {
        _endValue = endValue;
        _startValue = startValue;
        counter = 0;
    }
    public NumberValues(int endValue) : this(0, 10) { }

    public int counter { get; set; }

    public IEnumerator<int> GetEnumerator()
    {

        var iterator = _startValue;
        while (iterator < _endValue)
        {
            Trace.Write(iterator + ",");
            iterator++;
            counter++;
            yield return iterator;
        }

    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

followed closely by

    [TestCase(0,5)]
    [TestCase(1,5)]
    [TestCase(0,6)]
    [TestCase(1,6)]
    [TestCase(0,10)]
    [TestCase(1,10)]
    public void TestSkipBeforeIf(int start, int end)
    {
        var numberValue = new NumberValues(start,end);
        numberValue.SplitBeforeIf(i => i%2 == 0).ToList();
    }

which results in the following output.

0,5 > 0,0,1,0,1,2,0,1,2,3,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,  - 25
1,5 > 1,1,1,2,1,2,3,1,2,3,4,1,2,3,4,1,2,3,4,  - 19
0,6 > 0,0,1,0,1,2,0,1,2,3,0,1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,5,  - 27
1,6 > 1,1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,1,2,3,4,5,  - 21
0,10 > 0,0,1,0,1,2,0,1,2,3,0,1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,5,6,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,8,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,  - 65
1,10 >     1,1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,1,2,3,4,5,6,1,2,3,4,5,6,7,1,2,3,4,5,6,7,8,1,2,3,,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,  - 55

0,20 > 230
0,40 > 860
0,100 > 5150

But why?

        while (input.Any())
        {
            var temp = input.TakeWhile(v => !pred(v));
            if (predSatis == null || predSatis.Equals(default(T)))
                yield return temp;
            else
                yield return (new List<T> { predSatis }).Concat(temp);

            input = input.SkipWhile(v => !pred(v));
            predSatis = input.FirstOrDefault();
            input = input.Skip(1);
        }

if you evaluate your 2 lines

input = input.SkipWhile(v => !pred(v));
predSatis = input.FirstOrDefault();

over iterations of your while loop, it is necessary to expand the input variable for each iteration.

input.SkipWhile(pred).FirstOrDefault
input.SkipWhile(pred).SkipWhile(pred).FirstOrDefault
input.SkipWhile(pred).SkipWhile(pred).SkipWhile(pred).FirstOrDefault
input.SkipWhile(pred).SkipWhile(pred).SkipWhile(pred).SkipWhile(pred).FirstOrDefault

having seen this, we now consider the evaluation of input.SkipWhile(!pred)

so over 100 iterations

pred = x => x % 2 == 0 : 5150
pred = x => x % 3 == 0 : 3600
pred = x => x % 4 == 0 : 2625
pred = x => x % 5 == 0 : 2120
pred = x => x % 6 == 0 : 1849
pred = x => x % 15 == 0 : 837
pred = x => x % 20 == 0 : 605
pred = x => x % 25 == 0 : 504
pred = x => x % 30 == 0 : 564
pred = x => x % 30 == 0 : 413

Your functions behaviour is therefore dependent not just on the size of your data, but on the form of your predicate.

For your own analysis, this is what I used for evaluating the predicate

   [TestCase(1,5000,10)]
   public void TestSkipBeforeIf(int start, int end, int mod)
   {
        var numberValue = new NumberValues(start,end);
        numberValue.SplitBeforeIf(i => i%mod == 0).ToList();
   }

I'm not clear what you meant by stateful predicate or IEnumerable, however in terms of the IEnumerable I have maintained a count as state. Similarly I could maintain a count for the pred, or add some bizarre checking behaviour.

Func<object, int, bool> predStateful = (y,x) =>
{
    if (x == y.Check(x))
    {
        return false;
    }
    return x%mod == 0;
};
Func<int, bool> pred = x => predStateful(MyCheckingObject,x);
numberValue.SplitBeforeIf(pred).ToList();

Thanks for the interesting question.

EDIT: Modified Chunk function using a predicate.
original

    public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(
                    this IEnumerable<TValue> values,
                    Func<TValue,bool> pred)
    {
        using (var enumerator = values.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                yield return GetChunk(enumerator, pred).ToList();
            }
        }
    }
    private static IEnumerable<T> GetChunk<T>(
                     IEnumerator<T> enumerator,
                     Func<T,bool> pred)
    {
        do
        {
            yield return enumerator.Current;
        } while (!pred(enumerator.Current) && enumerator.MoveNext());
    }


Use DOM and XPath to make some changes in HTML document I intend to make some changes in an HTML document, like remove, replace, append some nodes.

I have several arrays with same structure like the following example

$patterns[] = array(
    'xpath'   => '/html/body/div/p',
    'insert'  => $new_a,
    'task'    => 'replace'
);

...

$patterns[] = array(
    'xpath'   => '/html/body/header',
    'insert'  => $new_b,
    'task'    => 'remove'
);

and I use the following snippet

$dom = new DOMDocument();

if ((empty($html) !== true) && ($dom->loadHTML($html) === true))
{
    $dom->formatOutput = true;

    // Use DomXPath
    $xpath = new DomXPath($dom);

    // Process Dom changes
    foreach ($patterns as $key => $value)
    {
        $xpath_results = $xpath->query($patterns[$key]['xpath']);

        if ($xpath_results->length)
        {
            // Assign some values
            $xpath_results = $xpath_results->item(0);
            $task          = $patterns[$key]['task'];
            $replacement   = $patterns[$key]['insert'];

            if ($task != 'remove')
            {
                // Create the replacement
                $newNode = $dom->createDocumentFragment();
                $newNode->appendXML($replacement);
            }

            switch ($task)
            {
                case 'remove':
                    $xpath_results->parentNode->removeChild($xpath_results);
                    break;
                case 'replace':
                    $xpath_results->parentNode->replaceChild($newNode, $xpath_results);
                    break;
                case 'append':
                    $xpath_results->appendChild($newNode);
                    break;
                case 'prepend':
                    $xpath_results->parentNode->insertBefore($newNode, $xpath_results);
                    break;
            }
        }
    }

    // Save Dom
    $html = $dom->saveXML($dom->documentElement);
}

I would like your expert comments about if this is done the right way. The foreach to loop through the array elements, the switch to choose what will be done and if the use of createDocumentFragment is appropriate in this case.

Your code seems to globally do the right job, using a right way, and I can't see how you could really improve performance.
I only noticed a few bad points:

Unless I missed some subtleness, there is a typo in the case 'append': branch: it should be using $xpath_results->**parentNode**,like others.
You didn't take in account a possible error condition at $newNode->appendXML($replacement);: it may return FALSE, so you should cancel the process in that case.
The same applies to a possible wrong value in the task index of a pattern: it should be taken in account through the default: option of the switch().

In the other hand I would suggest some improvements at the coding level itself, essentially for readability.

You're using foreach ($patterns as $key => $value), but then always write $patterns[$key][...] so you force PHP to a few more work, while $value is never used.
I suggest to rather use foreach ($patterns as $value), then $value[...].
(or even more readable foreach ($patterns as $pattern), then $pattern[...])
Still for readability I would add a separate variable to clearly distinguish the successive "avatars" of $xpath_results, which is first a DOMNodeList then a DOMNode.
So you could change your DOMNode extraction to $node = $xpath_results->item(0);, and all following code becomes much more obvious.
Your // Assing some valuespart could be reduced to the $node assignation above: the two other variables are only used once so you could merely write $newNode->appendXML($pattern['insert']); and switch ($pattern['task']).

So here is my suggestion for the whole snippet after the remarks above:

if ($html) {
    $dom = new DOMDocument();
    if (!$dom->loadHTML($html)) {
        $error = 'Error while loading source HTML!';
    } else {
        $dom->formatOutput = true;
        // Use DomXPath
        $xpath = new DomXPath($dom);
        // Process Dom changes
        foreach ($patterns as $pattern) {
            $xpath_results = $xpath->query($pattern['xpath']);
            if ($xpath_results->length) {
                $node = $xpath_results->item(0);

                if ($task != 'remove') {
                    // Create the replacement
                    $newNode = $dom->createDocumentFragment();
                    if (!$newNode->appendXML($pattern['insert'])) {
                        $error = "Wrong insert pattern: $pattern['insert']!";
                        break;
                    }
                }
                if (!@$error) {
                    switch ($pattern['task']) {
                        case 'remove':
                            $node->parentNode->removeChild($node);
                            break;
                        case 'replace':
                            $node->parentNode->replaceChild($newNode, $node);
                            break;
                        case 'append':
                            $node->parentNode->appendChild($newNode);
                            break;
                        case 'prepend':
                            $node->parentNode->insertBefore($newNode, $node);
                            break;
                        default:
                            $error = "Wrong task pattern: $pattern['task']!";
                    }
                }
            }
        }
    }
    if (@$error) {
        // print or return $error...
    } else {
        // Save Dom
        $html = $dom->saveXML($dom->documentElement);
    }
}

For the error processing, I arbitrarily choosed one simple option among numerous different possiilities.  You can notice:

The @$error form: it is a simple and clear way to allow using variables set only in certain cases without having defined them previously.
Still for readability, I changed the initial tests into more simple (and sufficient) forms: if ($html) and if (!dom->loadHTML($html)).


The dumbest (futex-based) mutex After reading Ulrich Drepper's "Futexes are Tricky", I have written the following "dumbest mutex" in C++14 using the Linux futex primitives. This mutex is simpler than Drepper's; I believe it to be correct. The reason it gets to be so simple is the same as the reason I'm calling it the "dumbest mutex": it makes a system call on every unlock, even if the mutex is not being contended and nobody's waiting for the lock.

Therefore this is not a good mutex if you care about performance.

My question is: Leaving aside the performance issue, is this a correct mutex?  Or does it, like most hand-written concurrency code, have some subtle bug?
 Stylistic comments are also welcome.

#include <atomic>
#include <linux/futex.h>
#include <syscall.h>
#include <unistd.h>

inline int futex_wait(void *addr, int block_if_value_is) {
    return syscall(SYS_futex, addr, block_if_value_is, nullptr, nullptr, 0);
}

inline int futex_wake_one(void *addr) {
    return syscall(SYS_futex, addr, FUTEX_WAKE, 1, nullptr, nullptr, 0);
}

class mutex {
    std::atomic<int> m_state;
    static constexpr int UNLOCKED = 0;
    static constexpr int LOCKED = 1;
public:
    constexpr mutex() noexcept : m_state(UNLOCKED) {}

    bool try_lock() {
        return m_state.exchange(LOCKED) == UNLOCKED;
    }

    void lock() {
        while (m_state.exchange(LOCKED) != UNLOCKED) {
            futex_wait(&m_state, LOCKED);
        }
    }

    void unlock() {
        m_state = UNLOCKED;
        futex_wake_one(&m_state);
    }
};

is this a correct mutex?

It is not correct. There is a requirement for std::mutex::lock (http://en.cppreference.com/w/cpp/thread/mutex/lock):

  If another thread has already locked the mutex, a call to lock will
  block execution until the lock is acquired.

A simple test below that uses your mutex consumes 100% CPU that means it is busy-waiting. I think you did it by mistake.

On the contrary if I use std::mutex for the same test consumes 0% CPU in waiting on mt.lock().

mutex mt;
int main() {
    auto f = []() {
        mt.lock();
        mt.unlock();
    };
    mt.lock();
    std::thread t (f);
    std::this_thread::sleep_for(std::chrono::seconds(60));
    mt.unlock();
    t.join();
}

Below is a pidstat report for running a test with your mutex:

$ pidstat 1 -p $(pidof custom_mutex)
Linux 3.10.0-229.el7.x86_64 (sk71.net.billing.ru)       05/16/2017      _x86_64_        (2 CPU)

09:44:31 AM   UID       PID    %usr %system  %guest    %CPU   CPU  Command
09:44:32 AM  1000      9806   11.00   88.00    0.00   99.00     0  custom_mutex
09:44:33 AM  1000      9806   14.00   86.00    0.00  100.00     0  custom_mutex
09:44:34 AM  1000      9806   13.00   86.00    0.00   99.00     0  custom_mutex
09:44:35 AM  1000      9806   15.00   84.00    0.00   99.00     0  custom_mutex
09:44:36 AM  1000      9806   15.00   83.00    0.00   98.00     0  custom_mutex
09:44:37 AM  1000      9806   12.00   87.00    0.00   99.00     0  custom_mutex
09:44:38 AM  1000      9806   16.00   83.00    0.00   99.00     0  custom_mutex
09:44:39 AM  1000      9806   15.00   85.00    0.00  100.00     0  custom_mutex

And this is a report for a test that uses std::mutex:

$ pidstat 1 -p $(pidof std_mutex)
Linux 3.10.0-229.el7.x86_64 (sk71.net.billing.ru)       05/16/2017      _x86_64_        (2 CPU)

09:46:45 AM   UID       PID    %usr %system  %guest    %CPU   CPU  Command
09:46:46 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:47 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:48 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:49 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:50 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:51 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:52 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex
09:46:53 AM  1000      9965    0.00    0.00    0.00    0.00     0  std_mutex

update

I believe your mistake is in parameters for syscall. FUTEX_WAKE on my Linux is equal to 1. But take a look at:

inline int futex_wait(void *addr, int block_if_value_is) {
    return syscall(SYS_futex, addr, block_if_value_is, nullptr, nullptr, 0);
}

It passes block_if_value_is to SYS_futex as a parameter for int op. However the value of block_if_value_is in your program is equal to LOCKED and LOCKED is 1 (it means that it is equal to FUTEX_WAKE):

static constexpr int UNLOCKED = 0;
static constexpr int LOCKED = 1;

futex_wait(&m_state, LOCKED);

So you do not wait. You actually ask the kernel to wake up 0 (nullptr) processes. That is why you instead of waiting in kernel on your futex  returns:

return syscall(SYS_futex, addr, block_if_value_is, nullptr, nullptr, 0);


Function to generate all subsets of size n The function works this way:

Set is an instance variable, and is an array of type generic.
nElement is the size of all the subsets that you want. For example if you give it the value 3 the function will return all the subsets of Set of size 3
The idea is that we create an array named indices (indices = index in French) that will follow the index that we want for each subset.
We know that all of our subsets have a size of 3 elements so if indices[2] = 3 we have to increment indices[1] by 1 and set all of the following indices[i] to indices[i-1]+1.

Example

Set = {1,2,3,4} nElement = 3

for the first subset the indices = {0,1,2} -> {1,2,3}
for the second subset the indices = {0,1,3} -> {1,2,4} indices[2] = 3 so we indices[1]++ and indices[2] = indices[1]+1
for the third subset the indices = {0,2,3} -> {1,3,4} indices[2] = indices[2] = 3 so we indices[1]++ and indices[2] = indices[1]+1 but indices[1] now = 2 and the max value that indices[1] can have is 2 so indices[0]++ and indices[1] = indices[0]+1
for the fourth subset the indices = {1,2,3} -> {2,3,4}

Code

public List<T[]> GenerateCoupleOf(int nElement)
{
    if (nElement < 1)
        throw new Exception("nElement must be greater than 0");

    List<T[]> tr = new List<T[]>();
    T[] arr;

    int[] indices = new int[nElement];
    T[] temp_arr = new T[nElement];

    for (int i = 0; i < indices.Length; i++)
        indices[i] = i;

    while (indices[0] <= Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + 0)) + 1)
    {
        for (int i = 0; i < indices.Length; i++)
            temp_arr[i] = Set[indices[i]];

        arr = new T[nElement];

        for (int i = 0; i < indices.Length; i++)
            arr[i] = Set[indices[i]];

        tr.Add(arr);

        indices[indices.Length - 1]++;

        for (int i = indices.Length - 1; i > 0; i--)
        {
            if (indices[i] > Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + i)) + 1)
            {
                indices[i - 1]++;
                for (int j = i; j < indices.Length; j++)
                    indices[j] = indices[j - 1] + 1;
            }
        }
    }

    return tr;
}

Readability is a big factor in programming when it comes to maintaining the code by yourself or some other developer.
Readability can be improved by using standards which other developers expecting to see. Therefor some guidelines had been created like the .NET Naming Guidelines to name things like classes, properties, variables and parameters. Based on these guidlines variables should be named using camelCase casing instead of snake_case casing.

Omitting braces {} can lead to hidden and therfor hard to find bugs. i would like to encourage you to always use them.

That beeing said I will first focus on one part of your code...no, on two parts of your code but both are related.

while (indices[0] <= Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + 0)) + 1)

and

if (indices[i] > Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + i)) + 1)

but lets focus on the right part of the first line

Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + 0)) + 1

using simple math we can shorten this by removing the first () like so

Set.Length - 1 - (Set.Length - 1 - Set.Length + 1 + indices.Length - 0) + 1

and by removing the remaining () like so

Set.Length - 1 - Set.Length + 1 + Set.Length - 1 - indices.Length + 0 + 1

we get

Set.Length - indices.Length + 0

which is just

Set.Length - nElement + 0

which makes the while much more readable like so

int maxValueOfFirstIndex = Set.Length - nElement;

while (indices[0] <= maxValueOfFirstIndex)
{

}

which can be applied to the former if condition like so

if (indices[i] > maxValueOfFirstIndex  + i)
{

}

but nElement isn't as expressive as it could so numberOfItems could be a better name.

The T[] temp_arr isn't used in a useful way. You can safely remove it.
The check for nElement < 1 whouldn't throw an Exception but an ArgumentOutOfRangeException.
because variables should be declared as near as possible to their usage you should move the declaration of T[] arr inside the while.
by using Enumerable.Repeat().Select().ToArray() you can simplify the creation of indeces[] like so

int[] indices = Enumerable.Repeat(0, nElement).Select((s, d) => s + d).ToArray();

creating the T[] arr by a method would clean the main method as well
using the var type instead of concrete types can help if you later need to refactor to use a different type. And its shorter to write hence easier to read, at least if the type can be seen clearly from the right hand side of the assignment.

Applying the mentioned points will lead to

public List<T[]> GenerateCoupleOf(int numberOfItems)
{
    if (numberOfItems < 1)
    {
        throw new ArgumentOutOfRangeException("numberOfItems", "Value must be greater than 0");
    }

    var tr = new List<T[]>();

    var indices = Enumerable.Repeat(0, numberOfItems).Select((s, d) => s + d).ToArray();

    var maxValueOfFirstIndex = Set.Length - numberOfItems;

    while (indices[0] <= maxValueOfFirstIndex)
    {

        T[] arr = CreateArrayByIndices(indices, numberOfItems);

        tr.Add(arr);

        indices[indices.Length - 1]++;

        for (var i = indices.Length - 1; i > 0; i--)
        {
            if (indices[i] > maxValueOfFirstIndex + i)
            {
                indices[i - 1]++;
                for (var j = i; j < indices.Length; j++)
                {
                    indices[j] = indices[j - 1] + 1;
                }
            }
        }
    }

    return tr;
}
private T[] CreateArrayByIndices(int[] indices, int numberOfItems)
{

    var arr = new T[numberOfItems];

    for (int i = 0; i < indices.Length; i++)
    {
        arr[i] = Set[indices[i]];
    }
    return arr;
}


French animal generator I'm learning Python. I'm making a random animal generator, from 5 txt files. Each file is a list of words for respectively the specie of the animal, an adjective, an origin, and a bodypart with a color. Not all may appear in the description. I also wanted it to be arithmogrammatic. Here is my code, I know it can be improved, but how ?

import time
import random
z=5
nom=[line.strip() for line in open("ani_nom.txt").readlines()]
adj=[line.strip() for line in open("ani_adj.txt").readlines()]
ori=[line.strip() for line in open("ani_ori.txt").readlines()]
cor=[line.strip() for line in open("ani_cor.txt").readlines()]
cou=[line.strip() for line in open("ani_cou.txt").readlines()]

for w in range (120):
    z=random.randint(1,100)
    Inom=[x for x in nom if len (x) == z ]
    Iadj=[x for x in adj if len (x) == z ]
    Iori=[x for x in ori if len (x) == z ]
    Icor=[x for x in cor if len (x) == z-2 ]
    Icou=[x for x in cou if len (x) == z ]
    try:
            name = random.choice(Inom)
            adje = random.choice(Iadj)
            orig = random.choice(Iori)
            corp = random.choice(Icor)
            coul = random.choice(Icou)
    except IndexError :
        continue
    r = random.randint(1,5)
    print ""
    if r == 0:
        print name
    elif r == 1:
        print name
        print orig
    elif r == 2:
        print name
        print "a " + corp
        print coul
    elif r == 3:
        print name
        print adje
        print "a " + corp
        print coul
    elif r == 4:
        print name
        print orig
        print "a " + corp
        print coul
    elif r == 5:
        print name
        print adje
        print orig
        print "a " + corp
        print coul

The quite chaotic results look like this :

gecko
d'ete

merles
musque
d'Iran
a tete
Prasin

moucheron
d'Espagne

foulque
pelerin
d'hiver
a duvet
Abricot

crocodile
du Canada
a griffes
Malachite

sphecides
de bassan
a remiges
Framboise

okapi
a pic
Safre

gasteruption
constricteur
d'Angleterre
a couverture
Vert poireau

chardonneret
garde-boeufs
a couverture
Cafe au lait

vireos
a tete
Tomate

calligraphe
du Pakistan
a mandibule
Bleu marine

enrouleuses
de Finlande
a mandibule
Bleu canard

puceron
d'arbre
a joues
obscure

hemipteres
a criniere
Anthracite

perroquet
des tours
a remiges
Amethyste

roadrunner
porte-musc
a poitrine
Vert gazon

mamba
a pic
blanc

chaus
huppe
a pic
brune

serpent
de Bali
a duvet
Abricot

loriot
d'Inde

etoiledemer
flamboyante
de Brewster
a mandibule
Vert meleze

bronze
maçon
de mer
a aile
Soufre

hesperie
d'egypte

grande
d'Irak
a lore
Brique

belette
a duvet
Abricot

cochond'inde
d'Angleterre
a scapulaire
Vert prairie

moucheron
atricille
de Russie
a collier
Amethyste

salamandre
parenthese
a poitrine
Heliotrope

dendrocygne
de Birmanie
a mandibule
Bleu Persan

tephritides
a mandibule
Tourterelle

trichopteres
a scapulaire
Jaune canari

etc...

Feel free to comment, any help is appreciated !

Use classes
You should consider making animals a class, since you intend to make many of them that all have the same types of characteristics.  This is exactly what classes are good for.  I've taken the liberty of creating a characteristics dictionary for easy characteristic assignment using the data read from files
Don't repeat yourself
You do most things 5 times in a row (one for each characteristic).  You can avoid this in most situations.  For reading data, you can stuff each set of characteristics into one element of a dictionary.  For assigning characteristics, you can randomly select one item from each element of that dictionary.
Here's a crack at your code, revised:
import random

documents = [
    "ani_nom.txt",
    "ani_adj.txt",
    "ani_ori.txt",
    "ani_cor.txt",
    "ani_cou.txt"
    ]

data = {}

for document in documents:
    try:
        data.update({document.split(".")[0]: [line.strip() for line in open(document)]})
    finally:
        close(document)

class Animal(object):
    def __init__(self):
        self.characteristics = dict(
            ani_nom=None,
            ani_adj=None,
            ani_ori=None,
            ani_cor=None,
            ani_cou=None
        )

    def assign_all_characteristics(self):
        for characteristic in self.characteristics:
            self.characteristics[characteristic] = random.choice(data[characteristic])

    def print_random_characteristics(self):
        num_to_print = random.randint(1, 5)
        characteristics_to_print = list(self.characteristics.values())
        print "\n".join(characteristics_to_print[:num_to_print])

number_of_animals = 120
for _ in range(number_of_animals):
    animal = Animal()
    animal.assign_all_characteristics()
    animal.print_random_characteristics()


Using findInterval to assign vector elements to corresponding brackets The following function receives a vector of positive integers and list of brackets. The function returns a data frame with a logical vector for each bracket indicating whether a given element of a vector falls within that bracket.

Background

Received arguments

Vector x consisting of unique positive integers, usually corresponding to:

1:6000
c(1:100, 753:4000)

List of brackets, for instance:

list(c(1, 325),
     c(1, 651),
     c(1, 976),
     c(1, 1301),
     c(1, 1626),
     c(1, 1952))

Behaviour

For each of the brackets, the function creates a column int_brakcet_value consisting of TRUE / FALSE values indicating whether i element of vector falls within the designed bracket

Function

assign_interval <- function(x, brackets) {
    do.call("cbind",
            lapply(
                X = brackets,
                FUN = function(bracket) {
                    findInterval(x = x,
                                 vec = bracket,
                                 rightmost.closed = TRUE)
                }
            )) -> int_dta

    # Create friendly names
    int_nms <- lapply(
        X = brackets,
        FUN = function(brc) {
            paste0("int_", paste0(brc, collapse = "_"))
        }
    )

    # Set friendly names
    int_dta <- setNames(object = as.data.frame(int_dta),
                        nm = unlist(int_nms))

    # Replace findInterval outputs with T/F
    apply(X = int_dta, MARGIN = 2,
          FUN = function(col) {
              ifelse(col == 1, TRUE, FALSE)
    }) -> int_dta

    dta_res <- data.frame(int_dta)
    rownames(dta_res) <- x

    return(dta_res)
}

Tests

x <- 1:6505

res <- assign_interval(x = x, brackets = list(c(1, 325),
                                              c(1, 651),
                                              c(1, 976),
                                              c(1, 1301),
                                              c(1, 1626),
                                              c(1, 1952)))

Maybe it is overkill to use findInterval when your brackets only have two values (a min and a max). I would suggest this much shorter function based on two outer calls with >= and <=. As you probably know, outer is efficient in that it can take advantage of vectorized functions, so here only a single call to <= and >= will be made:

assign_interval2 <- function(x, brackets) {
  stopifnot(all(lengths(brackets) == 2L))
  lower_bounds <- sapply(brackets, head, 1)
  upper_bounds <- sapply(brackets, tail, 1)
  outer(x, lower_bounds, ">=") & outer(x, upper_bounds, "<=")
}

The results are the same and benchmarks suggest this is also a bit faster:

x <- 1:6505
brackets <- list(c(1,  325), c(1,  651), c(1,  976),
                 c(1, 1301), c(1, 1626), c(1, 1952))

res1 <- assign_interval(x = x, brackets = brackets)
res2 <- assign_interval2(x = x, brackets = brackets)
any(res1 != res2)
# [1] FALSE

library(microbenchmark)
microbenchmark(
  assign_interval(x = x, brackets = brackets),
  assign_interval2(x = x, brackets = brackets)
)

# Unit: milliseconds
#                                          expr      min        lq      mean
#   assign_interval(x = x, brackets = brackets) 7.851050 11.278404 15.300305
#  assign_interval2(x = x, brackets = brackets) 1.373723  1.628319  3.134719
#     median      uq       max neval
#  13.099052 14.4824 152.33409   100
#   2.192194  3.2971  13.70505   100

That being said, let's review your code and see if we can make small suggestions to improve your code while staying true to your implementation.

Instead of the do.call("cbind", lapply(...)), you could use sapply. The s in sapply is meant to do that exactly that: simplify the output by binding the pieces together. It comes at a very small (time) performance cost which should not affect you much here considering you do not have many brackets. I also notice that you are using the -> assignment operator which is not often used by R programmers hence not recommended.

dat <- sapply(brackets, findInterval, x = x, rightmost.closed = TRUE)

For the friendly names, I think the following would read better:

lower_bounds <- sapply(brackets, head, 1)
upper_bounds <- sapply(brackets, tail, 1)
friendly_names <- paste("int", lower_bounds, upper_bounds, sep = "_")

Next, a call to setNamesis a bit inefficient as it copies your data to a separate space in memory. Instead, you should use the colnames<- function so it only modifies the attribute of your existing object.

colnames(int_dta) <- friendly_names

Next, the use of apply is pretty inefficient as it loops on the columns. Instead you could just do:

int_dta <- int_dta == 1L

to convert to a matrix of TRUE/FALSE.

At the end, you are again making an unnecessary copy of your data. You can just change the rownames of your current object, then return it.


Factoring Integers the fun way Code dump:

function factor(n) {
    function count(a) {
        if (a.length == 0) {
            return [];
        } else {
            var x = a.pop();
            var l = count(a);
            if (l[x] == undefined) {
                l[x] = 0;
            }
            l[x]++;
            return l;
        }
    }
    function decomp(comp, fac) {
        if (comp == 1) {
            return [];
        }
        if (fac == 1) {
            return [ comp ];
        }
        if (comp % fac == 0) {
            return decomp(fac, fac - 1).concat(decomp(comp / fac, fac));
        } else {
            return decomp(comp, fac - 1);
        }
    }
    return count(decomp(n, n)).map(function(a, b) {
        return [ b, a ];
    }).filter(function(a, b) {
        return a[1];
    }).map(function(a, b) {
        return "" + a[0] + "^" + a[1];
    }).reduce(function(a, b) {
        return a + " * " + b;
    }).replace("^1", "");
}

It's mainly because I've been into functional programming lately that I tried a loopless, stateless, functional algorithm; I know that this example is absolutely facetious and that no one would do this in real life. That said, are there ways I can make this:

More efficient (e.g. less data),
More concise (which keeping the cool functional aspect), or
More functional (in a good way) in paradigm?

Keystrokes are (almost) free. It's not like decomp looks any better than decompose. (Moving forward, I'm going to assume you made the rename.)
Your count() function is cute. For extra fun, you could replace it with Array.reduce() (which you may know as foldl):

decompose(n, n).reduce(function(accumulator, value) {
    if (typeof accumulator[value] === "undefined") {
        accumulator[value] = 0;
    }
    accumulator[value]++;
    return accumulator;
}, []).map ...

(The logic can be reduced to prev[cur]++ || (prev[cur] = 1) or prev[cur] = prev[cur] + 1 || 1 if desired.)
It's worth mentioning that comparisons against undefined are typically done with ===.
You've got a redundant else in decompose().
You can use switch(true) syntactic sugar to make decompose() prettier:

function decompose(composite, factor) {
    switch(true) {
        case composite == 1:
            return [];
        case factor == 1:
            return [composite];
        case composite % factor == 0:
            return decompose(factor, factor - 1).concat(decompose(composite / factor, factor));
        default:
            return decompose(composite, factor - 1);
    }
}

or alternatively, chained conditional operators (commonly called ternary operators):

function decompose(composite, factor) {
    return composite == 1 ? [] :
           factor == 1 ? [composite] :
           composite % factor != 0 ? decompose(composite, factor - 1) :
           decompose(factor, factor - 1).concat(decompose(composite / factor, factor));
    }
}

decompose(n, n) is ugly. Maybe you rewrite the contract of decompose to int (maybe int) -> array?
You're replacing only the first instance of ^1. You'll want to do .replace(/\^1/g, "") instead.
factor(1) doesn't return 1 as expected. You can fix this by switching your first two ifs.
factor(0) recurs infinitely.
You're using a lot of functions at the end there.

Here's my rendition. It's a little bit less elegant with the return... oh well. I'm using a utility function when to avoid potentially ugly ternary nesting. The double reduce bugs me but I can't think of a better way right now.

function factor(n) {
    function when(condition, string) {
        return condition ? string : "";
    }

    function decompose(composite, factor) {
        return factor === undefined ? decompose(composite, composite) :
               factor <= 1 ? [composite] :
               composite <= 1 ? [] :
               composite % factor != 0 ? decompose(composite, factor - 1) :
               decompose(factor, factor - 1).concat(decompose(composite / factor, factor));
    }

    return decompose(n).reduce(function(accumulator, value) {
            accumulator[value] = accumulator[value] + 1 || 1;
            return accumulator;
        }, []).reduce(function(accumulator, value, index) {
            return accumulator + when(value, " * " + index + when(value > 1, "^ " + value));
        }, "").substr(3);
}


Script to enter text in a box Here's a little script that enters text into a document when activated.

tell application "TextEdit"
  activate
end tell
delay 0.2
tell application "System Events"
  keystroke "Hello World!"
  keystroke return
end tell

I stuck the delay in there because otherwise the first few keystrokes tend to trigger before the window is done activating, so I end up with "lo World!" in the document and "Hel" in whatever other window had focus when the script was activated. Is that the proper use of delay, or is there a better way to circumvent that problem?

Rather than using System Events to generate keystrokes, consider using TextEdit itself to insert text.

tell application "TextEdit"
    activate
    tell first document to set its text to its text & "Hello World!\n"
end tell

There is a difference, though: this version always appends "Hello World!" to the end of the document, rather than wherever the cursor happens to be.  (Unfortunately, TextEdit's AppleScript dictionary mentions nothing about cursors.)

A side benefit of this approach is that you don't have to grant permission to use Assistive Access to your script.


Ruby-ize for loop - counting all the n-digit numbers that contain the digit 5 anywhere I wrote this a while back when my fiance was taking a Number Theory class. I wrote about it here and it recently came back to my attention. Anytime I write a for loop in Ruby I feel kind of dirty. I would like to "Ruby-ize" this routine if there is a more Ruby way to do it. Also, is this the most efficient algorithm for this?

Original Problem:

  How many numbers less than 10000 that contain the digit 5 anywhere?

(Even thought the original problem was for < 10000, I've run this much farther out)

The algorithm:

  \$f(x) = 9y + \dfrac{x}{10}\$

  Where \$y\$ is the previous result and \$x\$ is the power of 10 we're checking against.

  i.e. \$y = 1\$ and \$x = 100\$, or \$y = 19\$ and \$x = 1000\$

or, for the more mathematically inclined

  \$f(10^n)=9f(10^{n-1})+10^{n-1}\$

The code:

def numbersContaining5(pwr)
# Prints on screen the count of numbers containing a "5"
#    for each power of ten up and including the one passed in.
# pwr = the power of ten you wish to calculate to

    prev = 0
    for i in 1..pwr
        prev = (prev*9) + (10**i)/10
        puts prev
    end
end

#call function
numbersContaining5(4) # 10^4 = 10000

I would use recurence in place of the loop - it is easier to understand the logic behind it then:

def number_containing_5(pwr)
  return 0 if pwr == 0
  number_containing_5(pwr-1) * 9 + 10**(pwr-1)
end


Reporting the highest satisfied poker hand in F# I'm learning F# by doing various small projects. One of them is a problem where the program reads Poker hands and rates them. It's Texas Hold'Em, so for each player it tries every five card selection from seven cards.

When it's time for scoring I have made a set of functions that each evaluate a hand and produces an Score option of whether that hand matches or not:

type Score =
{ Points: int
  Desc: string }

val tryStraightFlush: PokerHand -> Score option
val tryFourOfAKind: PokerHand -> Score option
// more functions ..
val getHighCard: PokerHand -> Score option

type PokerHand =
  class
    new : cards:Card list -> PokerHand
    member Cards : Card list
    member HighCard : Card option
  end

But now I have a problem, because I need to use the options that these functions produce, so I cannot do a match like this:

//Non-working code.
//Something roughly similar to this would be nice.
//But I need to use the values from the "try"-functions
//and they get thrown away here:

let scoreCards (hand: PokerHand) =
match hand with
| r when (tryStraightFlush hand) <> None -> //prod. Score
| r when (tryFourOfAKind hand) <> None -> //prod. Score
// more code

Instead my code ends up looking like this, and I have to say I don't like this deep nesting.. How can I have a small function for testing each type of configuration, while avoiding a deeply nested if-expressions?

let scoreCards (hand: PokerHand) =
  // Too much nesting!
  let r = tryStraightFlush hand
  if r <> None then
    r.Value
  else
    let r = tryFourOfAKind hand
    if r <> None then
        r.Value
    else
        let r = tryFullHouse hand
        if r <> None then
            r.Value
        else
            let r = tryFlush hand
            if r <> None then
                r.Value
            else
                // nesting continues..

The solution here is to use an active pattern, which enables you to create a custom matching function.

You can even reuse your existing functions.

It would look like

let |StraightFlush|_| hand = tryStraightFlush hand

then you can use it like this

match hand with
|Straightflush(score) -> ...
| ....


Code First approach, feeding the table I have a database (PostgreSQL) from which I want to migrate some data to a MS SQL Server database. I decided to use a code first approach. The question is related to the proper way of feeding my new tables.

Model.cs:

public class Info
{
    [Key]
    public int InfoID { get; set; }
    public int NameID { get; set; }
    public string Name { get; set; }
}

DatabaseInitializer:

  private void SeedInfos(SomeContext context)
    {
        var Infos = new List<Info>();

using (var com = new NpgsqlCommand(PostgresSQLs.GetAllInfos, EstablishedConnection()))
        {
            using (var r = com.ExecuteReader())
            {
                while (r.Read())
                {
                    Infos.Add(new Info { InfoID= Convert.ToInt32(r["infoID"]), NameID = Convert.ToInt32(r["NameId"]), Name = r["Name"].ToString()});
                };
            }
        }
        foreach (var Usr in Users)
            context.Infos.Add(Usr);
    }

One of my concerns is related to the static class PostgreSQL where I store queries which are retrieving the data I need from PostgreSQL. Is it a proper approach? The more complicated query, the more complex code, so it may be hard to maintain later, isn't it? What approach would you use?

Besides, such data feeding may cost a lot of memory in case the table is big. Is there a possibility to avoid memory leaks?

Variables should be named using camelCase casing, see the NET naming guideline so Infos -> infos and Usr -> usr but as one shouldn't use abbreviation for any names you should change it to users which is much easier to read. This same rule applies to r vs reader and com vs command.

Using braces {} always although they might be optional is the way to make your code less error prone.

foreach (var user in Users)
{
    context.Infos.Add(user);
}

I don't know where these Users are coming from and what context.Infos type is, but if it is by any chance a List<T> you could use the AddRange() method to add them all at once like context.Infos.AddRange(Users);.

What sense does it have to fill a List<Info> which is not used afterwards ?

Having a static class containing the queries can be ok, but you should at least add some possibility to add custom queries as well.


Improve my little syntactic hack Current best practice for using a lock_guard looks like this:

// introduce scope to take the lock
{
    lock_guard lock(sync);    // sync is an accessible mutex object
    do_protected_stuff();     // may throw, but the mutex is released regardless
}
// no exception, mutex is released in normal flow

I don't like the scope being introduce without a statement.  I think it detracts from readability, and I think it's ugly.  It occurred to me that what I wanted was the equivalent of modern Python's with statement:

with Lock() as lock:          # corresponds to lock+mutex in C++
    do_protected_stuff()

I thought about it for a while and designed a syntax hack that's gotten me partway there:

#include <iostream>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using std::cout;
using std::endl;

//=============================================
// This is the "novel" part
// See main() for usage
//=============================================
// a utility class
class with_lock_
{
public:
    with_lock_(boost::mutex &mtx_) : lock(mtx_), new_lock(true) {}
    operator bool() { bool ret = new_lock; new_lock = false; return ret; }
private:
    boost::lock_guard<boost::mutex> lock;
    bool new_lock;
};
// a macro to hide the gory details
#define with_lock_guard(SYNC)   for (with_lock_ lk_(SYNC); lk_; )

//==============================================

// some global stuff for multi-thread action
// a mutex
boost::mutex sync;

// a value protected by the mutex
float zz = 0.0f;

// a thread function that will change the value and crow about it
void get_it_yourself()
{
    boost::lock_guard<boost::mutex> lock(sync);
    zz = 99999.99999f;
    cout << endl << "  ---  MINE!!" << endl;
}

//==============================================

int main()
{
    boost::thread runit;

    //=============================================
    // This is the intended use...
    // a little syntactic hack, inspired by Python
    //=============================================
    with_lock_guard (sync)
    {
        runit = boost::thread(get_it_yourself);
        cout << "Starting... ";
        boost::this_thread::sleep(boost::posix_time::millisec(500));
        cout << "OK!  Z = " << zz << endl;
    }

    // wait for that thread to complete
    runit.join();

    return 0;
}

Accept, for this discussion, that having a keyword to introduce the scope is preferable to introducing scope with just a brace.  This hack lets you pretend you have a real with-like statement: you can follow it with a single or compound statement.

I do have a concern regarding the scope of the with_lock_ object. As I read things, at some level (persisting even into C++11?) the scope of a variable introduced within a for statement is the block enclosing the for. In practice, it's working OK for me with MSVS 2008; there is a compiler option regarding this, which defaults to the behavior I need in this situation.

Even without backing off from the basic idea, I see room for improvement.  For one thing, a true with statement in C++ would be able to accept other types of RAII-based objects, as Python does.  But so far in practice, I've only really the undesirable syntax with lock_guard.

What I'm looking for is a way to generalize this feature such that, at least, any mutex type, from any namespace, can be used.  Better, if any lock type can be used.  A cleaner implementation than abusing for or the operator bool() would be of interest.

Also: I'm not concerned if it breaks older compilers, but it would good to know if this works or doesn't in platforms/compilers other than Windows/MSVS2008+. Comments decrying the whole abomination are fine.

Comments on Design
I like the idea in general but usually when I introduce a lock in a scope, the scope is usually the whole method so it does not look that ugly:
void MyClass::myMethod()
{
    lock_guard lock(sync);    // sync is an accessible mutex object
    do_protected_stuff();     // may throw, but the mutex is released regardless
}

But lets assume that you have situations that make your style worth while in using:
Now my problem is that you have situations where things are not as they seem:
with_lock_guard (sync)
    runit = boost::thread(get_it_yourself);
    cout << "Starting... ";
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    cout << "OK!  Z = " << zz << endl;

Only the first statement is inside the lock. Yet I get no compiler error (yes I know silly error but the idea is that you should design your class so that it is really hard to abuse even accidentally):
I would change the design slightly so that it used a lambda:
with_lock_guard(sync, []()
{
    runit = boost::thread(get_it_yourself);
    cout << "Starting... ";
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    cout << "OK!  Z = " << zz << endl;
});

This way it will be harder to abuse accidentally.
Comments on code:
If you are going to have operator bool() conversion method then at least make it explicit so it can not accidentally be abused. But since you are calling this from your own macro I would have a method that you explicitly call. This makes the code easier to understand.
https://stackoverflow.com/questions/6242768/is-the-safe-bool-idiom-obsolete-in-c11
// Prefer to use explicit on bool to prevent accidental usage:
explict operator bool() { bool ret = new_lock; new_lock = false; return ret; }

But I would do this:
#define with_lock_guard(SYNC)   for (with_lock_ lk_(SYNC); lk_.MakeSureWeRunOnceOnly(); )


Priority scheduling algorithm using std::vector I'm learning priority scheduling algorithm and trying to implement it using std::vector. But the current performance of my code that's partially implemented is not that good since I'm performing sort operation every time I add a new process to std::vector list. Can somebody suggest ways I can improve my current partially implemented algorithm. This is my code:
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>

void print_list(const std::vector<std::pair<int, int>>& pair_list) {
    for (const auto& pa : pair_list)
        std::cout << "process_ID: " << pa.first << ", " << "priority: " << pa.second << "\n";
    std::cout << std::endl;
}

void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list) {
    pair_list.emplace_back(pro_ID, pro_pri);

    std::sort(pair_list.begin(), pair_list.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) {
        return a.second < b.second;
    });
}

bool check_pro_is_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list) {
    for (const auto& pa : pair_list) {
        if (pa.first == pro_ID)
            return true;
    }

    return false;
}

bool is_higher_pri_pro_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list) {
    if (pair_list.front().first == pro_ID)
        return false;

    return true;
}

int main() {
    std::vector<int> process_ID_list { 1345, 45, 5646, 52525, 55757, 23424, 68696, 55878, 667, 252 };
    std::vector<int> process_pri_list { 41, 334, 747, 41, 47, 7, 75, 544, 42, 6 };

    std::vector<std::pair<int, int>> pair_list;
    for (int i = 0; i < process_ID_list.size(); ++i) {
        int new_pro_ID = process_ID_list.at(i);
        int new_pro_pri = process_pri_list.at(i);

        if (!check_pro_is_present(new_pro_ID, pair_list))
            add_pro(new_pro_ID, new_pro_pri, pair_list);
        else
            std::cout << "process is already in list" << std::endl;

        print_list(pair_list);
    }

    int query_pro_ID = 1345;
    std::cout << std::boolalpha << is_higher_pri_pro_present(query_pro_ID, pair_list) << std::endl;

    return (EXIT_SUCCESS);
}

While comments have suggested more suitable types than std::vector, I'm going to assume that the use of this underlying type is a given, and suggest straightforward improvements without changing that.
The main performance concern is here:

void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list) {
    pair_list.emplace_back(pro_ID, pro_pri);

    std::sort(pair_list.begin(), pair_list.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) {
        return a.second < b.second;
    });
}

It's wasteful to sort the vector every time we add an element, when we know it was sorted before we called this function.  Instead, we need to insert the new element in the correct position.
void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list)
{
    auto position = std::upper_bound(pair_list.begin(), pair_list.end(), pro_pri,
                                     [](auto pri, auto const& ele) { return pri < ele.second; });
    pair_list.emplace(position, pro_ID, pro_pri);
}

We use the type std::vector<std::pair<int, int>> a lot.  It's worth giving it a name:
using priority_queue = std::vector<std::pair<int, int>>;

That makes changing the code easier, e.g. if we decide that process ids actually need to be unsigned long or something.
However, I observe that every function takes one of these as an argument.  That suggests that we want a class with this vector as member, then convert those free functions to be members of that class.

Thank you for including the test program - that's always helpful in a review.  There's a couple of small points:

for (int i = 0; i < process_ID_list.size(); ++i) {

We're mixing signed and unsigned types in this comparison (int and std::size_t).  Obviously we should change int i to std::size_t i - and enable more compiler warnings.

       std::cout << "process is already in list" << std::endl;

Prefer to use std::cerr for error messages.

The pattern if (condition) return true; else return false; can simply be replaced with return condition.  So:
bool is_higher_pri_pro_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list)
{
    return pair_list.front().first != pro_ID;
}

The loop in check_pro_is_present can be replaced with std::any_of:
bool check_pro_is_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list)
{
    return std::any_of(pair_list.begin(), pair_list.end(),
                       [pro_ID](auto const& e){ return e.first == pro_ID; });
}

Modified code
This is just a beginning - we'll probably want an initialiser-list constructor, and replace print() with operator<<(), but it's a start.
#include <algorithm>
#include <iostream>
#include <utility>
#include <utility>
#include <vector>

template<typename T, typename Priority = int>
class priority_queue
{
    std::vector<std::pair<T, Priority>> values = {};

public:
    void print(std::ostream &os) const {
        for (const auto& pa : values) {
            os << "process_ID: " << pa.first << ", "
               << "priority: " << pa.second << '\n';
        }
        std::cout << '\n';
    }

    void add(T t, Priority pri) {
        auto const position
            = std::upper_bound(values.begin(), values.end(),
                               pri,
                               [](auto const& pri, auto const& ele) { return pri < ele.second; });
        values.emplace(position, std::move(t), std::move(pri));
    }

    bool contains(int pro_ID) const
    {
        return std::any_of(values.begin(), values.end(),
                           [pro_ID](auto const& e){ return e.first == pro_ID; });
    }

    bool has_higher(int pro_ID) const
    {
        return values.front().first != pro_ID;
    }
};

int main()
{
    const std::pair<int,int> processes[]
        = { { 1345, 41 }, { 45, 334 }, { 5646, 747 },
            { 52525, 41 }, { 55757, 47 },
            { 23424, 7 }, { 68696, 75 }, { 55878, 544 },
            { 667, 42 }, { 252, 6 } };

    priority_queue<int, int> queue;
    for (auto const& p: processes) {
        if (queue.contains(p.first)) {
            std::cerr << p.first << " is already in list\n";
        } else {
            queue.add(p.first, p.second);
        }
        queue.print(std::cout);
    }

    int query_pro_ID = 1345;
    std::cout << std::boolalpha << queue.has_higher(query_pro_ID) << '\n';
}


Is this "unsafe" declaration unnecessary? I have a class that I inherited from someone else. It is doing a P/Invoke on CopyFileEx to copy a file (we are using UNC shares if that matters). The code is marked unsafe but I thought you only needed to use that when dealing with raw pointers, if you are using IntPtr only your code does not need to be marked unsafe.

public void Copy()
{
    bool result;

    unsafe
    {
        if (System.Environment.OSVersion.Version.Major > 5)
        {
            //only newer versions of windows support the no buffer flag
            //(this is set because copying large files on a computer with limited ram will pretty much kill the computer)
            result = CopyFileEx(SourceFile, TargetFile, new CopyProgressRoutine(CopyProgressEvent), IntPtr.Zero, ref Cancelflag, CopyFileFlags.COPY_FILE_NO_BUFFERING);
        }
        else
        {
            result = CopyFileEx(SourceFile, TargetFile, new CopyProgressRoutine(CopyProgressEvent), IntPtr.Zero, ref Cancelflag, 0);
        }
    }

    //file copy failed so get the DLL error and throw an exception
    if (result == false)
    {
        Win32Exception exc = new Win32Exception(Marshal.GetLastWin32Error());
        throw exc;
    }
}

//xcopy file progress event handler
private CopyProgressResult CopyProgressEvent(Int64 TotalFileSize, Int64 TotalBytesTransferred, Int64 StreamSize, Int64 StreamBytesTransferred, uint dwStreamNumber,
                                                   XCopy.CopyProgressCallbackReason dwCallbackReason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)
{
    //chunk of a file finished copying
    if (dwCallbackReason == XCopy.CopyProgressCallbackReason.CALLBACK_CHUNK_FINISHED)
    {
        int currentFilePercent = Convert.ToInt32(Math.Round(TotalBytesTransferred * 100.0 / TotalFileSize));

        //only send a new message when something changes (prevents flooding of messages)
        if (currentFilePercent != LastFilePercent)
        {
            LastFilePercent = currentFilePercent;

            //Report back the progress
            ProgressCallback.Report(currentFilePercent);
        }
    }

    //stop the copy?
    if (Cancelflag == 1)
        return XCopy.CopyProgressResult.PROGRESS_CANCEL;
    else
        return XCopy.CopyProgressResult.PROGRESS_CONTINUE;

}

//win32 API call
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName,
    CopyProgressRoutine lpProgressRoutine, IntPtr lpData, ref Int32 pbCancel,
    CopyFileFlags dwCopyFlags);

//xcopy event handler
public delegate CopyProgressResult CopyProgressRoutine(
                    Int64 TotalFileSize,
                    Int64 TotalBytesTransferred,
                    Int64 StreamSize,
                    Int64 StreamBytesTransferred,
                    uint dwStreamNumber,
                    CopyProgressCallbackReason dwCallbackReason,
                    IntPtr hSourceFile,
                    IntPtr hDestinationFile,
                    IntPtr lpData);

I think the unsafe is not needed but the person who wrote this originally claims he was getting intermittent errors during run-time when in production environments when it was not marked unsafe.

Was he right about needing unsafe or did he have a problem elsewhere that was just fixed at the same time that made it look like unsafe fixed the issue?

unsafe is purely a compile-time check. If it were needed the code wouldn’t compile. The runtime errors are caused by something else.

Furthermore, unsafe is needed if and only if you are using unmanaged pointers (e.g. inside a fixed block).