texts: Implementing the IQueryable counterpart method of the IEnumerable method?

texts:
I have created this method to simulate SQL's IN operator:

public static IEnumerable<TSource> In<TSource, TMember>(this IEnumerable<TSource> source,
            Func<TSource, TMember> identifier, params TMember[] values) =>
         source.Where(m => values.Contains(identifier(m)));

to use it like:

var selectedAccounts = allAccounts.In(x => x.Id, 1, 2, 100); //select accounts whose Id's are 1, 2, 100

I think there's no problem with it since it's working on the in-memory data.

and this is the IQueryable version of it:

    public static IQueryable<TSource> In<TSource, TMember>(this IQueryable<TSource> source,
   Expression<Func<TSource, TMember>> identifier, params TMember[] values)
        {
            var parameter = Expression.Parameter(typeof(TSource), "m");
            var inExpression = GetExpression(parameter, identifier, values);
            var theExpression = Expression.Lambda<Func<TSource, bool>>(inExpression, parameter);
            return source.Where(theExpression);
        }

  static Expression GetExpression<TSource, TMember>(ParameterExpression parameter, Expression<Func<TSource, TMember>> identifier, IEnumerable<TMember> values)
        {
            var memberName = (identifier.Body as MemberExpression).Member.Name;
            var member = Expression.Property(parameter, memberName);
            var valuesConstant = Expression.Constant(values.ToList());
            MethodInfo method = typeof(List<TMember>).GetMethod("Contains");
            Expression call = Expression.Call(valuesConstant, method, member);
            return call;
        }

I'd like to know if this is how IQueryable methods are implemented?
did I use the Expressions API right? and is there a better suggestion than using Reflection, or it's OK?


texts:
I'm calculating how many possibilities there are to fit \$n\$ identical bottles inside \$k\$ crates of various capacities.

n = Number of bottles
k = Number of crates
K = List of the number of bottles each crate can fit

Each crate may be filled with any number of bottles up to \$K_i\$, including being empty.

This is an instance of the Donut Shop Problem.

Example 1

Let's say we have:

7 Bottles (\$n = 7\$)
2 Crates (\$k = 2\$)
Crate 1 fits 3 bottles, crate 2 fits 5 bottles (\$K_1 = 3, K_2 = 5\$)

There are 2 possibilities to fit the bottles inside the crates.

Example 2

7 Bottles (\$n = 7\$)
3 Crates (\$k = 3\$)
Crate 1 fits 2 bottles, crate 2 fits 3 bottles, crate 3 fits 4 bottles (\$K_1 = 2, K_2 = 3, K_3 = 4\$)

6 possibilities

I have a recursive solution that works fine for small integers:

def T(n, k, K):
    if k==0: return n==0
    return sum(T(n-i, k-1, K) for i in xrange(0, K[k-1]+1))

But when I try it with \$n = 30, k= 20, K_i = i\$, it takes FOREVER, so I'm asking you: how could I improve the above code/function?


texts: ASP.NET MVC 3 ModelBinder with string sanitizing

texts:
I need to allow incoming HTML in string parameters in my projects action methods, so we have disabled Input Validation.  I have a good HTML sanitizer; the review I am interested in is the way I bound it into my project.

I have the following Model Binder:

    public class EIMBaseModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var boundValue = base.BindModel(controllerContext, bindingContext);
            return bindingContext.ModelType == typeof(string) ? HtmlCleaner.SanitizeHtml((string)boundValue) : boundValue;
        }

        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
       {
            if (propertyDescriptor.PropertyType == typeof(string))
            {
              var stringVal = value as string;
              value = stringVal.IsNullOrEmpty() ? null : HtmlCleaner.SanitizeHtml(stringVal);
            }

            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
       }
    }

I set it as my DefaultBinder in my set up and require that all custom model binders inherit from it. I know I can't completely defend against developers not following this rule, but we are a small team so I think we can police that well enough.

I have some basic unit testing pushing both string primitive values and strings as property values through the binder and those work as expected.  I will be asking the security team to do some penetration tests.

Can anyone see either a better way to have hooked into the incoming data or a base I have missed?


texts:
In this example, I am only looking for the first duplicate - curious if this logic in for loop (take from the top, evaluate, put on the bottom) pattern has a standard form

function findOneDupe(input){
  var b = input.split(/\s|\n/).map(Number);
  b.shift();
  for (var i=0;i<b.length;i++){
    var e = b.shift();
    if (b.indexOf(e) == -1) return e;
    b[b.length] = e;
  }
  return -1;
}


texts:
I have a question about this coding challenge for "Flatten a Dictionary":

  Given a dictionary dict, write a function flattenDictionary that
  returns a flattened version of it .

  If you’re using a compiled language such Java, C++, C#, Swift and Go,
  you may want to use a Map/Dictionary/Hash Table that maps strings
  (keys) to a generic type (e.g. Object in Java, AnyObject in Swift
  etc.) to allow nested dictionaries.

  Example:

  Input:

dict = {
    "Key1" : "1",
    "Key2" : {
        "a" : "2",
        "b" : "3",
        "c" : {
            "d" : "3",
            "e" : "1"
        }
    }
}

  Output:

{
    "Key1" : "1",
    "Key2.a" : "2",
    "Key2.b" : "3",
    "Key2.c.d" : "3",
    "Key2.c.e" : "1"
}

  Important: when you concatenate keys, make sure to add the dot character between them. For instance concatenating Key2, c and d the result key would be Key2.c.d.

def flatten_dictionary(dictionary):

  def items():
  # loop through each item inside the dictionary k, v
      #Appending
      # check if the sub-key and sub-value are
      # inside the flatten_dict(value)
      # join on subkey array
      # add to result
      # clear out prev_keys
    for key, value in dictionary.items():
      if isinstance(value, dict):
        for subkey, subvalue in flatten_dictionary(value).items():
          if key == "":
            yield subkey, subvalue
          yield key + "." + subkey, subvalue

      else:

        yield key, value

  return dict(items())

# test cases 1

dictionary2 = {
            "Key1" : "1",
            "Key2" : {
                "a" : "2",
                "b" : "3",
                "c" : {
                    "d" : "3",
                    "e" : "1"
                }
            }
        }

# output: {
#             "Key1" : "1",
#             "Key2.a" : "2",
#             "Key2.b" : "3",
#             "Key2.c.d" : "3",
#             "Key2.c.e" : "1"
#         }

print(flatten_dictionary(dictionary2))


texts:
This code is working on the user selection when pressed a button the table will be filtered by the number of criteria the user selected:

    Sub advancedMultipleCriteriaFilter()

 Dim cellRng As Range, tableObject As Range, subSelection As Range
 Dim filterCriteria() As String, filterFields() As Integer
 Dim i As Integer

Application.ScreenUpdating = False
'Call removeSpace

If Selection.Rows.Count > 1 Then
 MsgBox "Cannot apply filter to multiple rows within the same column. Please make another selection and try again.", vbInformation, "Selection Error!"
 Exit Sub
 End If

i = 1
 ReDim filterCriteria(1 To Selection.Cells.Count) As String
 ReDim filterFields(1 To Selection.Cells.Count) As Integer

Set tableObject = Selection.CurrentRegion
 For Each subSelection In Selection.Areas
 For Each cellRng In subSelection
 filterCriteria(i) = cellRng.Text
 filterFields(i) = cellRng.Column - tableObject.Cells(1, 1).Column + 1
 i = i + 1
 Next cellRng
 Next subSelection

With tableObject
 For i = 1 To UBound(filterCriteria)
 .AutoFilter field:=filterFields(i), Criteria1:=filterCriteria(i)
 Next i
 End With

Call GetLastRow

Set tableObject = Nothing
Application.ScreenUpdating = True

End Sub

Sub resetFilters()

Dim sht As Worksheet
Dim LastRow As Range

Application.ScreenUpdating = False

   On Error Resume Next
        If ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData
  End If

'Range("A3:T3").ClearContents
Application.ScreenUpdating = True
Call GetLastRow

End Sub

Private Sub GetLastRow()

 'Step 1: Declare Your Variables.
  Dim LastRow As Long

 'Step 2: Capture the last used row number.
  LastRow = Cells(Rows.Count, 8).End(xlUp).Row

 'Step 3: Select the next row down
  Cells(LastRow, 8).Offset(1, 0).Select

 End Sub


texts:
I wrote the following custom validation annotation for my project to confirm that at least one checkbox of a group of checkboxes is checked:

public class ValidateAtLeastOneChecked : ValidationAttribute {
    public string[] CheckBoxFields {get; set;}
    public ValidateAtLeastOneChecked(string[] checkBoxFields) {
        CheckBoxFields = checkBoxFields;
    }

    protected override ValidationResult IsValid(Object value, ValidationContext context) {
        Object instance = context.ObjectInstance;
        Type type = instance.GetType();

        foreach(string s in CheckBoxFields) {
            Object propertyValue = type.GetProperty(s).GetValue(instance, null);
            if (bool.Parse(propertyValue.ToString())) {
                return ValidationResult.Success;
            }
        }
        return new ValidationResult(base.ErrorMessageString);
    }
}

I then use it like this:

[ValidateAtLeastOneChecked(new string[] { "Checkbox1", "Checkbox2", "Checkbox3", "Checkbox4" }, ErrorMessageResourceType=typeof(ErrorMessageResources),ErrorMessageResourceName="SelectAtLeastOneTopic")]
public bool Checkbox1{ get; set; }
public bool Checkbox2{ get; set; }
public bool Checkbox3{ get; set; }
public bool Checkbox4{ get; set; }

The aim was to get the check boxes all validating and keep the validations and their localization contained in the ViewModel. This is working, my only concern is that I expected to find an easy google-paste piece of code for this and did not... Am I missing something easier?

As a secondary question I am attaching this to only one checkbox field, which I think is fine; but is there any unintended consequences of that (other than that any css error highlighting would only apply to the one checkbox)?


texts: Read output from a subprocess executed by Python

texts:
I've written these 2 methods and I'm wondering if the 2nd method, which uses yield is more efficient or if I'm using yield wrong. Can someone refactor the 2nd method to make it more efficient for reading system os calls with large output?

def exec_cmd(command):
    proc = subprocess.Popen(command,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)

    stdout, stderr = proc.communicate()
    return_code = proc.returncode

    if stderr:
        raise Error(stdout, stderr)

    if return_code:
        raise Error(stdout, return_code)

    return stdout, return_code

def exec_cmd_output_line_by_line(command):
    proc = subprocess.Popen(command,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)

    return_code = proc.returncode

    if return_code:
        raise Error(proc.stdout, return_code)

    for line in proc.stdout.readlines():
        yield line.strip()


texts:
I have a csv file with sales transactions. Each transaction includes person identifiers (which are sometimes/often missing) and transaction data. Person identifiers are fname, lname, phone, email and social security number. I want to link each transaction to a unique person. As a business rule, I have set that two transactions belong to the same person if fname and lname are identical AND at least one of the 3 other person identifiers are identical. As an outcome, I need to have two dataframes (and ultimately two csv files): one with the unique persons and one copy of the initial data with an additional column for the person id.

I have written code that works very well for solving the problem for small files. Except that when the file gets really long (hundreds of thousands of lines), it gets stuck. I am almost sure that my code is not optimized and I think I can find a better way using agreggate functions like groupby() or unique(), which I think are much faster. But I can't figure out how.

import pandas as pd
workDir=r"D:\fichiers\perso\perso\python\unicity\\"

sourceFile='rawdata.csv'
inFrame=pd.read_csv(workDir+sourceFile, sep=";",encoding='ISO-8859-1')
personFrame=pd.DataFrame(columns=('id','fname','lname','email', 'phone','social security number'))
outFrame=pd.DataFrame(columns=inFrame.columns)
idPerson=0
#print(inFrame)

def samePerson(p1, p2):
  response=0
  if p1['fname']==p2['fname'] and p1['lname']==p2['lname']:
      if p1['email']==p2['email'] or p1['phone']==p2['phone'] or p1['social security number']==p2['social security number']:
        response=1
  return(response)

def completePerson(old, new):
    #complete with new line missing data in ols version of the person
    for theColumn in ('fname','lname','email', 'phone','social security number'):
        if pd.isnull(old[theColumn]) :
            old [theColumn]=new[theColumn]
    return(old)

def processLine(theLine):
  global personFrame
  global idPerson
  global outFrame
  theFlag=0
  for indexPerson, thePerson in personFrame.iterrows():
      if theFlag==0:
          if samePerson(theLine,thePerson):
              theLine['idPerson']=thePerson.idPerson
              personFrame.loc[indexPerson]=completePerson(thePerson, theLine)
              theFlag=1
  if theFlag==0:
      theLine['idPerson']=idPerson
      idPerson=idPerson+1
      personFrame=personFrame.append(theLine)
  outFrame=outFrame.append(theLine)

def processdf():
    inFrame.apply(processLine, axis=1)
    with open(workDir+'persons.csv','w', encoding='ISO-8859-1') as f:
        personFrame.to_csv(f, index='false')
    with open(workDir+'transactionss.csv','w', encoding='ISO-8859-1') as f:
        outFrame.to_csv(f, index='false')

processdf()


texts: Finding an item name starting or ending with from a list

texts:
I have written this helper function. I want to know if there is an even better approach, considering that I do not want to add a dependency to any additional module.

def _isobjectInList(lst, name, criteria='startswith'):
    """ Find item in the list  starting or ending with name passed.

        :param lst: list of items/ objects
        :type lst: list

        :param name: name starting or ending with.
        :param name: string

        :param criteria: function of string obect whether startswith or endswith
        :param criteria: built-in method of str object
    """
    return [itemfound for itemfound in lst if getattr(itemfound, criteria)(name)]


texts: Quiz component with different but similar data models

texts:
I have a component with this template:

<ion-card *ngIf="isActive">
  <ion-card-header>{{question.question}}</ion-card-header>

  <ion-grid>
    <ion-row>
      <ion-col *ngFor="let answer of question.answers">
        <button ion-button outline (click)="answer.action()">{{answer.text}}</button>
      </ion-col>
    </ion-row>
  </ion-grid>

</ion-card>

And the code:

@Component({
  selector: 'extra-card',
  templateUrl: 'extra-card.html'
})
export class ExtraCard {
  public static readonly EXTRA_CARD_TYPE_1: string = "type_1";
  public static readonly EXTRA_CARD_TYPE_2: string = "type_2";

  @Input() type: string = ExtraCard.EXTRA_CARD_TYPE_1;

  isActive: boolean = true;
  question;

  constructor(
    private ga: GoogleAnalytics,
    private socialSharing: SocialSharing,
    private appRateService: AppRateService
  ) {}

  ngOnInit() {
    switch (this.type) {
      case ExtraCard.EXTRA_CARD_TYPE_1:
        this.makeExtraCardType1();
        break;

      case ExtraCard.EXTRA_CARD_TYPE_2:
        this.makeExtraCardType2();
        break;
    }
  }

  private makeExtraCardType1() {
    this.question = {
      question: "Some question",
      answers: [
        {text: "Answer 1", action: () => {this.action1Type1();}},
        {text: "Answer 2", action: () => {this.action2Type1();}},
        {text: "Answer 3", action: () => {this.action3Type1();}}
      ]
    };
  }

  private makeExtraCardType2() {
    this.question = {
      question: "Some question",
      answers: [
        {text: "Answer 1", action: () => {this.action1Type2();}},
        {text: "Answer 2", action: () => {this.action2Type2();}},
      ]
    };
  }

...

}

What does this code do?

A sequence of questions is shown to the user. Each question has several options. In the end of the sequence we do some action and skip this card.

What is the problem?

In this example I have 2 types of extra cards, but I want to have more (5, 10, 20, etc). In this case my component code will be growing too quickly.

What I want

I want to separate the logic of different question sequences. But I'm facing a problem with dependency injection for some unique actions in sequences. And I want to have a single component and use it like this:

<extra-card [type]="type_1"></extra-card>

Also, I want to avoid excessive dependency injections in the base component (in case with passing DI instances to question model).


texts: Python script that launches a process that it needs to clean up after and kill on receiving SIGTERM/SIGINT

texts:
I'm using a Python script to run a particular program that occasionally may need to be terminated (by receiving a SIGINT or SIGTERM) in which case a clean up process needs to be invoked (before killing the original process).

To test it I start the program in question and then I send a SIGINT to terminate it.

A signal handler is defined for SIGINT and SIGTERM that will launch a clean up program that takes as input a filepath output by the original process in its STDOUT. Afterwards it'll send a SIGTERM to the original process.

That clean up may hang in which case I raise a SIGALRM where I kill both the original process and the clean up process.

The problem is I'm not sure if I've covered all corner cases and I'm not really good at handling OS facilities (especially dealing with signals). For example, If I send SIGINT several times it terminates abruptly even though technically I have a flag to prevent SIGINT from being handled more than once.

EDIT: Included changes to the original code, such as the submission of subprocesses under process groups

Here's a stripped down version of the code:

import os
import sys
import signal
import subprocess

SUBMISSION_PROCESS = None # reference to the original process
CLEANUP_PROCESS    = None # reference to the clean up process
FILE_PATH          = '' # clean up process needs this from original process
HANDLER_CALLED     = False # to prevent signal handler from being called again

def kill_everything(signum, stack): # in case both processes hang...
    print 'Timed out, will kill all processes...'
    if SUBMIT_PROCESS:
        os.killpg(SUBMIT_PROCESS.pid, signal.SIGKILL)
    if CLEANUP_PROCESS:
        os.killpg(CLEANUP_PROCESS.pid, signal.SIGKILL)

def kill_submission_process(signum, stack):
    global HANDLER_CALLED
    global CLEANUP_PROCESS
    print 'Caught signal %d, please wait...' % signum

    if HANDLER_CALLED:
        print 'Already handling %d.' % signum
        return

    HANDLER_CALLED = True

    if FILE_PATH:
        stop_session_call = ['clean_up', '-arg_1', FILE_PATH]
        try:
            signal.alarm(120) # set a timeout for clean up session in case that fails too
            CLEANUP_PROCESS = subprocess.Popen(stop_session_call, preexec_fn=os.setsid)
            print 'Clean up process has started...'
            CLEANUP_PROCESS.communicate()
        except OSError as e:
            print >> sys.stderr, 'Unable to clean up session: an OSError was raised: %s' % e
    else:
        print >> sys.stderr, 'Unable to clean up session: file path not defined.'
    if SUBMISSION_PROCESS and SUBMISSION_PROCESS.poll() is None: # clean up original process if set and still running
        print 'Will clean up original submission process...'
        SUBMISSION_PROCESS.terminate()
        print 'Done, will quit.'
    raise SystemExit

if __name__ == '__main__':
    signal.signal(signal.SIGINT,  kill_submission_process)
    signal.signal(signal.SIGTERM, kill_submission_process)
    signal.signal(signal.SIGALRM, kill_everything)

    to_run = ['command', '-arg_1', 'param_1', '-arg_2', 'param_2']

    try:
        SUBMIT_PROCESS = subprocess.Popen(to_run, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=os.setsid)

        # Trying to parse process output to identify a particular file path
        while True:
            line = SUBMISSION_PROCESS.stdout.readline()
            if SUBMISSION_PROCESS.poll() != None and line == '': # if no more to read
                break
            line = line.rstrip('\n')
            print line
            if line[-4:] == '.ext': # line contains file path in question
                FILE_PATH = line # store it
                print 'File path found and saved.'
    except (OSError, IOError) as e:
        print >> sys.stderr, 'Exception raised while executing %s: %s.' % (' '.join(map(str, to_run)), e)
        raise SystemExit


texts: Project Euler #4 - Largest Palindrome Product

texts:
A palindromic number reads the same both ways. The largest palindrome
  made from the product of two 2-digit numbers is 9009 = 91 × 99.

  Find the largest palindrome made from the product of two 3-digit
  numbers.

How would you improve the following code?

I'm looking specifically for:

performance optimizations
ways to shorten the code
more "pythonic" ways to write it

   def is_palindrome(num):
        return str(num) == str(num)[::-1]
    def fn(n):
        max_palindrome = 1
        for x in range(n,1,-1):
            if x * n < max_palindrome:
                break
            for y in range(n,x-1,-1):
                if is_palindrome(x*y) and x*y > max_palindrome:
                    max_palindrome = x*y
                elif x * y < max_palindrome:
                    break
        return max_palindrome

    print fn(999)


texts:
I'm currently writing code so that when a red-colored cell appears in a column, a message box will appear letting me know that column has an error. I have written the following method:

Sub MSG()

    Dim a
    Dim B

    With Application.FindFormat.Interior
        .color = vbRed
    End With

    '/ Sheet1 is example sheet name
    Set a = Sheet1.Columns(1).Find(What:="", SearchFormat:=True)
    Set B = Sheet1.Columns(2).Find(What:="", SearchFormat:=True)

    If Not a Is Nothing Then
          MsgBox ("There is an issue with column A, please review.")
    End If
    If Not B Is Nothing Then
          MsgBox ("There is an issue with column B, please review.")
    End If

End Sub

But as you can see, expanding this to support an arbitrary number of columns would be impossible, and going up to column ED would require 134+ lines of code to be written!

Is there a more efficient way to do this? Would it be possible to optimize this code?


texts:
I'm teaching myself Object Oriented Programming in JavaScript and I'm looking over this small P5 code of CodingTrain's No.78, which deals with flying particles in the canvas, as a material.
The full code is below:
// Daniel Shiffman
// http://codingtra.in

// Simple Particle System
// https://youtu.be/UcdigVaIYAk

const particles = [];

function setup() {
  createCanvas(600, 400);
}

function draw() {
  background(0);
  for (let i = 0; i < 5; i++) {
    let p = new Particle();
    particles.push(p);
  }
  for (let i = particles.length - 1; i >= 0; i--) {
    particles[i].update();
    particles[i].show();
    if (particles[i].finished()) {
      // remove this particle
      particles.splice(i, 1);
    }
  }
}

class Particle {

  constructor() {
    this.x = 300;
    this.y = 380;
    this.vx = random(-1, 1);
    this.vy = random(-5, -1);
    this.alpha = 255;
  }

  finished() {
    return this.alpha < 0;
  }

  update() {
    this.x += this.vx;
    this.y += this.vy;
    this.alpha -= 5;
  }

  show() {
    noStroke();
    //stroke(255);
    fill(255, this.alpha);
    ellipse(this.x, this.y, 16);
  }

}

Wanting to train my OOP skill, I'm trying to refactor this code into more sophisticated one in the OOP point of view. So I refactored it by adding Particles_Manipulation class and moving the process written in draw function into the Particles_Manipulation class as action method.
The code is below:
// Daniel Shiffman
// http://codingtra.in

// Simple Particle System
// https://youtu.be/UcdigVaIYAk

class Particle {

  constructor() {
    this.x = 300;
    this.y = 380;
    this.vx = random(-1, 1);
    this.vy = random(-5, -1);
    this.alpha = 255;
  }

  finished() {
    return this.alpha < 0;
  }

  update() {
    this.x += this.vx;
    this.y += this.vy;
    this.alpha -= 5;
  }

  show() {
    noStroke();
    //stroke(255);
    fill(255, this.alpha);
    ellipse(this.x, this.y, 16);
  }

}

class Particles_Manipulation{
  constructor(){
    this.particles = [];
  }

  push_particles(_n){
    for (let i = 0; i < _n; i++) {
      let p = new Particle();
      this.particles.push(p);
    }
  }

  action(){
    for (let i = this.particles.length - 1; i >= 0; i--) {
      this.particles[i].update();
      this.particles[i].show();
      if (this.particles[i].finished()) {
        // remove this particle
        this.particles.splice(i, 1);
      }
    }
  }
}

const my_Particles_Manipulation = new Particles_Manipulation();

function setup() {
  createCanvas(600, 400);
}

function draw() {
  background(0);
  my_Particles_Manipulation.push_particles(5);
  my_Particles_Manipulation.action();
}

Could you evaluate my refactoring is nice or not?


texts: Lexicographically smallest wave like array without sorting

texts:
Given an array of integers, sort the array into a wave like array and return it. In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....

Example:

Given [1, 2, 3, 4]

One possible answer: [2, 1, 4, 3]

Another possible answer: [4, 1, 3, 2]

NOTE: If there are multiple answers possible, return the one that's lexicographically smallest. So, in example case, you will return [2, 1, 4, 3].

My solution is \$O(n\log n)\$ time since they want lexicographically. I'm unable to come up with a linear time solution for lexicographically smallest case. My questions here is, is it even possible to do that in \$O(n)\$ without sorting? I looked up online quite a bit and don't see any linear time solution for this scenario.

  public ArrayList<Integer> wave(ArrayList<Integer> a) {
    Collections.sort(a);
    if(a.size() == 0 || a.size() == 1)
        return a;
    int temp = -1;
    for(int i = 1; i < a.size(); i++) {
        if(i%2 == 0 && a.get(i) < a.get(i-1)) {
            temp = a.get(i);
            a.set(i, a.get(i-1));
            a.set(i-1, temp);
        }
        if(i%2 == 1 && a.get(i) > a.get(i-1)) {
            temp = a.get(i);
            a.set(i, a.get(i-1));
            a.set(i-1, temp);
        }
    }
    return a;
  }


texts: Structuring functions receiving and returning promises?

texts:
I keep running into the same pattern with code using promises in javascript.

When writing a function which takes a promise and returns a promise, obviously I want to reject the promise I'm returning when the promise I received is rejected (and usually I want to pass the error down the chain verbatim).  This results in a fair amount of boilerplate:

var fs = require ('fs');
var when = require ('when');
var nodefn = require ("when/node/function");

var get_some_data = function (filename) {
    return nodefn.call (fs.readFile, filename);
};

var parse_some_data = function (filename) {
    var deferred = when.defer ();

    var input = get_some_data (filename);
    input.then (function (data) {
        // imagine some complicated but synchronous process here which
        // may also call deferred.reject() if something goes wrong.
        deferred.resolve (JSON.parse (data));
    }, function (error) {
        deferred.reject (error);
    });

    return deferred.promise;
};

var do_something = function (filename) {
    var deferred = when.defer ();

    var input = parse_some_data (filename);
    input.then (function (data) {
        // imagine some complicated but synchronous process here which
        // may also call deferred.reject() if something goes wrong.
        data['foo'] = 'bar';
        deferred.resolve (data);
    }, function (error) {
        deferred.reject (error);
    });

    return deferred.promise;
};

Is there a better way to structure this code?  Do promise libraries have features which I'm not using, which would reduce the boilerplate?  (The above code uses when from cujo.js, but if other promise libraries have better solutions I'm interested in hearing about them).


texts: Computing average grades for students in a class

texts:
I wrote up a simple averages calculator for student grades, based on this daily programming challenge.

First, the script asks for the file name for the text file containing the student names and grades. It is formatted like so:

JON 19 14 15 15 16
JEREMY 15 11 10 15 16
JESSE 19 17 20 19 18

The user is then asked how many assignments there are.

While my solution works, it seems awfully verbose. Can you give me tips on "pythonic" ways to simplify the script?

grade_avg_generator.py

"""Simple student grade manager"""

from fileinput import input

def import_data(grades_file, assignments):
    """Split the data into key value pairs."""
    student_grades = dict()
    for line in input(grades_file):
        this_line = line.split()
        student_grades[this_line[0]] = [int(item) for item in this_line[1:assignments + 1]]
    return student_grades

def student_means(student_grades):
    """Generate the average grade for each student and append it."""
    for k, v in student_grades.iteritems():
        grades = v
        grades_mean = float(sum(item for item in grades)) / len(grades)
        v.append(grades_mean)
    student_grades_mean = student_grades
    return student_grades_mean

def class_mean(student_grades_mean):
    """Generate the class average."""
    class_grades = list()
    for k, v in student_grades_mean.iteritems():
        this_avg = v[-1]
        class_grades.append(this_avg)
    class_mean = float(sum(item for item in class_grades)) / len(class_grades)
    return class_mean

def main():
    grades_file = raw_input('File name: ')
    assignments = int(raw_input('How many assignments are there? '))

    student_data = import_data(grades_file, assignments)
    student_data_avg = student_means(student_data)
    class_avg = class_mean(student_data_avg)
    print 'class average: %0.2f' % class_avg
    for k, v in student_data_avg.iteritems():
        grades = v[:-1]
        grades = ' '.join(str(i) for i in grades)
        avg = str(v[-1])
        print 'name: %s | grades: %s | average: %s' % (k, grades, avg)

if __name__ == '__main__':
    main()


texts: Will this code make some attacks (XSS, CSRF...) harder to do?

texts:
I have following code on my login page (now i use it for preventing POST variable resubmit on page refresh):

<?php

$cleaner = md5(uniqid(rand(), TRUE));
$_SESSION["cleaner"]=(empty($_SESSION["cleaner"])) ? $cleaner : $_SESSION["cleaner"];

if($_POST['login_button'] && !empty($_POST['cleaner']) && $_SESSION['cleaner'] == $_POST['cleaner']){

    $cleaner = md5(uniqid(rand(), TRUE));
    $_SESSION['cleaner'] = $cleaner;

     //all other verification/login code

}
?>

<form method="POST" action="">
  <input type="hidden" name="cleaner" value="<?php echo $_SESSION['cleaner']; ?>" />
  <--! all other login html code and fields -->
</form>

Can this code make some attacks harder to do, or if not - what to change?


texts:
I created this simple macro that works fine for its purpose: allow the user to create a list of updates that need to be made based on groups in a target table (to basically do mass updates).

However, I am very concerned about the performance of this macro, it would take less time to do it manually if the list of updates becomes significantly long. I started optimizing the code using arrays but that seems not be enough.

What I am going to look into next is the use of dictionaries, is anyone aware of the most optimal way to achieve this?

Sub UpdateManualUpdates()
    Application.ScreenUpdating = False
    Dim lookUpSheet As Worksheet, updateSheet As Worksheet
    Dim valueToSearch As String
    Dim i As Long, t As Long

    Set lookUpSheet = Worksheets("Manual price changes")
    Set updateSheet = Worksheets("Price Build-up")

    Dim lookUpSheetArray As Variant
    Dim updateSheetArray As Variant

    lastRowLookup = lookUpSheet.Cells(Rows.Count, "F").End(xlUp).Row
    lastRowUpdate = updateSheet.Cells(Rows.Count, "B").End(xlUp).Row

    lookUpSheetArray = lookUpSheet.Range("A1:F" & lastRowLookup).Value
    updateSheetArray = updateSheet.Range("A1:AW" & lastRowUpdate).Value

    For i = 6 To lastRowLookup 'i = 2 to last to omit the first row as that row is for headers

        valueType = lookUpSheetArray(i, 5) 'lookUpSheet.Cells(i, 5) 'Type of update - Both, Planning group or GC
        valueGroup = lookUpSheetArray(i, 3) 'Family group
        valueGC = lookUpSheetArray(i, 4) 'GC
        ValueChange = lookUpSheetArray(i, 6) 'What is the % change
        'above get the values from the four column into variables

        For t = 6 To lastRowUpdate
            'AW is column 49 target column to update
            'M is target column for group, 13
            'C is target column for GC, 3
            If valueType = "Both" Then
                If updateSheetArray(t, 13) = valueGroup And updateSheetArray(t, 3) = valueGC Then
                    updateSheet.Cells(t, 49) = ValueChange
                End If
            End If
            If valueType = "Planning group" Then
                If updateSheetArray(t, 13) = valueGroup Then
                    updateSheet.Cells(t, 49) = ValueChange
                End If
            End If
            If valueType = "GC" Then
                If updateSheetArray(t, 3) = valueGC Then
                    updateSheet.Cells(t, 49) = ValueChange
                End If
            End If
        Next t
    Next i
    Application.ScreenUpdating = True
End Sub


texts: Quick select - shuffle to make sorting faster

texts:
I'm trying to use shuffle to improve worse case scenario of quick select (e.g. every time, selected pivot value is the largest, so each iteration, only one elements could be removed from judgement).

My solution to this problem is to use shuffle, but I am not sure if using shuffle still have small chance (during every shuffle). The selected pivot is happening to be the largest element.

Any advice on algorithm time complexity improvement, code bugs or general code style advice is highly appreciated.

The entry point of my code is quick_select_k_largest, which tries to get k-th largest element from a list, and the 1st largest element from the list is max value element of the list (i.e. k starts from 1 other than 0).

import random
def shuffle(numbers, start, end):
    if start == end:
        return
    for i in range(start+1, end+1):
        index = random.randint(start,i-1)
        numbers[index], numbers[i] = numbers[i], numbers[index]

def quick_select_k(numbers, start, end, k):
    shuffle(numbers, start, end)
    pivot = numbers[end]
    i = start
    j = end - 1
    while i <= j:
        while i <= j and numbers[i] <= pivot:
            i += 1
        while numbers[j] > pivot:
            j -= 1
        if i < j:
            numbers[i], numbers[j] = numbers[j], numbers[i]
    numbers[i], numbers[end] = numbers[end], numbers[i]
    if i == k:
        return numbers[k]
    elif i > k:
        return quick_select_k(numbers, start, i-1, k)
    else:
        return quick_select_k(numbers, i+1, end, k)
def quick_select_k_largest(numbers, k):
    index = len(numbers) - k
    return quick_select_k(numbers, 0, len(numbers)-1, index)

if __name__ == "__main__":
    numbers = []
    for i in range(10):
        numbers.append(random.randint(0,20))
    k = random.randint(1,10)
    print quick_select_k_largest(numbers, k)
    print k, sorted(numbers)


texts: Review of HTML markup for this blog concept

texts:
I am creating a blog concept with this layout on CodePen

Here is my current code in development

Skating Down Venice Beach

Venice Beach

Literally trust fund Helvetica dreamcatcher selfies. Pinterest aesthetic organic Echo Park artisan meggings tousled Tumblr, Pitchfork gentrify raw denim yr you probably haven't heard of them banjo. Street art Wes Anderson ethnic ethical authentic, High Life swag ennui. Wolf cardigan fingerstache gentrify, PBR&B cray XOXO vegan deep v tote bag ethnic. Banh mi you probably haven't heard of them seitan meh Austin iPhone. High Life wolf Tonx, dreamcatcher lo-fi seitan ethnic pop-up fingerstache whatever. Trust fund Portland ethnic church-key, Tumblr squid hoodie dreamcatcher +1 seitan.

When I move to production, I will use a MustacheJS template in Meteor. So was planning on this

<template name="posts">

{{title}}

{{city}}

      {{{content}}}

</template>

Is there any room for improvement here? for example, will I be better off using
s? or should I perhaps change anything else?


texts:
I have 3 models: Import, Product, Values.
An import has_many products.
A product has_many values.

I want to find the product with the highest values count and the sum of all values for all those products. My current method is very expensive.

@import = Import.find(params[:id])
@products = @import.products
@max_product = @products.max_by{|product| product.values.count}
@values_count = @products.sum{|product| product.values.count}

How can I make this more efficient ?


texts: Checking if an associated object has failed to save/create

texts:
I smell something wrong here, but am not quite sure what the most idiomatic way to solve the problem.

I have a controller for (job)listings and it has a method called apply.  This method is used when someone has a resume and is clicking to apply for the job associated with the listing.

def apply
  set_resume
  if @resume.apply_to(@listing)
    redirect_to @listing
  else
    redirect_to @listing, alert: 'Unable to apply for job'
  end
end

This calls a method on the resume object:

def apply_to(listing)
  jobapp = Jobapp.new(resume: self, listing: listing)
  jobapp.save
end

Everything above works just fine - it just seems inelegant (and I don't get the errors associated with the jobapp object, although that's not vitally important).

If I use the following method in place of the above method:

def apply_to(listing)
  Jobapp.create(resume: self, listing: listing)
end

The conditional if @resume.apply_to(@listing) always returns true, even if the Jobapp failed to be created.

What is a cleaner way of achieving this task?


texts: SmartRandom bombing strategy for Battleship game

texts:
Now that I have some infrastructure in place to test it (see my Battleship test framework and the updated GitHub project for the full context), I have finally written a non-trivial bombing strategy class for the May 2015 Community Challenge.

The SmartRandom class guesses randomly until it gets a hit.  It then checks for possible ship positions based on that hit, and caches those guesses.  It then uses the cached guesses until either a ship is sunk (at which point it dumps the cache) or until the cache of guesses is exhausted.

SmartRandom.h

#ifndef SMARTRANDOM_H
#define SMARTRANDOM_H
#include "Ocean.h"
#include "Bomber.h"

class SmartRandom : public Bomber
{
public:
    SmartRandom() : Bomber(), next() {}
    SmartRandom(Ocean &o) : Bomber(o), next() {}
    bool turn();
    const char *id() const { return "SmartRandom"; }
private:
    // vector holding the next guesses
    std::vector<unsigned> next;
};

#endif // SMARTRANDOM_H

SmartRandom.cpp

#include <iostream>
#include <string>
#include <random>
#include "SmartRandom.h"

static std::random_device rd;
static std::uniform_int_distribution<> r{0, Ocean::dim*Ocean::dim-1};

/*
 * The strategy here is to bomb randomly, but to follow
 * up promptly when a ship is found.
 */
bool SmartRandom::turn() {
    ++turns;
    unsigned location = r(rd);
    // try using our pre-stored guesses first
    if (!next.empty()) {
        for (location = next.back();
                tracking[location] && !next.empty();
                location = next.back())
        {
            next.pop_back();
        }
    }
    if (tracking[location])
        for (location = r(rd);
                tracking[location];
                location = r(rd))
        { }
    char result = ocean.bomb(location);
    if (result != ocean.empty) {
        if (result == ocean.hit) {  // generic hit
            unsigned shortship = ocean.shipcount-1;
            if (tracking.place(location, shortship, true, true))
                next.push_back(location+1);
            if (tracking.place(location, shortship, false, true))
                next.push_back(location+ocean.dim);
            if (tracking.place(location-1, shortship, true, true))
                next.push_back(location-1);
            if (tracking.place(location-ocean.dim, shortship, false, true))
                next.push_back(location-ocean.dim);
        } else {  // specific ship was just sunk
            next.clear();
        }
    }
    tracking.record(location, result);
    if (verbose)
        std::cout << "Turn " << turns << ", bombing " <<
            location << '\n' << ocean << std::endl;
    return ocean.remaining();
}

Results

I used two different placement strategies (as explained in the Battleship test framework question) and two different bombardment strategies.  The first was a relatively stupid random bombing strategy and the second is this one, which performs much better.  (The numbers are the number of turns it took to sink all ships.)

There are 2 placers, and 2 bombers
Running 10 iterations
UpperLeft/RandomBomber  UpperLeft/SmartRandom   RandomPlacer/RandomBomber   RandomPlacer/SmartRandom
95  45  94  84
94  57  95  61
98  97  97  90
76  81  89  79
96  52  95  82
96  36  96  44
92  51  87  66
92  62  83  40
96  84  81  74
91  70  96  62

Questions

I'm interested in comments on the code, of course, but also in suggestions for improvements to the algorithm.


texts: Converting a float to a fraction as a string

texts:
I was inspired by this video by Matt Parker to use the Farey Sequence to convert a float into a string representation of a fraction, how did I do? How well did I follow F# workflow and patterns (I'm new to the language)? Can it be done better, or rather, how would a "professional" F# developer write this function? Thanks in advance!
let toFraction num =
  let rec farey n0 d0 n1 d1 =
    let n2 = n0 + n1
    let d2 = d0 + d1

    match (n2 / d2) with
    | x when abs (x - num) < 1e-5 -> string n2 + " / " + string d2
    | x when x < num -> farey n2 d2 n1 d1
    | x when x > num -> farey n0 d0 n2 d2
    | _ -> "" // Compiler detects "incomplete pattern matches on this expression without this wildcard,
    // maybe this is where my method can be improved?

  farey 0. 1. 1. 1.

Additionally, this problem assumes the input num is in the set 0 <= num < 1


texts: Combining two indexOf and regex in to one

texts:
I have the following code that splits a combination of names on either the word and or the & ampersand:

    var name = 'Ron & Peggy Sue'; //or 'Ron and Peggy Sue';

    if ( name.indexOf('&') > -1 ){
        names = name.split(/ & /g);
    }

    if ( name.toLowerCase().indexOf(' and ') > -1 ) {
        names = name.split(/ and /gi);
    }

Its returns an array of names like:

names = ['Ron', 'Peggy Sue']; //regardless of `&` or `and` separator

I was trying to combine these two conditions into one, but the results were not what I wanted. I know there must be a better way. How can the above code be improved?


texts: Parallelized Sobel algorithm using OpenMP

texts:
I implemented the Sobel algorithm sequentially, and got decent performance (1.49 s) but wanted to improve it. I parallelized it with OpenMP and got a ~3x speedup (0.523 s). I'd like to do better, but I'm not sure how.

// -------  C/C++ includes ------
#include <iostream>
#include <stdio.h>

#include <omp.h>
#include <time.h>

// ------ OpenCV includes ------
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

// dimension of kernel
int x[3][3];
int y[3][3];

/*----- OpenMP -----*/
int num_of_threads, i ,j;
double start, end;

int main( int argc, char** argv )
{

    Mat initialImage = imread(argv[1], 0); // imread gray-scale image
    Mat finalImage = Mat::zeros(initialImage.size(), initialImage.type());

    if (finalImage.type() == initialImage.type() )
    {
        cout << "YES" << endl;
    }

    if(argc != 2 || !initialImage.data)
    {
        cout << "No image data or Usage: ./sobel imagePath" << endl;
        return -1;
    }
    else
      cout << "Image OK!" << endl;

    //x direction
    x[0][0] = -1;  x[0][1] = 0;  x[0][2] = 1;
    x[1][0] = -2;  x[1][1] = 0;  x[1][2] = 2;
    x[2][0] = -1;  x[2][1] = 0;  x[2][2] = 1;

    //y direction
    y[0][0] = -1;  y[0][1] = -2;  y[0][2] = -1;
    y[1][0] =  0;  y[1][1] =  0;  y[1][2] =  0;
    y[2][0] =  1;  y[2][1] =  2;  y[2][2] =  1;

    num_of_threads = 8;//omp_get_num_procs();
    omp_set_num_threads(num_of_threads);

    start = omp_get_wtime();
    for(j = 0; j < initialImage.rows - 2; j++ ){
      #pragma omp parallel for private(i)
      for(i = 0; i < initialImage.cols -2; i++ ){
        // applay karnel in x direction
        int xValOfPixel =
         (x[0][0] * (int)initialImage.at<uchar>(j, i    )) + (x[0][1] * (int)initialImage.at<uchar>(j + 1, i    )) + (x[0][2] * (int)initialImage.at<uchar>(j + 2, i    )) +
         (x[1][0] * (int)initialImage.at<uchar>(j, i + 1)) + (x[1][1] * (int)initialImage.at<uchar>(j + 1, i + 1)) + (x[1][2] * (int)initialImage.at<uchar>(j + 2, i + 1)) +
         (x[2][0] * (int)initialImage.at<uchar>(j, i + 2)) + (x[2][1] * (int)initialImage.at<uchar>(j + 1, i + 2)) + (x[2][2] * (int)initialImage.at<uchar>(j + 2, i + 2));

        // apply karnel in y direction
        int yValOfPixel =
         (y[0][0] * (int)finalImage.at<uchar>(j, i    )) + (y[0][1] * (int)finalImage.at<uchar>(j + 1, i    )) + (y[0][2] * (int)finalImage.at<uchar>(j + 2, i    )) +
         (y[1][0] * (int)finalImage.at<uchar>(j, i + 1)) + (y[1][1] * (int)finalImage.at<uchar>(j + 1, i + 1)) + (y[1][2] * (int)finalImage.at<uchar>(j + 2, i + 1)) +
         (y[2][0] * (int)finalImage.at<uchar>(j, i + 2)) + (y[2][1] * (int)finalImage.at<uchar>(j + 1, i + 2)) + (y[2][2] * (int)finalImage.at<uchar>(j + 2, i + 2));

         int sum = abs(xValOfPixel) + abs(yValOfPixel);
         if(sum > 255)
          sum = 255;

        finalImage.at<uchar>(j, i) = (uchar)sum;
      }
    }
    end = omp_get_wtime();

    cout << "Time: " << end - start << endl;

    // display the images
    namedWindow("Initial Image", WINDOW_AUTOSIZE);
    namedWindow("Final Image", WINDOW_AUTOSIZE);
    imshow("Initial Image",initialImage);
    imshow("Final Image",finalImage);

    waitKey(0);
    return 0;
}


texts: Fetching ALL data set from API iterating via response data

texts:
Does this make sense? How would you achieve the same thing, with cleaner code?

function retrieveBatch(offset){
  var opts = {}
  opts.limit = 100
  if(offset) opts.offset = offset
  return new Promise(function(resolve, reject) {
    chargebee.subscription
    .list(opts)
    .request(function(err, value){
      if(err) return reject(err)
      return resolve(value)
    })
  })
}

function retireveAll(){
  var subscriptions = []
  function inception(data){
    if(!data) return retrieveBatch().then(inception)
    if(data && data.list) subscriptions.push(data.list)
    if(data && data.next_offset) return retrieveBatch(data.next_offset).then(inception)
    if(data && !data.next_offset) return _.flatten(subscriptions)
  }
  return Promise.resolve(inception(false))
}


texts: Adjoin-set for an ordered set representation

texts:
From SICP:

  Exercise 2.61

  Give an implementation
  of adjoin-set using the ordered
  representation. By analogy with
  element-of-set? show how to take
  advantage of the ordering to produce a
  procedure that requires on the average
  about half as many steps as with the
  unordered representation.

(define (adjoin-set x set)
  (define (rec subset)
    (cond ((null? subset) (list x))
          ((> x (car subset)) (cons (car subset) (rec (cdr subset))))
          (else (cons x subset))))
  (if (element-of-set? x set)
      set
      (rec set)))

Can this be improved?


texts:
I'm using SSL proxying to my squarespace.com site since they don't allow SSL. I was previously setting the HSTS header so I have some browsers that won't go to an HTTP version of my page. I need to use this proxy behavior to ensure they can still get to my page. Also, I want to make sure I haven't overlooked an issue with redirection looping.

Can I get some feedback about this configuration file? Did I leave anything out or add anything in that shouldn't be there?

# HTTP redirect for www
server {
    listen 80;

    server_name www.domain.com;
    return 301 http://domain.com$request_uri;
}

# HTTP listening
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/html;
    index index.php index.html index.htm ;

    server_name  domain.com;

    location / {
        proxy_set_header Host $host;
        proxy_pass http://192.168.2.100; # example IP, not my real IP
    }
}
# HTTPS Server

server {
    listen 443 ssl;

    ssl_certificate /etc/ssl/domain.com.chained.crt;
    ssl_certificate_key /etc/ssl/nginx.key;

    error_log /var/log/nginx/domain.error.log crit;

    server_name domain.com www.domain.com;
    location / {
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host  $http_host;
        proxy_set_header X-NginX-Proxy    true;
        proxy_set_header Connection "";
        proxy_http_version 1.1;
        proxy_pass https://192.168.2.100; # example IP, not my real IP
    }
}


texts:
I have a buffer - int array with defined length. I want to read and write values into this array in parallel. For instance, 5 readers and 3 writers with different intervals. Additionally, I want to block waiting readers and waiting writers until a specific operation (read or write) is available.

Buffer:

public class IntBuffer
{
    private readonly AutoResetEvent _readDone = new AutoResetEvent(false);
    private readonly AutoResetEvent _writeDone = new AutoResetEvent(false);

    private readonly int[] _array;
    private int _index;

    public IntBuffer(int bufferSize)
    {
        _array = new int[bufferSize];
        _index = -1;
    }

    public void Write(int insert)
    {
        while (true)
        {
            if (_index >= -1 && _index < _array.Length - 1)
            {
                try
                {
                    Monitor.Enter(this);

                    if (_index >= -1 && _index < _array.Length - 1)
                    {
                        _array[++_index] = insert;
                        return;
                    }
                }
                finally
                {
                    Monitor.Exit(this);
                    _readDone.Set();
                }
            }

            Console.WriteLine("waiting for add...");
            _writeDone.WaitOne();
        }

    }

    public int Read()
    {
        while (true)
        {
            if (_index >= 0)
            {
                try
                {
                    Monitor.Enter(this);
                    if (_index >= 0)
                    {
                        var val = _array[_index--];
                        return val;
                    }
                }
                finally
                {
                    Monitor.Exit(this);
                    _writeDone.Set();
                }
            }

            Console.WriteLine("waiting for read...");
            _readDone.WaitOne();
        }
    }
}

Reader:

public class Reader
{
    private readonly IntBuffer _buff;

    public Reader(IntBuffer buff)
    {
        _buff = buff;
    }

    public void Start(int sleepMs)
    {
        while (true)
        {
            Thread.Sleep(sleepMs);
            Console.WriteLine($"reader read {_buff.Read()}");
        }
    }
}

Writer:

public class Writer
{
    private readonly IntBuffer _buff;
    private readonly Random _random = new Random(Guid.NewGuid().GetHashCode());

    public Writer(IntBuffer buff)
    {
        _buff = buff;
    }

    public void Start(int sleepMs)
    {
        while (true)
        {
            Thread.Sleep(sleepMs);
            int val = _random.Next(1, 500);
            _buff.Write(val);
            Console.WriteLine($"writer write {val}");
        }
    }
}

All in one:

var buffer = new IntBuffer(8);

new Thread(() => new Writer(buffer).Start(1700)).Start();
new Thread(() => new Writer(buffer).Start(2900)).Start();
new Thread(() => new Writer(buffer).Start(3450)).Start();

new Thread(() => new Reader(buffer).Start(5000)).Start();
new Thread(() => new Reader(buffer).Start(3000)).Start();
new Thread(() => new Reader(buffer).Start(1400)).Start();

Please review and add remarks.


texts:
I'm writing a function in JavaScript which, when given an element, can look for the previous or next node, assuming a depth-first order traversal. If the next element is out of bounds, it should return null.

I could of course use document.querySelectorAll('*'), find the index of the element, and then move forwards/backwards by one. But this approach seems like overkill, since I would think it would be inefficient to get the entire DOM tree as a depth-first searched structure, when I could theoretically traverse by one element using local information.

I can't shake the feeling that I'm repeating much of the logic. Can anyone tell if there's a better refactored version I'm not seeing?

//returns previous element in a depth-first search traversal
//returns null if at the start of the tree
TreeWalker.prototype.getPreviousElement = function(element) {
  var previousElement;
  if(element.previousElementSibling === null) {
    var parent = element.parentElement;
    if($(parent).is(this.rootSelector)) {
      previousElement = null;
    } else {
      previousElement = parent;
    }
  } else {
    var beforeBranch = element.previousElementSibling;
    previousElement = this.cycleToPreviousBranch(beforeBranch);
  }
  return previousElement;
};

TreeWalker.prototype.cycleToPreviousBranch = function(element) {
  var previousElement;
  if(element.children.length === 0) {
    previousElement = element;
  } else {
    var lastChild = element.lastElementChild;
    previousElement = this.cycleToPreviousBranch(lastChild);
  }
  return previousElement;
};

//returns next element in a depth-first search traversal
//returns null if at the end of the tree
TreeWalker.prototype.getNextElement = function(element) {
  var nextElement;
  if(element.children.length > 0) {
    nextElement = element.children[0];
  } else {
    nextElement = this.cycleToNextBranch(element);
  }
  return nextElement;
};

TreeWalker.prototype.cycleToNextBranch = function(element) {
  var nextElement;
  if(element.nextElementSibling !== null) {
    nextElement = element.nextElementSibling;
  } else {
    var parent = element.parentElement;
    if($(parent).is(this.rootSelector)) {
      nextElement = null;
    } else {
      nextElement = this.cycleToNextBranch(parent);
    }
  }
  return nextElement;
};


texts: Menu selector that changes the background of a selected div

texts:
I made this code to change the background color for a div in a set of divs while disabling the rest of the divs in the background. It works fine, but I wanted the code reviewed for more improvements since I am new to jQuery and JavaScript.

عن المشروع

المميزات الرئيسية

الخارطة

البوم الصور والفيديو

  var count = $(".ProjectMainLink").length;
     for(var i=0; i<count;i++){
         $(".ProjectMainLink").eq(i).click(function() {
              $(".ProjectMainLink").css("background-color","");
            $(this).css("background-color","#fff");

        });
         }


texts: Bash function to dynamically move N directories above the current directory

texts:
up moves N directories above the current directory (executes "cd ..""
N times)
When executed without input values it moves only one
directory above the current directory
When executed with input
values, up uses the first input value (checking to see if it is a
positive integer)to move above the current directory the specified
number of directories

up() {
    if [ -z "$1" ]
        then
            eval "cd .."
    else
        if [ "$1" -eq "$1" ]
            then
                if [ "$1" -gt "0" ]
                    then
                        for i in `seq 1 $1`;
                        do
                            eval "cd .."
                        done
                            eval "pwd"
                else
                    echo "First argument is not a positive integer"
                fi
        else
            echo "First argument is not an integer"
        fi
    fi
}

I did consider building a cd ../../.. etc., chain which would execute after the for loop builds the required string and would also preserve the usefulness of cd - but this version was slightly cleaner.

The [ "$1" -eq "$1" ] thing is one way to check if a value is an integer.


texts: Check that elements in list follow a specified date-format schema and are not null/na/nan

texts:
I'm practicing some data-analysis and I'm currently checking the integrity of my data. The elements that do not follow my date-schema, should be funneled to a new separate list so I can work on strategies and suggestions on how to handle these exceptions.
The following code checks the format successfully:
def datetime_check_format(col):
    tracker = []
    false_dates = []
    true_dates = []
    counter = 0
    for element in col:
        if not isinstance(pd.to_datetime(element, errors="ignore", format= "%d-%m-%Y"), date):
            counter += 1
            true_dates.append(pd.to_datetime(element, errors="raise", format= "%Y-%m-%d"))
        else:
            counter +=1
            false_dates.append(element)
            tracker.append(counter)

    if len(tracker) == 0:
        return "column is ok."
    else:
        return tracker, false_dates, true_dates

I was wondering if someone has an idea on how to make this code better. It seems to be based on some backwards bending mobius-ring kind of twisted logic.
I used this one as guide, since it told me of error-handling:
pandas.to_datetime
best regards,
Jacob Collstrup


texts: Python function to implement an image-processing pipeline

texts:
I have written the following function to process images. Now I am not sure if it's pythonic or considered as spaghetti code. I know being flat is better than nested, but I don't see a way around it.

I could easily apply list comprehensions if the "if" statements are only resolving true/false, but each step depends on the output of the previous steps, so I don't think I could use itertools.

def get_image(width, height, collection_sku, order_id, name, handle):
    """image processing pipeline"""

    # Check-1 image exception should be checked before proceeding further
    # covers both images in exception(currently bookshelves) list and also personal true doors
    #   1. bookshelves need to be cropped
    #   2. personal images needs to be added in the required size
    if helpers.image_exception(collection_sku):

        # Step-1 Find image folder
        directory_sizes = helpers.find_directory(width, height)

        if directory_sizes is not None:
            # Step-2 Find the image from the given folder.
            key = helpers.find_image(directory_sizes, collection_sku)

            if key is not None:

                requires_resize = helpers.should_resize(width, height)
                requires_flip = helpers.should_flip(handle) and not helpers.flip_exception(collection_sku)

                # Check-2 check whether image requires resizing or flipping
                if requires_resize or requires_flip:

                    # Step-3 Create local directory to store temporary images
                    location, is_created = helpers.local_directory(
                        order_id)

                    if is_created:
                        # Step-4 Download image
                        image = helpers.download_image(key, location, name)

                        if image is not None:
                            width_px = helpers.cm_to_pixel(width)
                            height_px = helpers.cm_to_pixel(height)
                            image_modified = False

                            # Step-5.1 Resize image
                            if requires_resize:
                                helpers.resize_image(image, width_px, height_px)
                                image_modified = True

                            # Step-5.2 Flip image
                            if requires_flip:
                                helpers.flip_image(image)
                                image_modified = True

                            # Step-6 Upload image
                            if image_modified:
                                helpers.upload_image(image, key)

                    # Step-3 No local dir created
                    # Step-4 Can't download image
                    # Step-5.1 Can't resize image
                    # Step-5.2 Can't flip image
                    # Step-6 Can't upload image
                    return None

                # Check-2 if no image processing required then copy image over
                helpers.copy_image(key, target=None) # TODO
                return True

    # raise exception in sub job
    #   Check-1 if image door image cannot be processed
    #   Step-1 if directory not available
    #   Step-2 if image not available

    return None


texts: Am I using crypt and mcrypt well in this simple encryption class?

texts:
These days I read a lot here on SO about password hashing and data encryption. It's a real mess, I mean, deciding what the best practice is. I need a very simple class that can be reused anywhere and that provide a decent-but-not-paranoic security level for my PHP applications (I do not handle bank data). Additionally, I want to rely as much as possible on PHP standard libs. I came up with this:

class Security {

    public static function hashPassword($plain) {
        $salt = md5(rand(0, 1023) . '@' . time()); // Random salt
        return crypt($plain, '$2a$07$' . $salt); // '$2a$07$' is the Blowfish trigger
    }

    public static function checkPassword($plain, $hash) {
        return (crypt($plain, $hash) === $hash);
    }

    public static function generateIv() {
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); // It's 32
        return mcrypt_create_iv($iv_size, MCRYPT_RAND);
    }

    public static function encrypt($key, $data, $iv = null, $base64 = true) {
        if (is_null($iv)) $iv = md5($key);
        $ret = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv);
        return ($base64 ? base64_encode($ret) : $ret);
    }

    public static function decrypt($key, $data, $iv = null, $base64 = true) {
        if (is_null($iv)) $iv = md5($key);
        return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $base64 ? base64_decode($data) : $data, MCRYPT_MODE_CBC, $iv), "\0");
    }

}

As you can see, I choose to hash passwords with crypt() using Blowfish hashing algorithm. The return value of hashPassword() is the salt + hash that then I store in the DB. I made this choice because crypt() is available on every server, provides a confortable way to check hash regardless of algorithm used (it's based on salt prefix) and, I read, bcrypt is a decent hashing method.

Then, for data encryption I used mcrypt() Rijndael 256 algorithm with CBC mode. As you can see, I can use encryption methods in two way. I can pass a IV (and generateIv() helps me to create one) that I will store in the DB along crypted data, or, if I don't, a basic IV is derived from key in both crypt and decrypt process.

What do you think about it? Am I missing something? Can I be finally relaxed about hashing and encryption in my PHP applications?


texts:
I started learning programing with C++. It runs perfectly, but I wonder what things I can improve following the principles of class inheritance, access, overwriting, virtual functions and destructors, and why.
#include <iostream>  // allows program to output data to the screen
using namespace std;

struct Base {
    virtual void do_something() {};
    virtual ~Base(){};

};

struct Derived1 : public Base {
    Derived1():Base(){}
    virtual void do_something() {
        std::cout << "Derived1!!!" << std::endl;
    }
    virtual~Derived1(){};
};

struct Derived2 : public Base {
   Derived2():Base(){}
    virtual void do_something() {
        std::cout << "Derived2!!!" << std::endl;
    }
    virtual ~Derived2(){};
};

// function main begins program execution
int main(int argc, const char *argv[]) {
    std::cout << "Welcome" << std::endl;

    Derived1 derived1;
    derived1.do_something();

    Derived2 derived2;
    derived2.do_something();

    return 0;

}  // end function main


texts: Moving certain items in a list to the end

texts:
I am learning Python and would like to know if there's a better way to rewrite it.

What I am trying to do is to match list A that is passed to a method against a predefined list B. If an item in list A contains an item in list B, I'd like to move it to the end of list A.

# example 1
a = [1, 2, 3, 4, 5]
sanitized_list = sanitize(a) # [3, 4, 5, 1, 2]

# example 2
a = [3, 6, 1, 7, 4]
sanitized_list = sanitize(a) # [3, 6, 7, 4, 1]

def sanitize(arg):
    # predefined list
    predefined_list = [1, 2]

    for item in predefined_list:
        try:
            # check to see if 'arg' contain any item
            # in the predefined list
            i = arg.index(item)

            # save the value of arg[i]
            j = arg[i]

            # remove "j" from "arg"
            arg.pop(i)

            # append item to end of "arg"
            arg.append(j)
        except ValueError:
            pass

    return arg


texts: Quadratic "Complete the Square" Solver in Python 3

texts:
I quickly wrote this program to transform quadratic expressions in general form into vertex form.

\$ax^2 + bx + c \;=\; a(x-h)^2 + k,\quad\text{where}\quad h = -\frac{b}{2a} \quad\text{and}\quad k = c - ah^2 = c - \frac{b^2}{4a}.\$

The actual conversion is easy, but with writing a lexer/parser came pain points:

I tokenize with Regex, and some of the regex patterns are built dynamically using f-strings (which seems suspect).
I use eval to compute terms in parentheses (to make fractions easy to input, for example).

I also feel like there's probably a library for working with ASCII-fied algebraic expressions, (lots of the same kind of code populates sites like Symbolab, Cymath and Desmos,) but I do not know of it.

## Tests:
# user_in = "(16/4)x^2 7x (3**2)" -> "Result is: 4.0(x + (0.875))^2 + (5.9375)" (Passes)
# user_in = "(41*4)x^2 41x 2" -> "Result is: 164.0(x + (0.125))^2 + (-0.5625)" (Passes)
# user_in = "x^2 4" -> "Result is: (x + (2.0))^2 + (-4.0)" (Fails)
# user_in = "x^2 4x 16" -> "Result is (x + (2.0))^2 + 12.0" (Fails)

import re

print("""~~~Square Completer!~~~
Enter the terms of your quadratic equation in standard form
Addition is implied, terms separated by spaces.
Only use one kind of single-letter variable in the whole expression.
Surround computations such as constant multiplication and fractions in parens.
DO NOT put variables inside parens!""")
user_in = input("> ")

# extract the variable
def extract_variable(expression):
    letters = re.findall(r'[a-z]', expression) # all the letters
    if all(match == letters[0] for match in letters): # if all letters == the first one
        return letters[0] # we have our variable
    else:
        raise ValueError("Only use one kind of single-letter variable in the whole expression.")

variable = extract_variable(user_in)

# eval all things in parens and split string into terms
def split_into_terms(expression):
    expression = re.sub(fr"\([^{variable}\)]+\)", lambda m: str(eval(m.group())), expression)
    print(f"working with {expression}")
    return expression.split(' ')

terms = split_into_terms(user_in)
print(terms)

# sort terms into bins

def bin_terms(terms):
    squareds, x_es, constants = [], [], []
    for term in terms:
        term = term.strip().lower()
        if term.endswith('^2'):
            squareds.append(term[:-2]) # without trailing '^2'
        elif term.endswith(variable):
            x_es.append(term)
        elif bool(re.search(r"^-?[0-9\.]+$", term)): # if the term contains only numbers
            constants.append(term)
    return squareds, x_es, constants

squareds, x_es, constants = bin_terms(terms)

print('unprocessed:', squareds, x_es, constants, sep='\n')

def sum_bins(squareds, x_es, constants):
    squareds = [squared[:-1] for squared in squareds if squared.endswith(variable)] # 2x -> 2
    print('squareds step1:', squareds, sep='\n')
    squareds = ['1' if squared == variable else squared for squared in squareds] # x -> 1
    print('step2:', squareds)

    print('\nprocessed:', squareds, x_es, constants, sep='\n')

    constant = sum(float(c) for c in constants)
    print('\n ***EXES: ', x_es,'***')
    x = sum(float(el[:-1]) for el in x_es)
    print('\n ***SUMX: ', x,'***')
    squared = sum(float(el) for el in squareds)

    return squared, x, constant

squared, x, constant = sum_bins(squareds, x_es, constants)

##print('\ntotals:', squared, x, constant, sep='\n')

##constant = constant / squared
##x = x / squared
##squared = 1

##print('\nover square term:', squared, x, constant, sep='\n')

def complete_square(a,b,c):
    """
    Complete the square, transforming a quadratic
    of form
    ax^2 + bx + c
    to form
    a(x + p)^2 - q
    """
    p = b/(2*a)
    q = c - (b**2)/(4*a)
    return p, q

p, q = complete_square(squared, x, constant)
a = squared
print(f'Result is: {a}({variable} + ({p}))^2 + ({q})')


texts:
public class EmployeeDBHandler
    {
        public List<Employee> GetEmployees()
        {
            List<Employee> empList = new List<Employee>();
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("GetAllEmployee", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlConn.Open();
            using (SqlDataReader reader = sqlCmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var emp = new Employee()
                    {
                        EId = (int)(reader["EmpID"]),
                        FirstName = Convert.ToString(reader["FirstName"]),
                        LastName = Convert.ToString(reader["LastName"])
                    };
                    empList.Add(emp);
                }
            }
            return empList;
        }
        public List<Employee> FetchEmployee(int empid)
        {
            List<Employee> empList = new List<Employee>();
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("usp_FetchEmployeeDetails", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@EmpID", empid);
            sqlConn.Open();
            using (SqlDataReader reader = sqlCmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var emp = new Employee()
                    {
                        EId = (int)(reader["EmpID"]),
                        FirstName = (reader["FirstName"].ToString()),
                        LastName = (reader["LastName"].ToString())
                    };
                    empList.Add(emp);
                }
            }
            return empList;
        }
        public void AddEmployeeInfo(string firstname, string lastname)
        {
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("AddEmployee", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@FirstName", firstname);
            sqlCmd.Parameters.AddWithValue("@LastName", lastname);
            sqlConn.Open();
            sqlCmd.ExecuteNonQuery();
            sqlConn.Close();
        }
        public void UpdateEmployee(int empid,string firstname, string lastname)
        {
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("usp_UpdateEmployeeDetails", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@EmpID", empid);
            sqlCmd.Parameters.AddWithValue("@FirstName", firstname);
            sqlCmd.Parameters.AddWithValue("@LastName", lastname);
            sqlConn.Open();
            sqlCmd.ExecuteNonQuery();
            sqlConn.Close();
        }
        public void DeleteEmployee(int empid)
        {
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("usp_DeleteEmployeeDetails", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@EmpID",empid);
            sqlConn.Open();
            sqlCmd.ExecuteNonQuery();
            sqlConn.Close();
        }

    }

I'm try to build a 3-tier arch. but I feel these code can be improvised so please review my above Data Access Layer code and give suggestions and corrections, if any, to improvise my code.


texts: Runge-Kutta 4th order using Python numexpr.evaluate()

texts:
I am implementing an ODE solver, where the user provides rates and coefficients as a string. ODE solver has to work with vectors.  The best implementation I got so far is the following:

# k_1 = dt*dcdt(C0, dt);
# k_2 = dt*dcdt(C0+0.5*k_1, dt);
# k_3 = dt*dcdt(C0+0.5*k_2, dt);
# k_4 = dt*dcdt(C0+k_3, dt);
# C_new = C0 + (k_1+2*k_2+2*k_3+k_4)/6;

import numpy as np
import numexpr as ne

dt = 0.1

coef = {'k': 1}
rates = {'R1': 'k*y1*y2'}
dcdt = {'y1': '-4 * R1', 'y2': '-R1'}
C0 = {'y2': np.random.rand(400), 'y1': np.random.rand(400)}

def k_loop(conc):
    rates_num = {}

    for k in rates:
        rates_num[k] = ne.evaluate(rates[k], {**coef, **conc})

    dcdt_num = {}

    for k in dcdt:
        dcdt_num[k] = ne.evaluate(dcdt[k], rates_num)

    Kn = {}

    for k in C0:
        Kn[k] = dt * dcdt_num[k]
    return Kn

def sum_k(A, B, b):
    C = {}
    for k in A:
        C[k] = A[k] + b * B[k] * dt
    return C

def result(C_0, k_1, k_2, k_3, k_4):
    C_new = {}
    for k in C_0:
        C_new[k] = C_0[k] + (k_1[k] + 2 * k_2[k] + 2 * k_3[k] + k_4[k]) / 6
    return C_new

k1 = k_loop(C0)
k2 = k_loop(sum_k(C0, k1, 0.5))
k3 = k_loop(sum_k(C0, k2, 0.5))
k4 = k_loop(sum_k(C0, k3, 1))

C_new = result(C0, k1, k2, k3, k4)

This ODE solver I am planning to use inside of the Object-oriented PDE solver. The PDE solver will provide C0 vectors. Therefore, the performance is crucial. I used numexpr.evaluate() for simplified user input of the rates. Can it be implemented in vectorized form? If you know the better implementation of the solver with such simplified input, please, let me know.

Metrics:

eval():

1000 loops, best of 3: 372 µs per loop

ne.evaluate():

1000 loops, best of 3: 377 µs per loop

@Graipher example:

1000 loops, best of 3: 452 µs per loop


texts:
In this function I'm parsing the page of the item in the online shop. Some items lack the picture, some lack price etc, so there are few if-else checks.

My questions are:

How to get rid of these ugly if-else checks?
How I can "pythonize" my code further?
Is it correct? I.e when I manipulate the variable value using previously assigned value:

name = soup.find('span',{"class":"project_name"})
if name is not None:
    name = re.sub(r'[«,»]','', name.text)

Below is my full code:

def grab_properties(url,html):
    soup = BeautifulSoup(html)
    link = soup.find('iframe', {"src":"e.smth.com"})

    if link is not None:
        link = link.get("src")
        id = re.match(".*\[(\w+)\].*", link).group(1)
        if id is not None:
            if id not in ids:
                name = soup.find('span',{"class":"project_name"})
                if name is not None:
                    name = re.sub(r'[«,»]','', name.text)
                    if (soup.find('img',{"id":"item0image"}) is not None):
                        img_url = soup.find('img',{"id":"item0image"}).get('src')
                        price = soup.find('span',{"class":"project_price"})
                        if price is not None:
                            price = price.text
                            price = re.sub(u'[руб,\., ]','', price)
                        else:
                            price =u"Call us!"
                        return [id.encode('utf8'), name.encode('utf8'), url.encode('utf8'), img_url.encode('utf8'), price.encode('utf8')]


texts: Array whose values are the product of every other integer

texts:
I was asked the following interview question over the phone:

  Given an array of integers, produce an array whose values are the
  product of every other integer excluding the current index.

  Example:

[4, 3, 2, 8] -> [3*2*8, 4*2*8, 4*3*8, 4*3*2] -> [48, 64, 96, 24]

and I gave the following answer

import java.math.BigInteger;
import java.util.Arrays;

public class ProductOfAnArray {

    public static void main(String[] args) {

        try {
            System.out.println(Arrays.toString(ProductOfAnArray
                    .calcArray(new int[] { 4, 3, 2, 8 })));
            System.out.println(Arrays.toString(ProductOfAnArray
                    .calcArray(new int[] { 4, 0, 2, 8 })));
            System.out.println(Arrays.toString(ProductOfAnArray
                    .calcArray(new int[] { 4, 0, 2, 0 })));
            System.out.println(Arrays.toString(ProductOfAnArray
                    .calcArray(new int[] {})));
            System.out
                    .println(Arrays.toString(ProductOfAnArray
                            .calcArray(new int[] { 4, 3, 2, 8, 3, 2, 4, 6, 7,
                                    3, 2, 4 })));
            System.out
                    .println(Arrays.toString(ProductOfAnArray
                            .calcArray(new int[] { 4, 3, 2, 8, 3, 2, 4, 6, 7,
                                    3, 2, 4 })));
            System.out.println(Arrays.toString(ProductOfAnArray
                    .calcArray(new int[] { 4432432, 23423423, 34234, 23423428,
                            4324243, 24232, 2342344, 64234234, 4324247,
                            4234233, 234422, 234244 })));
        } catch (Exception e) {
            // debug exception here and log.
        }
    }

    /*
     * Problem: Given an array of integers, produce an array whose values are
     * the product of every other integer excluding the current index.
     *
     * Assumptions. Input array cannot be modified. input is an integer array
     * "produce an array" - type not specified for output array
     *
     * Logic explanation:
     *
     * Assume we have array [a,b,c,d] Let multiple be multiple of each element
     * in array. Hence multiple = 0 if one of the element is 0; To produce the
     * output. Ans at i -> multiple divided by the value at i. if 2 numbers are
     * 0 then entire output will be 0 because atleast one 0 will be a multiple
     * if 1 number is 0 then every thing else will be 0 except that index whole
     * value is to be determined
     *
     */
    public static BigInteger[] calcArray(final int[] inp) throws Exception {
        if (inp == null)
            throw new Exception("input is null");

        int cnt = 0;
        BigInteger multiple = new BigInteger("1");
        boolean foundZero = false;

        for (int i : inp) {
            if (i == 0) {
                cnt++;
                foundZero = true;
                if (cnt < 2)
                    continue;
                else
                    break;
            }
            multiple = multiple.multiply(BigInteger.valueOf(i));
        }

        BigInteger ans[] = new BigInteger[inp.length];

        for (int i = 0; i < inp.length; i++) {
            if (foundZero) {
                if (cnt < 2) {
                    ans[i] = (inp[i] == 0) ? multiple : new BigInteger("0");
                } else {
                    ans[i] = new BigInteger("0");
                }
            } else {
                ans[i] = multiple.divide(BigInteger.valueOf(inp[i]));
            }
        }
        return ans;
    }

}

But I was not selected. I would like to get feedback on my answer and see what's wrong.


texts:
I tried to solve the SPOJ prime number problem below. The code produced correct results, but Time limit exceeded and also memory need around 970M which is not efficient(?)

How can I optimize this code under a time constraint of around few seconds?

  Problem

  Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!

  Input

  The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

  Output

  For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include <cmath>
#include <vector>
#include<iostream>
using namespace std;

void simplesieve(int limit, vector<int>&prime);

void segmentedsieve() {
    int T, M, K;

    cin >> T;

    for (int t = 0; t < T; t++) {
        cin >> M >> K;
        const int limit = floor(sqrt(K)) + 1;
        vector<int> prime;
        simplesieve(K, prime);

        bool *mark = new bool[K - M];
        memset(mark, true, sizeof(bool)*(K-M));

        vector<int>::iterator it;

        for (it = prime.begin(); *it<limit; it++) {

            int lolim = floor(M / (*it))*(*it);
            if (lolim < M)
                lolim = lolim + (*it);

            for (int j = lolim; j < K; j += (*it))
            {   if(j!=*it)
                mark[j - M] = false;
            }

        }

        for (int i = M; i < K; i++) {
            if (mark[i - M] == true)
                cout << i << "\n";
        }

        delete[] mark;
    }

}

void simplesieve( int limit, vector<int>&prime) {

    bool *mark=new bool[limit + 1];

    memset(mark, true, sizeof(bool)*(limit+1));
    for (int p = 2; p*p < limit; p++) {
        if (mark[p] == true) {
            for (int i = p * 2; i < limit; i += p)
                mark[i] = false;
        }
    }
    for (int p = 2; p < limit; p++) {
        if (mark[p] == true)
        {
            prime.push_back(p);

        }

    }

}

int main()
{
    int n = 100;
    segmentedsieve();
    return 0;
}


texts: Understanding my permalink service tests

texts:
I started writing unit tests cases recently. For now, I created only "perfect case" where there is no error. However, the test seems to me difficult to maintain and difficult to understand.

How can I make it better for other people to understand?

All permalink attributes are set within the service itself I'm testing (PermalinkService.java).

My test

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Configuration.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)

public class PermalinkServiceTest {

    @Autowired
    PermalinkService permalinkService;

    private static Permalink PERMALINK;
    private static Validacao VALIDATION;
    private static DBObject PECA;
    private static BasicDBObject COMMENTS;

    @BeforeClass
    public static void init(){
        PERMALINK = new Permalink();
        VALIDATION = new Validacao().setId("55534e63ccf2f879efcbd2a3");
    }

    @Test
    public void testPermalinkServiceA_createPermalinkWithoutValidation_permalinkWithAllFilesAndWithoutValidation() throws Exception {
        PERMALINK = permalinkService.createPermalink(VALIDATION.getId(), "Permalink sem validação");
        Assert.notNull(PERMALINK);
    }

    @Test
    public void testPermalinkServiceB_createPermalinkWithValidation_permalinkWithAllFilesAndValidation() throws Exception {
        PERMALINK = permalinkService.createPermalink(VALIDATION.getId(), "Permalink com validação");
        PECA = (DBObject) JSON.parse(PERMALINK.getPecas().get(0).toString());
        Assert.notNull(PERMALINK);
    }

    @Test
    public void testPermalinkServiceB_getAllPermalinks_getAllPermalinks() throws Exception {
        Assert.notNull(permalinkService.getPermalinks(VALIDATION.getId()));
    }

    @Test
    public void testPermalinkServiceC_getPermalink_getPermalink() throws Exception {
        Assert.notNull(permalinkService.getPermalinks(VALIDATION.getId(), PERMALINK.getId()));
    }

    @Test
    public void testPermalinkServiceD_setStatus_setNokStatus() throws Exception {
        String status = "nok";
        String email = "daniela.morais@sofist.com.br";
        permalinkService.setStatus(VALIDATION.getId(), PERMALINK.getId(),
                String.valueOf(PECA.get("id")), status, email);
    }

    @Test
    public void testPermalinkServiceE_addComment_addComment() throws Exception {
        String comment = "comentario teste";
        String email = "daniela.morais@sofist.com.br";
        PERMALINK = permalinkService.addComment(VALIDATION.getId(), PERMALINK.getId(), String.valueOf(PECA.get("id")),
                comment, email);
        DBObject pecas = (DBObject) JSON.parse(PERMALINK.getPecas().toString());
        DBObject peca = (DBObject) JSON.parse(pecas.get("0").toString());
        DBObject comentarios = (DBObject) JSON.parse(peca.get("comentarios").toString());
        COMMENTS = (BasicDBObject) JSON.parse(comentarios.get("0").toString());
        Assert.notNull(PERMALINK);
    }

    @Test
    public void testPermalinkServiceF_removeComment_removeComment() throws Exception {
        permalinkService.removeComment(VALIDATION.getId(), String.valueOf(COMMENTS.get("id")), PERMALINK.getId(), "");
    }

    @AfterClass
    public static void testPermalinkService_removeFromMongo_removeFromMongo() throws Exception {
        MongoCollection mongoCollection = DBSingleton.getJongo().getCollection("validacao_permalinks");
        mongoCollection.remove("{ _id : #}", PERMALINK.getId());
    }
}


texts:
I'm working on making a shortcut... manager, if you will. It will be reused throughout the rest of the application for registering types that can later be resolved into views. I have a rule that the shortcuts need to be able to be grouped by their different purposes throughout the application. For instance, if I have shortcuts for car related stuff and then shortcuts for truck related stuff I would need them sorted.

This is what I have come up thus far. Thoughts, comments, and suggestions on changing this to make it better would be appreciated.

public static Shortcuts
{
    public enum ShortcutType
    {
        Car, Truck
    }

    static Shortcuts
    {
        AllShortcuts = new Dictionary<string, Type>();
        CarShortcuts = new Dictionary<string, Type>();
        TruckShortcuts = new Dictionary<string, Type>();
    }

    public static Dictionary<string, Type> AllShortcuts { get; private set; }
    public static Dictionary<string, Type> CarShortcuts { get; private set; }
    public static Dictionary<string, Type> TruckShortcuts { get; private set; }

    public static void AddShortcut(KeyValuePair<string, Type> kvp, ShortcutType type)
    {
        switch(type)
        {
            case ShortcutType.Car:
                CarShortcuts.Add(kvp.Key, kvp.Value);
                break;
            case ShortcutType.Truck:
                TruckShortcuts.Add(kvp.Key, kvp.Value);
                break;
        }

        if (!AllShortcuts.Contains(kvp))
        {
            AllShortcuts.Add(kvp.Key, kvp.Value);
        }
    }

    public static void RemoveShortcut(KeyValuePair<string, Type> kvp, ShortcutType type)
    {
        switch(type)
        {
            case ShortcutType.Car:
                if (CarShortcuts.Contains(kvp))
                {
                    CarShortcuts.Remove(kvp.Key);
                }
                break;
            case ShortcutType.Truck:
                if (TruckShortcuts.Contains(kvp))
                {
                    TruckShortcuts.Remove(kvp.Key);
                }
                break;
        }

        if (AllShortcuts.Contains(kvp))
        {
            AllShortcuts.Remove(kvp.Key);
        }
    }
}


texts: Recursion: Count from x until n and backwards

texts:
I wrote this recursive function to print a number sequence from x to n and n to x back.

Here is one of the ideas I had to improve it, but it didn't work out (use another ternary operator at the end of the first one):

return x < n ? printNumberSequence(x + 1, n) : n = 0  x > n
       && x != n ? printNumberSequence(x - 1, n) : n;

However, I do have a working solution below:

#include <iostream>
using namespace std;

int printNumberSequence(int x, int n)
{ //counts from x until n
    cout << x << endl;
    x < n ? printNumberSequence(x + 1, n) : n = 0 ;
    return x > n  && x != n ? printNumberSequence(x - 1, n) : n;
}

int main()
{
    return printNumberSequence(0, 5);
}

I want to know if this way to solve the problem is good and how could I improve that code.


texts: Is this the right way to read every line?

texts:
I am never to sure when it comes to ifstream and reading lines. I am often confused with the good(), bad(), eof() and so on.

Could anyone tell me if I am doing it right?

int parseLine(std::ifstream & _file)
{

  while( std::getline( _file, line, '\n' ).good() && !_file.eof() )
  {
     // some treatment
  }

  return 0;
}


texts:
I'm a little rusty in Java, but I'm using it to get ready for interviews.  Here's the problem description from HackerRank:

  Problem Statement

  Suppose you have a string \$S\$ which has length \$N\$ and is indexed from \$0\$
  to \$N−1\$. String \$R\$ is the reverse of the string \$S\$. The string \$S\$ is funny
  if the condition \$|S_i−S_{i−1}|=|R_i−R_{i−1}|\$ is true for every \$i\$ from 1 to
  \$N−1\$.

  (Note: Given a string str, stri denotes the ascii value of the ith
  character (0-indexed) of str. |x| denotes the absolute value of an
  integer x)

  Input Format

  First line of the input will contain an integer T. T testcases follow.
  Each of the next T lines contains one string S.

  Constraints

  \$1 \le T \le 10\$
  \$2 \le\$ length of S \$\le 10000\$

  Output Format

  For each string, print Funny or Not Funny in separate lines.

This passing solution took me about 20 minutes, so that might be a bit long given the difficulty of the problem.  I'm open to critiques on my speed too.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    private static boolean isFunny (String s)
    {
        String rev = reverse(s);
        boolean stillEq = true;
        for (int i = 2; i < s.length() && stillEq; ++i)
        {
            int comp = (int)s.charAt(i) - (int)s.charAt(i-1);
            int comp2 = (int)rev.charAt(i) - (int)rev.charAt(i-1);
            stillEq = Math.abs(comp) == Math.abs(comp2);
        }

        if (stillEq)
            return true;
        else
            return false;
    }

    private static String reverse (String s)
    {
        if (s.length() > 0)
            return s.charAt(s.length()-1) + reverse(s.substring(0, s.length()-1));
        else
            return "";
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int tests = sc.nextInt();
        for (int i = 0; i < tests; ++i)
        {
            String out = isFunny(sc.next()) ? "Funny" : "Not Funny";
            System.out.println( out );
        }
    }


texts: Find the highest product between elements in a set

texts:
I'm solving a programming challenge that essentially consists of finding the highest product of elements in a set.

This is my current solution, and is passing all the test cases but one. The test case that is failing is not available to me, so I kinda have to guess what is wrong with my code.

public static String solution(int[] xs) {
    if (xs.length == 1) {
        return Integer.toString(xs[0]);
    }

    Arrays.sort(xs);

    BigInteger productOfPositiveIntegers = BigInteger.ONE;
    BigInteger productOfNegativeIntegers = BigInteger.ONE;
    Vector<BigInteger> negativeIntegers = new Vector<>();
    BigInteger result;

    boolean areAllElementsZero = true;

    for (int element : xs) {
        if (element > 0) {
            productOfPositiveIntegers = productOfPositiveIntegers.multiply(new BigInteger(Integer.toString(element)));
            areAllElementsZero = false;
        } else if (element < 0) {
            negativeIntegers.add(new BigInteger(Integer.toString(element)));
            areAllElementsZero = false;
        }
    }

    if (areAllElementsZero) {
        return BigInteger.ZERO.toString();
    }

    if (negativeIntegers.size() % 2 == 0) {
        for (BigInteger element: negativeIntegers) {
            productOfNegativeIntegers = productOfNegativeIntegers.multiply(element);
        }
    } else {
        negativeIntegers.remove(negativeIntegers.size() - 1);
        for (BigInteger element: negativeIntegers) {
            productOfNegativeIntegers = productOfNegativeIntegers.multiply(element);
        }
    }

    if (productOfNegativeIntegers.compareTo(BigInteger.ZERO) == 1) {
        result = productOfPositiveIntegers.multiply(productOfNegativeIntegers);
    } else {
        result = productOfPositiveIntegers;
    }

    return result.toString();
}

My algorithm is essentially:

sort numbers from lowest to highest.
keep track negative numbers in a separate vector.
multiply all positive numbers
If the total number of negative numbers is even, multiply them all. If not, drop the lowest negative number and multiply all the negative ones.
If the product of all the negative numbers is bigger than zero, multiply the product of negative numbers with the product of all positive numbers.
Return solution.

These are the test cases that I'm passing to my method:

    int[] testCase = {2, 0, 2, 2, 0}; // should return "8"
    int[] testCase2 = {-2, -3, 4, -5}; // should return "60"
    int[] testCase3 = {2, -3, 1, 0, -5}; // should return "30"
    int[] testCase4 = {-4, -10, -2, -1, -5}; // should return "400"
    int[] testCase5 = {1, 2, 3, 4};
    int[] testCase6 = {0, 0, 0}; // should return "0"
    int[] testCase7 = {-1}; // should return "-1"
    int[] testCase8 = {-1, -1, -1}; // should return "1"

For example the first test case, should return 8 because the highest product would be:

2 * 2 * 2 = 8

Second test case is 60 because:

-4 * -5 * 4 = 60

Last test case is 1 because:

-1 * -1 = 1

My assumption is that my code is taking too long to run for the test case that is failing.

According to the challenge, the highest possible number is 1000, and the highest number of elements in the set would be 50, so the biggest product would be 1E150 When I pass that test case to my program, it runs in less than a second.

So my question is two parts really:

What can I do to speed this up? I'm casting integers to BigIntegers in a loop, so that hurts just to look at it. But I kinda need to do that anyways.
If performance is not the problem, and I'm missing one edge case, which one is it?

Also, if this is not a good question for this community please let me know and I'll be more than happy to remove the question.