texts: Optimising and error handling Linq query

texts:
I have 2 tables as below:

Downtime

DowntimeCode

I am then doing this to get the Description field from the DowntimeCode table for the DowntimeCode with the sum highest value in the Downtime table for the current date and a specified line:

public string TopCodeForToday(string line)
    {
        var date = DateTime.Now;

        using (var db = new PillowContext())
        {
            var qry = (from d in db.DownTimes
                        where DbFunctions.TruncateTime(d.DateTime) == DbFunctions.TruncateTime(date) && d.Line == line
                        group d by new { d.Code }
                            into g
                            let total = g.Sum(x=>x.Amount)
                            orderby total descending
                            select new { g.Key.Code, Total = total }).ToList();

            for (int i = 0; i <= 1; i++)
            {
                foreach (var item in qry)
                {
                    int x = item.Code;
                    var result = from r in db.DownTimeCodes
                        where r.Code == x
                        select r.Description;

                    return result.FirstOrDefault();
                }
            }
        }
        return "Fail";
    }

Now this is working OK but I can't help but think there is a simpler way of doing it. I'm also not too hot on error handling (hence there not being any). Can anyone make any recommendations on how to improve and streamline the above?


texts:
Here is the premise:

  Three women robbed a gentleman of a vase, containing 24 ounces of
  balsam. Whilst running away they met a glass-seller, of whom they
  purchased three vessels. On reaching a place of safety they wished to
  divide the booty, but found that their vessels contained 5, 11, and 13
  ounces respectively. How could they divide the balsam into equal
  portions?

  Basically you have to get the Vase = 8, Vessel2 =8, and Vessel3 = 8.

  But it has to be in this format:

Pour 1 2

Show

Pour 1 3

Show

Pour 2 4

Show

Pour 4 1

Show

...

"Show" means display the contents of the jars
"Pour 1 2" means pour as much of the contents of container 1 into container 2 as possible

The pour function should protect itself from bad commands:

Pour 1 1
Pour 0 3
Pour 1 5 // where there are only 4 jars

I finished the program but I was wondering if anyone thinks I could improve the performance or formatting, and how. In particular, the protection in the range because it kinda seems like it messes with the flow since the user no longer enters pour. They just enter the source and destination, and if they decide to enter the pour source destination, the while loop goes into space.

#include <iostream>
#include <string>
#include <cassert>
using namespace std;

const int VASE = 0;
const int VESSEL1 = 1;
const int VESSEL2 = 2;
const int VESSEL3 = 3;

const int capacity[] = { 24, 5, 11, 13 };
const string names[] = { "VASE", "VESSEL 1", "VESSEL 2", "VESSEL 3" };
int volume[] = { 24, 0, 0, 0 };

void display(int count);
void pour(int source, int destination);
bool isEmpty(int container);
bool isFull(int container);

int main()
{
int count = 0;

cout << "----------The commands available are pour from source to destination or show the contents of all the jars.-----------" << endl;
cout << "\nFOR EXAMPLE:" << endl;
cout << "'Pour 1 2' means pour as much of the contents of container 1 into container 2 as possible." << endl;
cout << "'Show' means display the contents of the jars." << endl;

cout << "The starting contents of the jars are ";
display(count);

do
{
    int source, destination;
    string command;
    cout << "\nPLEASE ENTER COMMAND NUMBER " << count + 1<< endl;
    cin >> command;
    cin.ignore();

    if (command == "Pour" || command == "pour" || command == "POUR")
    {
        cin >> source >> destination;
        pour(source, destination);
    }
    else if (command == "Show" || command == "show" || command == "SHOW")
        display(count);
    else
        cerr << "YOU HAVE NOT ENTERED A VALID COMMAND." << endl;

    count++;
} while ((volume[VASE] != volume[VESSEL2]) || (volume[VESSEL2] != volume[VESSEL3]));
system("pause");
return 0;
}

void pour(int source, int destination)
{
    while (source < VASE || source >VESSEL3 || destination < VASE ||                  destination > VESSEL3)
{
    cerr << "You have enterered a wrong source or a wrong destination." << endl;
    cout << "Please note that the range of both source and destination is from 0-3." << endl;
    cout << "Please enter source and destination now i.e for example (1 3) " << endl;
    cin >> source >> destination;
}
while (!isEmpty(source) && !isFull(destination))
{
    volume[source]--;
    volume[destination]++;
}
}
 bool isEmpty(int container)
 {
     return volume[container] == 0;
 }
 bool isFull(int container)
 {
    return volume[container] == capacity[container];
 }

void display(int count)
{
    cout << ": ";
    for (int index = VASE; index <= VESSEL3; index++)
         cout << volume[index] <<  " : ";
    cout << endl;
}


texts: Typescript : Adding types to a function that takes in a string and returns a different promise based on the string

texts:
I have a function that takes in a string and based on the string hits different APIs to fetch images.
I have solved it by writing an interface and then as the return type of the function, it returns a Promise<Interface> as shown in the code below.
    interface IAnimal {
      image?: string | null
      message?: string
      status: string
    }
    const getAnimal = async (inAnimal: string): Promise<IAnimal> => {
      const isDogWord: boolean = ["dog", "Dog", "DOG"].includes(inAnimal.trim())
      const isFoxWord: boolean = ["fox", "Fox", "FOX"].includes(inAnimal.trim())
      let result: IAnimal = { image: null, status: "tofetch" };
      if(isDogWord) {
        result = await fetch("https://dog.ceo/api/breeds/image/random").then((data) => data.json());
        if(result.status === "success") {
          return {
            image: result.message,
            status: result.status
          }
        }
      }
      if(isFoxWord) {
        result = await fetch("https://randomfox.ca/floof/").then((data) => data.json());
        return {
          image: result.image,
          status: "success"
        }
      }
      return {
        image: null,
        status: "failure"
      }
    };

This solves the typescript errors but I am not happy with making the image and message optional in the Interface. I am receiving { "message": "image__link", "status": "success or failure" } from dog API and {"image": "image__link", "status": "success or failure"} from the fox API. Is what I have done the right approach or do we have a better solution.


texts:
I'm a beginner in Python and I've just finished a Rock, Paper, Scissors simulator in Python. It asks the user to enter paper, rock, or scissors and the program will generate a random number which will convert it to paper, rock or scissors. The program will then print the corresponding result. It also keeps tracks of wins/losses/ties until the user wants to stop playing then prints the prints the results back to the user.

import random as r
print("Welcome to my Rock-Paper-Scissor Game")
print("The rules are as follow:")
print("     Paper beats Rock")
print("     Rock beats Scissors")
print("     Scissors beat Paper")
print()
win=0
ties=0
loss=0
i=0
while i==0:
    while True:
        user=input("Do you pick Rock, Paper, or Scissors? ")
        if user not in ("Scissors","scissors","paper","Paper","Rock","rock"):
            print("Please enter Rock, Paper or Scissors. ")
            continue
        else:
            break
    computer=r.randint(1,3)
    if computer==1:
        computer="Paper"
    if computer==2:
        computer="Rock"
    if computer==3:
        computer="Scissors"
    if (user=="Paper" or user=="paper"):
        print("You choose paper")
        if computer=="Paper":
            print('\033[0;32m' + "It's a tie! The program also choose paper")
            ties=ties+1
        if computer=="Rock":
            print('\033[1;31m' + "You won! The program choose rock")
            win=win+1
        if computer=="Scissors":
            print('\033[1;36m' + "You lost! The program choose scissors")
            loss=loss+1

    if (user=="Rock" or user=="rock"):
        print("You choose Rock")
        if computer=="Rock":
            print('\033[0;32m' + "It's a tie! The program also choose rock")
            ties = ties + 1
        if computer=="Scissors":
            print('\033[1;31m' + "You won! The program choose scissors")
            win = win + 1
        if computer=="Paper":
            print('\33[1;36m' + "You lost! The program choose paper")
            loss = loss + 1

    if (user=="Scissors" or user=="scissors"):
        print("You choose Scissors")
        if computer=="Scissors":
            print('\033[0;32m' + "It's a tie! The program also choose scissors")
            ties = ties + 1
        if computer=="Paper":
            print('\033[1;31m' + "You won! The program choose paper")
            win = win + 1
        if computer=="Rock":
            print('\033[1;36m' + "You lost! The program choose rock")
            loss = loss + 1
    while True:
        question=input('\033[0;0m' + "Would you like to play again? ")
        if question not in ("Yes","yes","Y","y","no","No","n","N"):
            print('\033[;1m' + "Please only enter yes or no. ")
            continue
        else:
            break
    if question in ("Yes","y","Y","yes"):
        i=0
    if question in ("No","n","no","N"):
        i=1
print()
print("Your final results are as follows")
print("Number of wins:",win)
print("Number of ties:",ties)
print("Number of losses:",loss)


texts: Type for each value and naming, anonymous structs inside struct

texts:
Here is little snippet from my types.h code:

/**
 * tick_t: is used to store and manipulate with time (tick count)
 * Unsigned, at least 32bits
 * 32bit number gives us 71 minutes resolution
 * 64bit number gives us 584'942 years resolution
 * Use OMFW_TIME_ISELAPSED(targetTime, currentTime) for time comparing
 */
typedef unsigned long tick_t;

/**
 * pos_t: Signed integer which holds position
 * In most cases even 16bit number is enough
 */
typedef int pos_t;

/**
 * num_t: Floating point number used to calculate
 * Please note, if you want use fixed point or any custom
 * number, you should use operator overoading feature of C++
 * and also implement following functions for it in omfw/math.h
 */
typedef double num_t;

/**
 * step_t: Hold current step value
 * Only increased / decreased by one
 * May be signed, unsigned, floating point
 */
#ifdef OMFW_PRECOMPUTE_TABLE
typedef uint32_t step_t;
#else
typedef num_t step_t;
#endif

and here definition of struct in different file:

typedef struct {
    num_t acceleration;
    num_t speed;
    num_t pulseLength;

    int id; //index 0,1,2...
    int32_t letter; //unicode letter

    /** total resolution = motor resolution * gearbox */
    pos_t motorResolution;
    num_t gearbox;

    int pinSignal;
    int pinDirection;
    bool invertSignal;
    bool invertDirection;
} MotorSettings;

typedef struct {

    /** Motor settings */
    MotorSettings set;

    /** Maximum achievable limits
     * Computed from "in" variables */
    struct {
        num_t speed; //v-max; max steps/sec
        num_t acceleration; //a-max; Max accceleration that can be used
    } max;

    /** Position data stored here */
    struct {
        pos_t resolution;
        pos_t curPosition;
        pos_t tarPosition;

        //TODO impl - when motor lose step, increment this
        pos_t curOffset;

        dir_t curDirection;
        dir_t tarDirection;
    } pos;

    /** Calculated and changed by program
     * Used as indications to calculate realtime data */
    struct {
        num_t speed; //v = steps/sec
        num_t acceleration; //a = steps/sec.sec
    } cur;

    /** Used for Realtime caclulations and timing
     * Should not be used in other parts of program than realtime */
    struct {
        //tick count to turn off and next tick
        //cannot overflow
        tick_t timeTurnOff;
        tick_t timeNextMove;

        num_t firstDelay; //c0; depending on TIME_RESOLUTION
        num_t minimalDelay; //clast; TIME_RESOLUTION / maxSpeed

        step_t stepsToAccelerate; //nmax
        step_t currentStep; //n
    } rt;

} Motor;

I am doing one little project that I would like to publish soon, but I have few questions about naming:

Is having multiple types for each value OK in way I have them? I hope yes, I tried keep it as simple as I knew, but we are arguing with friend about that - he thinks that we should add omfw_ prefix to them and make them more general (eg. make tick_t just 64bits), but I want to make this code run fast on 16bit microcontrollers too and having 32bit timing is working good.
Do they have correct naming? I added _t prefix as uintx_t have.
Is it OK to have multiple anonymous structs inside main struct? There is lot of data in here and I want to organize them. Should I declare then as normal structs, even when I dont want to serialize them or access as single ones (except MotorSettings)?
Do the structs and variables in them have correct naming?
And last one. I am not native English speaker, so if there are any errors in text or code, I would appreciate if you let me know. Thanks


texts: Toggle Count without Continually Increasing It

texts:
Using a window.count variable to track which dialogue user is in and at one point they may skip a dialogue, so if that option is selected I want to increase the count, otherwise not.

Of course I do not want to count to increase every time they check and uncheck the field.

This is what I came up with:

var count = Math.floor(Math.random() * 10);
clickCount = 0;
countBeforeClick = count;

$("input[type='checkbox']").change(function() {
  var nextBtn = $('.nextButton').children(":first")
  clickCount++;
    // need to increase var count by one if we are skipping next page
  if (clickCount % 2 == 0) {
    count = countBeforeClick + 1;
  } else {
    count = countBeforeClick;
  }
  nextBtn.toggleClass(".dialogue-one");
  nextBtn.toggleClass(".dialogue-two");
  $('#feedback').text("Count is now: " + count);
  $('#feedback').append("
Click Count is now: " + clickCount);
});
div {margin: 1rem}

  <button class="dialogue-one">Click Me – actually don't bother</button>

    <input id="noAdditional" type="checkbox">Skip the next dialogue


texts: Server side validations and unit testing in MVP

texts:
We are following passive controller approach and when user clicks on submit, server side validations are fired. There are many other fields on the screen that needs to be validated.

I would like to get feedback about the following approach.

Is it ok to have validations in Presenter.
As there are many fields in UI, PerformServerValidations() method is getting big. Is there any way I could refactor it.
Intention behind declaring PerformServerValidations() as public and returning a IList is to be able to test it. Is it a good approach to take?

[TestMethod]
public void Presenter_PerformServerValidations_ValidateFromCustomerId_ExpectFalseForInvalidNumber()
{
    //creating presenter
    presenter.View.Stub(x=>x.FromCustomerId).Return("one two three");

    var errorCodes = presenter.PerformServerValidations();

    Assert.IsTrue(errorCodes.Contains("ERR_InvalidFromCustomerId"));
}

Presenter.cs

public void OnSubmit()
{
    var serverValidationErrors = PerformServerValidations();
    this.View.ServerErrors = serverValidationErrors ; // View.ServerErrors will loop over the list and sets validator's IsValid property to false
    if(!serverValidationErrors.Any())
    {
         BindCustomers();
    }
}

public IList<string> PerformServerValidations()
{
   var errorCodes = new List<string>();

   int parsedFromCustomerId;
   int parsedToCustomerId;

   bool isValidFromCustomerId = int.TryParse(this.View.FromCustomerId, out
parsedFromCustomerId);
   bool isValidToCustomerId = int.TryParse(this.View.ToCustomerId, out parsedToCustomerId);

   if(!string.IsNullOrWhiteSpace(this.View.FromCustomerId) && !isValidFromCustomerId)
   {
       errorCodes.Add("ERR_InvalidFromCustomerId");
   }

   if(!string.IsNullOrWhiteSpace(this.View.ToCustomerId) && !isValidToCustomerId)
   {
       errorCodes.Add("ERR_InvalidToCustomerId");
   }

   if((!string.IsNullOrWhiteSpace(this.View.FromCustomerId) && !string.IsNullOrWhiteSpace(this.View.FromCustomerId) && (isValidFromCustomerId && isValidFromCustomerId))
   {
       if(parsedFromCustomerId > parsedFromCustomerId)
       {
           errorCodes.Add("ERR_InvalidCustomerIdRange");
       }
   }

   //There are many other fields to be validated
   return errorCodes;
}


texts:
I tried(trying...) to solve the SPOJ prime number problem PRIME1 so i learned and implemented Segmented Sieve correctly but this program works in time for 10^8 but getting Time limit exceeded (TLE) for 10^9 input integer. can someone help me reduce complexity within my code please.

/*
 followed this tutorial
 https://medium.com/@agilanbtdw/prime-number-generation-in-java-using-segmented-sieve-of-eratosthenes-187af1dcd051
*/
#include <iostream>
#include <math.h>
#include <vector>
#include <fstream>
using std::cin;
using std::ifstream;
using std::vector;
using std::cout;
using std::ios_base;
int main() {
ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    //ifstream in("inp.txt");
  short int t;
  unsigned long int n ,q;
  cin >> t;
  while(t--){
  cin >>q >> n;
  vector<bool> a(n,true);
  unsigned long int m = sqrt(n);
  a[0] = false;
  a[1] = false;
  // find primes till sqrt
  for(unsigned long int i = 2 ; i <= m ; i++ ){
    if(a[i]){
      for(unsigned long int j = i*i ; j <= m ; j+=i ){
        a[j] = false;
      }
    }
  }
//  store the primes upto m
  vector<unsigned long int> primes;
  for(unsigned long int i = 2 ; i <= m ; i++ ){
      if(a[i]){ primes.push_back(i);}
  }

  unsigned long int temp;
  for (unsigned long int x : primes) {
        temp = q/x;
        temp*=x;
                // from primes arrays increment each prime with that num , set the index as false
        for(unsigned long int y = temp ; y <=n ; y+=x){
        a[y] = false;
        }
  }
// set the falsed indexes in previous primes arrays to true
  for(unsigned long int i = 0 ; i < primes.size() ;++i){
    a[primes[i]] = true;
  }
  for(unsigned long int i =q ; i <= n ; i++ ){
    if(a[i]) {cout << i << " ";}
  }
  cout << "\n";
  }
  return 0;
}

  my repl link - https://repl.it/repls/UnrulyMotherlyTransformation


texts: How can I enhance my jigsaw puzzle solver function?

texts:
I'm working on writing code which gets several pieces of an image, and reconstructs them to one whole picture.  The images are represented by matrices, and two pieces should be "glued" if the right column of one matrix is the same as the left column in the other one.

from images import *

def reconstruct_image(m):
    try:
        Matrix.load("./im1.bitmap")
    except:
        for i in range(m**2):  #first run only - turn .bmp to .bitmap
            image2bitmap("./puzzle/im"+str(i+1)+".bmp")
    pieces=[Matrix.load("./im"+str(i+1)+".bitmap") for i in range(m**2)]
    #find top left
    for candidate in pieces:
        if is_top(candidate,pieces) and is_left(candidate,pieces):
            base=[pieces.pop(pieces.index(candidate))]
            break
    #building vertical "strips"
    strips=[]
    rows,cols=base[0].dim() #all pieces of equal size
    while len(strips)<m:
        for i in range(len(pieces)):
            if base[len(base)-1][rows-1:rows,0:cols]==pieces[i][0:1,0:cols]: #base is up
                if len(strips)==0 and is_left(pieces[i], pieces): #leftmost strip
                    down=pieces.pop(i)
                    base.append(down)
                    break
                elif pieces[i][0:rows,0:1]==strips[len(strips)-1][len(base)][0:rows,cols-1:cols]: #pieces[i] fits
                    down=pieces.pop(i)
                    base.append(down)
                    break
        if len(base)==m: #base became a strip
            strips.append(base)
            for candidate in pieces: #find top piece that matches strip on the left
                if candidate[0:rows,0:1]==strips[len(strips)-1][0][0:rows,cols-1:cols] and is_top(candidate,pieces):
                    base=[pieces.pop(pieces.index(candidate))]
                    break
    return join([join(strip, "v") for strip in strips], "h")

def is_top(candidate, pieces):
    '''checks if there are no pieces above candidate'''
    rows,cols=candidate.dim() #all pieces of equal size
    for piece in pieces:
        if candidate[0:1,0:cols]==piece[rows-1:rows,0:cols]:
            return False
    return True

def is_left(candidate, pieces):
    '''checks if there are no pieces left of candidate'''
    rows,cols=candidate.dim() #all pieces of equal size
    for piece in pieces:
        if candidate[0:rows,0:1]==piece[0:rows,cols-1:cols]:
            return False
    return True

def join(mats, direction, sep=0):
    '''variation on joined from class - recieve mats as list/tuple'''
    '''deletes overlapping pixel row/col'''
    res=mats[0]
    rows,cols=res.dim()
    if direction=="v":
        for mat in mats[1:]:
            res=join_v(res, mat[1:rows,0:cols])
    else:
        for mat in mats[1:]:
            res=join_h(res, mat[0:rows,1:cols])
    return res

def join_h(mat1, mat2, sep=0):
    """ joins two matrices, side by side with given separation """
    n1,m1 = mat1.dim()
    n2,m2 = mat2.dim()
    m = m1+m2+sep
    n = max(n1,n2)
    new = Matrix(n, m, val=255)  # fill new matrix with white pixels

    new[:n1,:m1] = mat1
    new[:n2,m1+sep:m] = mat2

    return new

def join_v(mat1, mat2, sep=0):
    """ joins two matrices, one below the other with given separation """
    n1,m1 = mat1.dim()
    n2,m2 = mat2.dim()
    n = n1+n2+sep
    m = max(m1,m2)
    new = Matrix(n, m, val=255)  # fill new matrix with white pixels

    new[:n1,:m1] = mat1
    new[n1+sep:n,:m2] = mat2

    return new


texts: A quartic polynomial in four variables, for numerical integration

texts:
About half year ago, I derived a integral of a piecewise polynomial, which was a complex formula. Below is one of that formula:

Obviously, the above formula has relationship with four varibles \$u_i,\cdots u_{i+3}\$.

In the begining, I implement it in Wolfram Mathematica with the help of Compile[] technique and corresponding option like CompilationTarget -> "C". The screenshot as shown below:

Recently, I would like to rewrite it to C to achieve more higher performance.

#include <math.h>
#include <stdio.h>
//calc_A()
double calc_A(int i, const double *U) {
    double u0, u1, u2, u3;
    double res;
    u0 = U[i];
    u1 = U[i+1];
    u2 = U[i+2];
    u3 = U[i+3];
    //implementation of the explicit formula
    res = 3 * pow(u1, 4) + 3 * pow(u1, 3)*(u2 - 2 * u3) +
        pow(u1, 2)*(3 * pow(u2, 2) - 7 * u2*u3 + 3 * pow(u3, 2)) +
        u1*u2*(3 * pow(u2, 2) - 8 * u2*u3 + 4 * pow(u3, 2)) +
        pow(u2, 2)*(3 * pow(u2, 2) - 9 * u2*u3 + 8 * pow(u3, 2)) +
        pow(u0, 2)*(8 * pow(u1, 2) + 3 * pow(u2, 2) + 4 * u1*(u2 - 5 * u3) - 10 * u2*u3 +
        15 * pow(u3, 2)) - u0*(9 * pow(u1, 3) + pow(u1, 2)*(8 * u2 - 19 * u3) +
        u1*(7 * pow(u2, 2) - 22 * u2*u3 + 10 * pow(u3, 2)) +
        u2*(6 * pow(u2, 2) - 19 * u2*u3 + 20 * pow(u3, 2)));
    return res;
}

int main() {
    double U[] = { 0., 0., 0., 0., 0.2, 0.25, 0.4, 0.6, 0.8, 1., 1., 1., 1. };
    int i;
    double res;
    //calculate A[2]~A[6]
    for (i = 2; i <= 6; i++) {
        res = calc_A(i, U);
        printf("%f\n", res);
    }
    system("pause");
    return 0;
}

where, \$\mathbf U=\{u_0,\cdots,u_m\}\$

TEST

According to my experience, the code for res is inefficient, but I don't know how to deal with it by myself.


texts:
Say you have two strings: exp->aaccbb comp-> aa2bb

This example will return true as there are 2 chars between aa and bb. I have written this code snippet and am wondering if there is a better way do solve this problem and if I am missing any edge cases.

Also, what would be the fastest way to solve this problem with respect to time/place complexity? The solution is a 2 pointer approach with linear complexity. Follow up -> either side can have compressions or both at the same time.

const isNumber = (ch)=>{
  return Number(ch) == ch
}

const isExp = (exp, comp)=>{
  let i=j=0;

  while(i<exp.length && j<comp.length){
    if(comp[j] !== exp[i] && !isNumber(comp[j])){
      return false
    }
    else if(isNumber(comp[j])){

     let currentCompIdx = j;

     /*Find consexutive numbers*/
      while(isNumber(comp[currentCompIdx+1]))currentCompIdx++;

      /*Get Number from the compressed string*/
      const moveIndexBy = Number(comp.slice(j,currentCompIdx+1));
            /*set j pointer to index after the number*/
            j=currentCompIdx+1;

      /*Check if the letters after number is same*/
      if(comp[j] !== exp[i+moveIndexBy]){
        return false
      }
     i++;
     j++;

    }
    else{
      i++;
      j++;
    }
  }
  return true
}

/*Returns true as it has 2 chars between aa and cc*/
alert(isExp("aaccbb", "aa2bb"))

/*Returns true as it has 2 chars between aa and cc and 4 chars between bb and cc*/
alert(isExp("aaccbbqqqqcc", "aa2bb4cc"))

/*Returns true as it has 10 chars between aa and cc */
alert(isExp("aaccbbqqqqsacc", "aa10cc"))

/*Returns false as the exp string as only 1 char between aa and bb */
alert(isExp("aacbb", "aa2bb"))
```


texts:
I have a complicated Dagger 2 use case on Android, where I have a lot of dependencies, but some of them are really slow to construct. Like 2-3 seconds slow.

My solution was to create an RX Observable that will be provided through Dagger's injection mechanism to other components, instead of waiting for the slow component to construct on the main thread.

The app's Application object would create the Observable, and provide access to it via one public getter I place on it. Application instance is a singleton by default, so I thought I could hold the reference there.

Another Observable would be the one constructing the slow component and pushing it into the publicly-accessible stream.

My code for demonstrating that scenario:

public class Dagger2TestApplication extends Application {

    private Subject<SlowComponent> mSlowComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        // behavior subject saves the last value inside (great for singleton access)
        mSlowComponent = BehaviorSubject.create();

        // async slow component loading
        Completable
            .create(emitter -> {
                // prepare an artificial blocking delay
                final long delay = 2000L + Math.round(Math.random() * 4000d);
                final long start = System.currentTimeMillis();

                // noinspection StatementWithEmptyBody - just actively wait here
                do {} while (System.currentTimeMillis() - start < delay);

                // now create the instance
                final SlowComponent instance = DaggerSlowComponent.builder().contextModule(new ContextModule(this)).build();

                // finally send the item to all observers, finalize this stream
                mSlowComponent.onNext(instance);
                emitter.onComplete();
            })
            .subscribeOn(Schedulers.io())
            .subscribe();
    }

    public Observable<SlowComponent> getSlowComponentObservable() {
        return mSlowComponent;
    }

}

I decided to use a BehaviorSubject because it would immediately emit anything that was previously pushed into the stream, making it a holder/wrapper around my singleton dependency graph.

Basically, main main conundrum is - do you think this is the way to go for my use case? Or do you have any other ideas on how to achieve this type of behavior?


texts: Check if nullable int has value and compare value to another integer

texts:
Question might be more appropriate in StackOverflow, however I'd also like a review.

I'd like to make my code inline as I feel like this could be possible, I'm just not sure how.

int highestWeightOfParcel  = 0;
if (collo.WeightGrammes.HasValue)
{
    if (collo.WeightGrammes > highestWeightOfParcel)
    {
        highestWeightOfParcel = collo.WeightGrammes.Value;
    }
}

Could I apply the same technique as this? :

int heigth = collo.HeightMm.HasValue ? collo.HeightMm.Value < 10 ? 1 : (collo.HeightMm.Value / 10) : 0,

Is there a 'better'/simpler way of writing this?


texts:
I needed an object I can use to serialize specific operations in an otherwise parallel workflow.

The specific use case I was solving for is request idempotency; a great example would be double-clicking a "Process Payment" button on a web form. I might have 100 payment processing requests in flight (parallel process) at any given time, but if two or three come in with the same credit card info, I want to make sure I process them serially (so I can deduplicate, etc.). In that case, a suitable key value might be the credit card number.

I came up with the Keybox class below. (Serializer is so overloaded...)

public class Keybox : IKeybox
{
    private readonly HashSet<string> Keys = new HashSet<string>();

    public void Lock(string key, int timeout = 60, int tick = 100)
    {
        //timeout is specified in seconds, tick in milliseconds
        //timeout = ConvertTimeoutToTicks(timeout, tick);
        //This logic is not important for the question
        timeout = 600;

        var @event = new ManualResetEvent(false);
        var counter = 0;
        do
        {
            @event.Reset();

            if (!Keys.Contains(key))
            {
                lock (Keys)
                {
                    if (!Keys.Contains(key))
                    {
                        Keys.Add(key);
                        return;
                    }
                }
            }

            Task.Delay(TimeSpan.FromMilliseconds(tick))
                .ContinueWith(t => @event.Set());

            @event.WaitOne();
        } while (counter++ < timeout);

        throw new Exception($"Unable to process '{key}'; timeout expired.");
    }

    public void Unlock(string key)
    {
        Keys.Remove(key);
    }
}

Test code:

public void Test()
{
    var box = new Keybox();
    var key = "EFF82671-DE8F-46B9-B1F1-0FB8308052C3";

    Parallel.ForEach(
        Enumerable.Range(1, 3),
        (i) =>
        {
            box.Lock(key);
            Console.WriteLine($"{i}: Running");
            Thread.Sleep(3000);
            Console.WriteLine($"{i}: Ending");
            box.Unlock(key);
        }
    );
}

which produces output like

1: Running
1: Ending
3: Running
3: Ending
2: Running
2: Ending

The main question is: is this an implementation of a specific design pattern? And the follow-on to that question is: is there a BCL class that already offers this functionality?

I'm also interested in general code review feedback.


texts:
I have to solve an exercise from ANSI C book:

  Add the commands to print the top elements of the stack without
  popping, to duplicate it, and to swap the top two elements. Add a
  command to clear the stack.

Here is my implementation in RPN Calculator:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXOP 100
#define NUMBER '0'
#define MAXVAL 100
#define BUFSIZE 100

int getop(char []);
void push(double);
double pop(void);
double top(void);
void clear(void);
void swap(void);
void duplicate(void);

int getch(void);
void ungetch(int);

int sp = 0;
double val[MAXVAL];
char buf[BUFSIZE];
int bufp = 0;

int main(void) {
    int type;
    double op2;
    char s[MAXOP];

    while ((type = getop(s)) != EOF) {
        switch (type) {
        case NUMBER:
            push(atof(s));
            break;
        case '+':
            push(pop() + pop());
            break;
        case '*':
            push(pop() * pop());
            break;
        case '-':
            op2 = pop();
            push(pop() - op2);
            break;
        case '/':
            op2 = pop();
            if (op2 != 0.0)
                push(pop() / op2);
            else
                printf("error: zero divisor\n");
            break;
        case '%':
            op2 = pop();
            if (op2 != 0)
                push((int) pop() % (int) op2);
            else
                printf("error: zero divisor\n");
            break;
        case 'c':
            clear();
            printf("stack empty!\n");
            break;
        case 'd':
            duplicate();
            printf("duplicate element\n");
            break;
        case 's':
            swap();
            printf("swap elements\n");
            break;
        case '?':
            printf("top element on the stack: %f\n", top());
            break;
        case '\n':
            printf("\t%.8g\n", pop());
            break;
        default:
            printf("error: unknown command %s\n", s);
            break;
        }
    }
    return 0;
}

void push(double f) {
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

double pop(void) {
    if (sp > 0)
        return val[--sp];
    else {
        printf("error: stack empty\n");
        return 0.0;
    }
}

double top(void) {
    if (sp > 0)
        return val[sp - 1];
    else {
        printf("error: stack empty\n");
        return 0.0;
    }
}

void clear(void) {
    if (sp > 0) {
        while (--sp > 0);
    } else {
        printf("error: stack empty\n");
    }
}

void duplicate(void) {
    if (sp > 0) {
        int elem = val[sp - 1];
        push(elem);
    } else {
        printf("error: stack empty\n");
    }
}

void swap(void) {
    if (sp > 0 && (sp - 1) > 0) {
        int elem1 = val[sp - 1];
        int elem2 = val[sp - 2];
        val[sp - 1] = elem2;
        val[sp - 2] = elem1;
    } else {
        printf("error: stack empty\n");
    }
}

int getop(char s[]) {
    int i, c;

    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';
    if (!isdigit(c) && c != '.' && c != '-')
        return c;
    i = 0;
    if (c == '-')
        s[++i] = c = getch();
    if (isdigit(c))
        while (isdigit(s[++i] = c = getch()))
            ;
    if (c == '.')
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '\0';
    if (c != EOF)
        ungetch(c);
    return NUMBER;
}

int getch(void) {
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) {
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

What are your opinions about it? Is it proper and optimal way to implement these functions?


texts:
I am creating a simple program that will do three things: add up the prime numbers found within the range set by the user, print out the entire list of prime numbers, and print how many prime numbers were found.

# Starting number
lower = int(input("Enter lower range: "))
# Final number
upper = int(input("Enter upper range: "))
print "Running..."
# Variables to keep track of progress
total = 0
list_of_primes = []

# Loop to see whether the number is prime or not
for num in range(lower, upper + 1):
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                break
        else:
            total += num
            list_of_primes.append(num)
    if num == 2:
        total += num
        list_of_primes.append(num)

# Print out the results
print "Finished..."
print "Sum of prime numbers:", total
print "List of prime numbers:", list_of_primes
print "Number of prime numbers:", len(list_of_primes)

The time waiting can be very long, especially with large numbers (max is around 3,000,000,000). Is there any way to shorten the time needed to run the program (thus improve efficiency) and make the code more elegant and readable?

Note: Negative numbers will work. No errors will be thrown.

EDIT: I have added three more lines of code, which helps to reduce time spent by removing all even numbers immediately except 2, which actually is prime.


texts: Nsum problem: find all n elements in an array whose sum equals a given value

texts:
I am pretty new to Python, so I want to listen to any advice that improve my coding style in a "pythonic" way, even about naming style of variables. The following code reflects a very general paradigm that formulates a problem as depth-first search in a tree, which I find interesting and powerful.

Suppose arr = [3, 5, 2, 1, 1, 7, 10, 2], we want to find all n=2 elements whose sum equals val=8. The algorithm should return a list of tuples, where each tuple is INDICES of n=2 elements (at different positions of the array) whose sum is val=8: [(3,5), (4,5), (0,1)], so we have,

arr[3]+arr[5] = 1+7 = 8;
arr[4]+arr[5] = 1+7 = 8;
arr[0]+arr[1] = 3+5 = 8.

Here is my code:

def nsum(arr, n, val):
    if arr is None or len(arr) < n:
        return []

    # first sort the array by indice, so that we can search sequentially
    # with early stopping
    sorted_indice = sorted(xrange(len(arr)), key=lambda i: arr[i])
    size = len(arr)

    def nsum_recursive(arr, prev_indice, prev_sum, result):
        ''' This is the main algorithm that is a recursive function.
        Think about the problem as tree search using depth-first search,
        Each node/state is determined by (prev_indice, prev_sum), where
        prev_indice is a list of currently explored indice, whose sum is
        prev_sum. When len(prev_indice)==n, we reach a leaf node. Then we
        can check whether the sum equals val.
        '''
        # termination condition (leaf nodes)
        if len(prev_indice) == n:
            if prev_sum == val:
                result.append(tuple(sorted_indice[i] for i in prev_indice))
        else:
            current_count = len(prev_indice)
            # depth-first search
            for idx in range(
                    0 if not prev_indice else prev_indice[-1]+1,
                    size-(n-current_count-1)):
                current_sum = prev_sum + arr[sorted_indice[idx]]
                # early stopping (pruning of branches)
                if current_sum>val and idx+1<size and arr[sorted_indice[idx+1]]>=0:
                    break
                nsum_recursive(arr, prev_indice+[idx],
                               current_sum, result)

    # start DFS from the root node
    result = []
    nsum_recursive(arr, [], 0, result)
    return result


texts: Finding all factors and prime factors of a number

texts:
I am working on the Project Euler, number 3 project (finding the largest prime factor of 600851475143), but I wanted to take it a step further and write something that will list all factors and prime factors of any inputted number. I'm also using this project to learn about classes (I'm putting all my different Proj. Euler challanges in their own class). Anyway, I know my code works, but when i put in the number they wanted me to use -- 600851475143 --, it sat for over five minutes and hadn't finished yet. Is there a way to optimize my code to work more efficiently?

challangesEuler.py

class ChallangeThree:
    """Challange Three: Find the largest prime factor of 600,851,475,143

    >> Takes a number, and finds it's prime factor. From there figures out
    which is the largest"""

    def __init__(self, value):  # Defines variables
        self.val = value
        self.dividend = 2
        # self.maxfactor = math.sqrt(value)... NOT USED
        self.listdivids = []
        self.listprimes = []

    def isprime(self, val):  # Called by 'findprimes' after getting all factors
        for factor in range(2, val):
            if val % factor == 0:
                break  # If not prime, stop trying
        else:
            self.listprimes.append(val) # Add new prime to list

    def factor(self):  # Called by 'findprimes' to find all factors
        while self.val / self.dividend != 1:
            if self.val % self.dividend == 0:
                self.listdivids.append(self.dividend)
                pass
            else:
                pass
            self.dividend += 1
            continue
        self.listdivids.sort()
        return self.listdivids  # Returns list of dividends

    def findprimes(self): # The part called in execution module
        self.factor()  # Finds factors
        print(self.listdivids)  # Prints list of factors
        for dividend in self.listdivids:  # For each dividend in the list, see if it's a factor
            self.isprime(dividend)  # Runs each dividend through the code
        return self.listprimes  # Returns list of prime factors

runEuler.py

import challangesEuler as Pr

def challangethree(x):  # Creates a function to run challange three in other
    ct = Pr.ChallangeThree(x)
    return ct.findprimes()

print(challangethree(600851475143))


texts: How to write a simple script to read text from a file and compute the number of sentences, number of unique words and punctuation/symbols? (NodeJS)

texts:
I just finished a challenge (noted above) and I was wondering how good is this approach or is there some simpler solution that I am not aware of?
If you have a different solution, try to explain the code for people less experienced than myself rather just than pasting a solution.
Here is an example text file to be read from:
This file has eight words in this sentence.
There are two sentences. In this paragraph.

And two paragraphs in total.
Lorem ispsum.
Lorem ispsum.
Lorem ispsum.
Lorem ispsum.

/**
 * Write a simple script to read text from a file and compute (approximately) the number of sentences, number of unique words and punctuation/symbols.
 * Run the code with node ./problem-2.js test.txt
 */

 // Use Node's builtin api to read a file
const fs = require('fs');

//#1 count the number of words
const wordCount = (string) => string.split(" ").length;

//#2 count the number of unique words
const uniqueWords = txt => new Set(txt.toLowerCase().match(/\w+/g)).size;

//#3 count the number of paragraphs
const paragraphCount = (paragraphString) =>{
  //seperate each sentence into a seperate string
  paragraphString = paragraphString.split("\n\n");
  // console.table(paragraphString) // show as a table for better visual
  let paragraphArray = paragraphString.length; // length of paragraph array

  let paragraphCount = 0;
  let strip_whitespace = /\s+/gi;
  while (paragraphArray >=0) {
    paragraphArray--;
    let tmp = paragraphString[paragraphArray];
    tmp = tmp ? tmp .replace(strip_whitespace,"") : tmp;

    if( tmp && tmp.length > 1 ) paragraphCount++;
  }
  return paragraphCount;
}

function countPunctuations(punctuationsStrings) {
  let punctuationsCount = 0;
  const punctuations = [".", ",", "!", "?"];
  // const symbols = ["~","`","!","@","#","$","%","^","&","*","(",")","_","+","-","=","{","}","|","[","]","\",":",";","'","<",">","?","/",]
  for (const ch of punctuationsStrings) {
    if (punctuations.includes(ch)) punctuationsCount++;
  }
  return punctuationsCount;
}

fs.readFile("test-2.txt", 'utf8', function(err, data) {
  if (err) throw err;
  console.log("The text in the file:\n\n", data,"\n")
  // store results in an object to present the log better
  let result={
    "word count": wordCount(data),
    "unique words": uniqueWords(data),
    "paragraph count": paragraphCount(data),
    "punctuation count": countPunctuations(data),
  }
  console.table(result)
});
```


texts:
Here is my attempt to implement a minimum priority queue class in Python using the heapq module. I plan to use it in graph search algorithms so the values associated with each key are update-able.

Note: Any obsolete values related to an updated key are kept until they are on the top of the queue, at which time they are ignored.

from heapq import heappush, heappop, heapify

class PriorityQueueUpdateable(object):
    """
    Updateable Priority Queue implemented with heapq module and standard python dictionary
    """
    def __init__(self):
        self._heap = []
        self._dict = dict()
        heapify(self._heap)

    def _clear_heap(self):
        """
        Removes obsolete entries from heap
        """
        value, key = self._heap[0]
        while (key not in self._dict) or (self._dict[key] != value):
            heappop(self._heap)
            if not self._heap:
                break
            value, key = self._heap[0]

    def pop(self):
        if not self:
            raise IndexError("Queue is empty")

        self._clear_heap()

        value, key = heappop(self._heap)
        del self._dict[key]

        self._clear_heap()

        return key, value

    def peek(self):
        if not self:
            raise IndexError("Queue is empty")
        self._clear_heap()
        value, key = self._heap[0]
        return key, value

    def __contains__(self, key):
        return key in self._dict

    def __getitem__(self, key):
        return self._dict[key]

    def __len__(self):
        return len(self._dict)

    def __setitem__(self, key, value):
        self._dict[key] = value
        heappush(self._heap, (value, key))

The code passes this simple test

pq = PriorityQueueUpdateable()
pq[1]= 0.1
pq[1]= 2
pq[1]= 0.2
pq[2] = 6
pq[2] = 0.1
pq[2]= 0.001
assert pq[1] == 0.2
assert pq[2] == 0.001

assert 2 in pq
assert 1 in pq

assert len(pq) == 2
assert pq.pop() == (2, 0.001)
assert pq.pop() == (1, 0.2)

I would appreciate any feedback on improving my code. Thanks.


texts: Variable declaration outside or inside when using on of the methods of Array.prototype

texts:
The purpose of this script is to enforce some rules for validating a keyboard shortcuts definition. In my case I want to reject duplicates keys improperly added in the combo properties. This code rejects key combinations like CtrlAltPPwhich are not valid.

I would like to know what are the best practices regarding variable declaration placement (in/out) when method like Array.prototype.forEach are used.

Which version of the code would you suggest as better? Also, for my understanding in the first snippet, variables declared inside the function in .forEach are hoisted to that function and not to the check() function, is my assumption correct?

window.app = {
    combos: {
        a: 'Ctrl-Alt-P',
        b: 'Ctrl-Ctrl-Alt-P', // invalid
        c: 'Ctrl-Alt-P-P'// invalid
    },
    check: function () {
        var result = true,
            combos = Object.keys(this.combos).forEach(function (combo) {
                var comboWin = this.combos[combo],
                    parts = comboWin.split('-').sort(),
                    item,
                    itemNext;
                for (var i = 0, len = parts.length; i < len; i++) {
                    item = parts[i];
                    itemNext = parts[i + 1];
                    if (item === itemNext) {
                        result = false;
                        alert('DUPLICATED PART IN: '+ comboWin + ' : ' + item);
                    }
                }
            }.bind(this));
        return result;
    }
}

window.app.check();

 window.app = {
        combos: {
            a: 'Ctrl-Alt-P',
            b: 'Ctrl-Ctrl-Alt-P', // invalid
            c: 'Ctrl-Alt-P-P'// invalid
        },
        check: function () {
            var result = true,
                comboWin,
                parts,
                item,
                itemNext;
            combos = Object.keys(this.combos).forEach(function (combo) {
                comboWin = this.combos[combo],
                parts = comboWin.split('-').sort(),
                item,
                itemNext;
                for (var i = 0, len = parts.length; i < len; i++) {
                    item = parts[i];
                    itemNext = parts[i + 1];
                    if (item === itemNext) {
                        result = false;
                        alert('DUPLICATED PART IN: ' + comboWin + ' : ' + item);
                    }
                }
            }.bind(this));
            return result;
        }
    }

    window.app.check();


texts: function swap 2 nodes in doubly linked list

texts:
Helo everyone, I need to review on function swapNode in doubly linked list. It works but I want to make it clearer and better. Are there any errors like memory leak in my code?

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

struct node;
struct list;

typedef struct node node;
typedef struct list list;

struct node
{
    int point;
    char name[30];
    node *next;
    node *prev;
};

struct list
{
    node *head;
    node *tail;
    int count;
};

node *createNewNode(int point, char name[30], node *prev, node *next);
list *createList();
void insertHead(list *listNode, int point, char name[30]);
bool compareName(char a[30], char b[30]);
void swapNode(list *listNode, char nameA[30], char nameB[30]);

int main()
{
    list *listNode = createList();

    insertHead(listNode, 10, "abc def");
    insertHead(listNode, 9, "qwe rty");
    insertHead(listNode, 8, "ui op");
    insertHead(listNode, 30, "fgh jkl");
    insertHead(listNode, 1234, "akaka");

    swapNode(listNode, "fgh jkl", "akaka");

    node *temp = listNode->head;
    while (temp != NULL)
    {
        printf("%-20s%d\n", temp->name, temp->point);
        temp = temp->next;
    }

    return 0;
}

node *createNewNode(int point, char name[30], node *prev, node *next)
{
    node *newNode = (node *)malloc(sizeof(node));
    newNode->point = point;
    strcpy(newNode->name, name);
    newNode->next = next;
    newNode->prev = prev;
    return newNode;
}

list *createList()
{
    list *listNode = (list *)malloc(sizeof(list));
    listNode->count = 0;
    listNode->head = NULL;
    listNode->tail = NULL;
    return listNode;
}

void insertHead(list *listNode, int point, char name[30])
{
    node *newNode = allocateNewNode(point, name, NULL, listNode->head);
    if (listNode->head)
        listNode->head->prev = newNode;
    listNode->head = newNode;
    if (listNode->tail == NULL)
        listNode->tail = newNode;
    ++listNode->count;
}

bool compareName(char a[30], char b[30])
{
    for (int i = 0; i < 31; i++)
    {
        if (a[i] != b[i])
            return false;
        if (a[i] == '\0')
            break;
    }

    return true;
}

void swapNode(list *listNode, char nameA[30], char nameB[30])
{
    node *A = NULL, *B = NULL;
    node *temp = listNode->head;

    for (int i = 0; i < listNode->count; i++)
    {
        if (compareName(temp->name, nameA))
            A = temp;
        else if (compareName(temp->name, nameB))
            B = temp;
        temp = temp->next;
        if (A && B)
            break;
    }
    if (!A || !B)
        return false;
    else if (A == B)
        return false;

    node p=*A;
    *A=*B;
    *B=p;

    B->next = A->next;
    B->prev = A->prev;

    A->next = p.next;
    A->prev = p.prev;
}


texts: Follow Up post: Proper handling of exceptions in MVP

texts:
This is a follow up post of my early question "Proper handling of exceptions in MVP"

So based on the answers I re edited the post and now my exception handling code looks like this...

DAL

    public bool InsertAccount(IBankAccount ba)
    {
string insertStatement = @"IF NOT EXISTS (SELECT ac_no FROM BankAccount WHERE ac_no=@ac_no) BEGIN INSERT INTO BankAccount (ac_no, emp_id, ac_name, bank_name, ac_type," +
                                  "ent_date, ent_by, remarks, file_no, status) VALUES (@ac_no, @emp_id, @ac_name, @bank_name, @ac_type, @ent_date, @ent_by, @remarks, @file_no, @status) END";

        using (SqlConnection sqlConnection = new SqlConnection(db.ConnectionString))
        {
            using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
            {
                try
                {
                    sqlConnection.Open();
                    sqlCommand.Parameters.Add("@ac_no", SqlDbType.Char).Value = ba.AccountNumber;
                    sqlCommand.Parameters.Add("@emp_id", SqlDbType.Int).Value = ba.EmployeeID;
                    sqlCommand.Parameters.Add("@ac_name", SqlDbType.VarChar).Value = ba.AccountName;
                    sqlCommand.Parameters.Add("@bank_name", SqlDbType.VarChar).Value = ba.BankName;
                    sqlCommand.Parameters.Add("@ac_type", SqlDbType.VarChar).Value = ba.AccountType;
                    sqlCommand.Parameters.Add("@ent_date", SqlDbType.DateTime).Value = ba.EnteredDate;
                    sqlCommand.Parameters.Add("@ent_by", SqlDbType.VarChar).Value = "ABCD";
                    sqlCommand.Parameters.Add("@remarks", SqlDbType.VarChar).Value = ba.Remarks;
                    sqlCommand.Parameters.Add("@file_no", SqlDbType.Int).Value = ba.FileNo;
                    sqlCommand.Parameters.Add("@status", SqlDbType.Bit).Value = ba.Active;

                    sqlCommand.ExecuteNonQuery();
                    return true;
                }
        catch (SqlException)
        {
            throw new Exception("DataBase related Exception occurred");
        }
        catch (Exception)
        {
            throw new Exception("Exception occurred");
        }
    }

BankAccountPresenter

    private void SaveBankAccount()
    {
        try
        {
           _DataService.InsertAccount(_model);
        }
        catch (Exception e) { MessagingService.ShowErrorMessage(e.Message); }
    }

Why I've caught exceptions in DAL is that even at the moment I'm not logging errors, I may have to do it in future.

And also this way I can differentiate the error massages in DAL, whether it's sql related or general.

I've used messaging service in my presenter when showing error messages.

Does this meaning full? Can this be simplified?


texts: Validating a credit card number using Luhn's algorithm

texts:
I implemented Luhn's algorithm explained on Wikipedia to validate a credit card number, in Bash.

Does this code follow good practices?

#!/bin/bash
getchecknumber(){ # get the last digit of the cc number
    str=$1
    checknum=$(echo ${str: -1})
}
getrest(){ # get the rest of the numbers in the sequence
    str=$(echo ${str%?})
}
doubleeveryother(){ # double every other number
    # split characters into an array
    arr=()
    i=0
    while [ "$i" -lt "${#str}" ]; do
        arr+=(${str:$i:1})
        i=$((i+1))
    done
    for ((i=1; i<=15; i++))
    do  {
        char=$(echo "$i-1" | bc)
        double=$(echo "${arr[$char]} * 2" | bc)
        if [ $(($i%2)) -eq 0 ] ; then foo=bar; else arr[$char]=$double #replace the number in the array
        fi
    }
    done
    echo -e
}
adddigitsum() { #split a two digit number into two numbers and add them
    for ((a=0; a<=14; a++))
    do {

        NUMSPLIT=()
        number=$(echo ${arr[$a]})
        if [[ ${#number} == 2 ]] ; then
            i=0
            while [[ "$i" -lt ${#number} ]]; do
                NUMSPLIT+=(${number:$i:1})
                i=$((i+1))
                done
            num=$((${NUMSPLIT[0]} + ${NUMSPLIT[1]}))
            addeddigit=$( echo $num | bc )
            arr[$a]=$addeddigit # replace the number in the array
        fi
    }
    done
}
addall(){ #add all the digits
    sum=$( IFS="+"; bc <<< "${arr[*]}" )
}
multiply(){ #multiply by 9
    result=$( echo "$sum * 9" | bc )
}
validate(){ #see if the last number of 'result' is equal to the checknum
    resultchecknum=$(echo ${result: -1})
    if [[ $resultchecknum == $checknum ]] ; then echo "CC Number is valid!" ; else echo "CC Number is not valid."
    fi
}
echo "$1 "
getchecknumber $1
getrest
doubleeveryother
adddigitsum
addall
multiply
validate


texts: Convert .NET DateTime to a string using ordinals

texts:
With a DateTime object, it's easy to get, for example, 11 October 2011 by using:

d.ToString("d MMMM yyyy");

However, there seems to be no built-in method to get the output 11th October 2011.

So here's a possible extension method.

public string ToStringWithOrdinal(this DateTime d) {
  var sb = new StringBuilder(d.Day);
  switch (d.Day) {
    case 1:
    case 21:
    case 31:
      sb.Append("st");
      break;
    case 2:
    case 22:
      sb.Append("nd");
      break;
    case 3:
    case 23:
      sb.Append("rd");
      break;
    default:
      sb.Append("th");
      break;
  }
  sb.Append(" ").Append(d.ToString("MMMM yyyy"));
  return sb.ToString();
}

Can anyone think of any improvements, either to performance or to add functionality for a format parameter, so we can call e.g. d.ToStringWithOrdinal("d^ MMMM");?

Thanks.


texts:
I was given a homework assignment to code a console Guess the Number Game, where the user should guess a random number. Also, I had to code a simple menu with switch where I can change a random number origin/bound and attempts amount.

Please, give me some tips how could I improve the code and where I'm wrong.

P.S. I must not use classes / methods etc. Only Control Flow Statements.

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static void main(String[] args) {
        var scanner = new Scanner(System.in);
        var origin = 0;
        var bound = 100;
        var attempts = 10;

        System.out.println("Guess the Number Game!");

        while (true) {
            System.out.println();
            System.out.println("1. Start new game.");
            System.out.println("2. Change origin (" + origin + ").");
            System.out.println("3. Change bound (" + bound + ").");
            System.out.println("4. Change attempts amount (" + attempts + ").");
            System.out.println("5. Quit.");
            System.out.println();

            switch (Integer.parseInt(scanner.nextLine())) {
                case 1:
                    var number = ThreadLocalRandom.current().nextInt(origin, bound);
                    var currentAttempts = attempts;
                    System.out.println("Guess the number between " + origin + " and " + bound + "!");
                    while (currentAttempts > 0) {
                        System.out.println(currentAttempts-- + " attempts left:");
                        var input = Integer.parseInt(scanner.nextLine());
                        if (input == number)
                            break;
                        else
                            System.out.println("The number is " + (input < number ? "greater" : "less") + " than yours.");
                    }
                    if (currentAttempts > 0)
                        System.out.println("You win! Congratulations!");
                    else {
                        System.out.println("You loose! Better luck next time!");
                        System.out.println("The number was " + number);
                    }
                    break;
                case 2:
                    while (true) {
                        System.out.println("Enter new origin:");
                        int newOrigin = Integer.parseInt(scanner.nextLine());
                        if (newOrigin < bound) {
                            origin = newOrigin;
                            break;
                        } else
                            System.out.println("Origin should be less than bound. Try again.");
                    }
                    break;
                case 3:
                    while (true) {
                        System.out.println("Enter new bound:");
                        int newBound = Integer.parseInt(scanner.nextLine());
                        if (newBound > origin) {
                            bound = newBound;
                            break;
                        } else
                            System.out.println("Bound should be greater than origin. Try again.");
                    }
                    break;
                case 4:
                    while (true) {
                        System.out.println("Enter new attempts amount:");
                        int newAttempts = Integer.parseInt(scanner.nextLine());
                        if (newAttempts > 0) {
                            attempts = newAttempts;
                            break;
                        } else
                            System.out.println("Attempts amount should be greater than 0. Try again.");
                    }
                    break;
                case 5:
                    System.out.println("Bye!");
                    return;
            }
        }
    }
}


texts:
Recently, I've asked in a code review if my code was causing any pointer related issues. They mentioned that I had problems with my dispose method. Basically, I'm disposing textures from a texture map, by cleaning the texture at the ID given to the method. So I would like to ask you if now, I'm disposing correctly my texture, and if there's a better way to do it.

void TextureManager::freeTexture(std::string id){

    std::map<std::string, SDL_Texture*>::iterator it = m_textureMap.find(id);

    std::cout << "Disposing texture : [ID==" << id << "] [MemoryAdress==" << it->second << "] : \n";

    if (it == m_textureMap.end())
    {
        LOGERROR("ERROR : Invalid ID : cannot dispose texture");
        return;
    }

    SDL_DestroyTexture(it->second);
    std::cout << "--> Destroyed !";

    m_textureMap.erase(id);
    std::cout << " --> Erased from TextureMap !\n\n";
}


texts:
I'm rewriting an old Swing project that I did a few months ago, a fairly simple copy-cat of MS paint. I've been doing a pretty good job of keeping the code maintainable and organized, but I've hit a wall on one class. All I need is some general tips on organization on this one class.

The way I have my program set up is that each component of my painting program (buttons for colors, eraser button, JPanel to paint on) is actually a relative (extended from) of another swing component class (for instance PaintPanel, the panel you paint on, extends JPanel, or colorButton is an extension of JButton). This just allows me to keep things encapsulated and organized.

So, I needed a JFileMenu for the top of the program in order to save, open files, edit, etc. I created a new Class called PaintMenuBar, extended it from JMenuBar, and started creating the JMenus and JMenuItems. Now, each JMenuItem obviously needs an ActionListener, so I just gave each one a different ActionListener. I'm skeptical about this because I know it can be kind of disorganized looking.

Basically, I just want somebody to let me know if this practice is all right, or if there is a better alternative that doesn't involve me making 20 new classes.

Here's the entire class:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class PaintMenuBar extends JMenuBar
{
    private static final long serialVersionUID = 1L;

    JMenu fileMenu;
    JMenu editMenu;
    JMenu aboutMenu;

    public PaintMenuBar()
    {
        setUpFileMenu();
        setUpEditMenu();
        setUpAboutMenu();
    }

    // Set up menu items & such

    private void setUpFileMenu()
    {
        fileMenu = new JMenu("File");

        // File menu items
        JMenuItem newMenuItem = new JMenuItem("New");
        newMenuItem.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {

            }
        });

        JMenuItem openMenuItem = new JMenuItem("Open");
        openMenuItem.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {

            }
        });

        JMenuItem saveMenuItem = new JMenuItem("Save");
        saveMenuItem.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {

            }
        });

        JMenuItem saveAsMenuItem = new JMenuItem("Save As");
        saveAsMenuItem.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {

            }
        });

        JMenuItem printMenuItem = new JMenuItem("Print");
        printMenuItem.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {

            }
        });

        add(fileMenu);
    }

    private void setUpEditMenu() // Create Edit Menu
    {
        editMenu = new JMenu("Edit");
    }

    private void setUpAboutMenu() // Create About Menu
    {
        aboutMenu = new JMenu("About Paint 2.0");
    }
}

I am aware of some of the junk that is in this class that I still need to clean up, but just try and ignore it.


texts:
This quick code I made is meant to be an easy-to-use, multi-purpose calculator. When I say "multi-purpose", then I mean that this calculator can do some more interesting functions like rounding numbers to the nearest one (which isn't that interesting, honestly). I was hoping to get some feedback or review on how my coding structure and methods could be improved.

Here is the code "in action".

function start(){
var type = readLine("What type of calculation would you like to do?");

if(type == "multiplication"){
    var mFirstNum = readInt("What is the first number you want to multiply?");
    var mSecondNum = readInt("What is the second number you want to multiply?");
    var product = (mFirstNum * mSecondNum);
    println("The product is " + product);

}else if(type == "addition"){
    var aFirstNum = readInt("What is the first number you want to add?");
    var aSecondNum = readInt("What is the second number you want to add?");
    var sum = (aFirstNum + aSecondNum);
    println("The sum is " + sum);

}else if(type == "subtraction"){
    var sFirstNum = readInt("What is the first number you want to subtract?");
    var sSecondNum = readInt("What is the second number you want to subtract?");
    var difference = (sFirstNum - sSecondNum);
    println("The difference is " + difference);

}else if(type == "division"){
    var dFirstNum = readInt("What is the first number you want to divide?");
    var dSecondNum = readInt("What is the second number you want to divide?");
    var quotient = (dFirstNum / dSecondNum);
    println("The quotient is " + quotient);

}else if(type == "square root"){
    var sqFirstNum = readInt("What is the number you would like to find the square root of?");
    var sqRoot = Math.sqrt(sqFirstNum);
    println(sqRoot);

}else if(type == "round"){
    var roundFirstNum = readFloat("What is the decimal you want to round?");
    var roundedNum = Math.round(roundFirstNum);
    println(roundedNum);

}else if(type == "max number"){
    var numO = readInt("What is the first number you want to compare?");
    var numT = readInt("What is the second number you want to compare?");

    var final = max(numO, numT);
    println("The bigger number is " + final);

}else if(type == null){
    println("Goodbye.");

}else{
    println("That is not a valid calculation.");
}
}
function max(x, y){
    if(x > y){
        max = x;
    }else{
        max = y;
    }
    return max;
}


texts: Get all followers and friends of a Twitter user

texts:
I'm trying to find my bug or any potential bottleneck that cause my program to be really slow. The script is to get all the followers and friends and save that in MongoDB.

import pymongo
import tweepy

consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''

from pymongo import MongoClient
client = MongoClient()

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, retry_count=3, retry_delay=60)

db = client.tweets

raw_tweets = db.raw_tweets
users = db.users

def is_user_in_db(user_id):
    return get_user_from_db(user_id) != None

def get_user_from_db(user_id):
    return users.find_one({'user.id' : user_id})

def get_user_from_twitter(user_id):
    return api.get_user(user_id)

def get_followers(user_id):
    users = []
    page_count = 0
    for user in tweepy.Cursor(api.followers, id=user_id, count=200).pages():
        page_count += 1
        print 'Getting page {} for followers'.format(page_count)
        users.extend(user)
    return users

def get_friends(user_id):
    users = []
    page_count = 0
    for user in tweepy.Cursor(api.friends, id=user_id, count=200).pages():
        page_count += 1
        print 'Getting page {} for friends'.format(page_count)
        users.extend(user)
    return users

def get_followers_ids(user_id):
    ids = []
    page_count = 0
    for page in tweepy.Cursor(api.followers_ids, id=user_id, count=5000).pages():
        page_count += 1
        print 'Getting page {} for followers ids'.format(page_count)
        ids.extend(page)

    return ids

def get_friends_ids(user_id):
    ids = []
    page_count = 0
    for page in tweepy.Cursor(api.friends_ids, id=user_id, count=5000).pages():
        page_count += 1
        print 'Getting page {} for friends ids'.format(page_count)
        ids.extend(page)
    return ids

def process_user(user):
    user_id = user['id']
    screen_name = user['screen_name']
    print 'Processing user : {}'.format(user['screen_name'])

    the_user = get_user_from_db(user_id)
    if the_user is None:
        follower_ids = get_followers_ids(user['screen_name'])
        friend_ids = get_friends_ids(user['screen_name'])

        user['followers_ids'] = follower_ids
        user['friends_ids'] = friend_ids

        users_to_add = []
        for follower in get_followers(screen_name):
            if not is_user_in_db(follower.id):
                users_to_add.append(follower._json)

        for friend in get_friends(screen_name):
            if not is_user_in_db(friend.id):
                users_to_add.append(friend._json)

        users.insert_many(users_to_add)
        users.insert_one(doc['user'])

if __name__ == "__main__":

    for doc in raw_tweets.find({'processed' : {'$exists': False}}):
        print 'Start processing'
        if 'user' in doc:
            process_user(doc['user'])

        if 'retweeted_status' in doc:
            process_user(doc['retweeted_status']['user'])

        raw_tweets.update_one({'_id': doc['_id']}, {'$set':{'processed':True}})


texts: Methods to search for a client in MySQL by ID or by phone

texts:
I have this code that returns a client object, but to do it I use two methods.

How can I improve this to be more efficient and ensure it meets common standards?

    //Method that returns a client from a string
    private static Cliente ObtenerCliente(string query)
    {
        try
        {
            abrirConexion(); //Static method that opens a connection

            cmd = new MySqlCommand(query, mySqlConexion);
            MySqlDataReader dataReader = cmd.ExecuteReader();

            if (dataReader.Read())
            {
                return new Cliente(
                    Convert.ToInt32(dataReader["id_cliente"]),
                    dataReader["nombre_cliente"].ToString());
            }
            else
            {
                dataReader.Close();
                return null;
            }
        }
        catch (MySqlException e)
        {
            MessageBox.Show(e.ToString());
            return null;
        }
        finally
        {
            cerrarConexion(); //Static method that closes the connection
        }
    }

    //Method that returns a customer from a phone number given
    public static Cliente ObtenerCliente_Telefono(string telefono)
    {
        string query = "SELECT * FROM clientes WHERE (telefono1_cliente = '" + telefono + "' OR telefono2_cliente = '" + telefono + "');";
        return ObtenerCliente(query); //Metodo que hace la consulta
    }
    public static Cliente ObtenerCliente_Id(int id)
    {
        string query = "SELECT * FROM clientes  WHERE id_cliente = " + id + ';';
        return ObtenerCliente(query);
    }


texts:
This is a basic implementation of Dijkstra's Shortest Path Algorithm for Graphs. I am looking for any kind of improvement.

/*
    Author: Stevan Milic
    Date: 10.05.2018.
    Dijkstra's Shortest Path Algorithm
*/
#include <stdio.h>
#include <limits.h>
#include <iostream>

#define N 9 // Number of Nodes in the graph

int minDistance(int distance[], bool visitedSet[])
{
    int min = INT_MAX, min_index;

    for (int v = 0; v < N; v++)
        if (visitedSet[v] == false && distance[v] <= min)
            min = distance[v], min_index = v;
    return min_index;
}

void displayPath(int parent[], int s)
{
    if (parent[s] == -1)
        return;
    displayPath(parent, parent[s]);

    printf("-> %d ", s);
}

void display(int distance[], int n, int parent[])
{
    int start = 0;
    printf("Node\t     Distance\t         Path");
    for (int i = 1; i < N; i++)
    {
        printf("\n%d -> %d\t\t%d\t\t%d ", start, i, distance[i], start);
        displayPath(parent, i);
    }
}

void dijkstra(int graph[N][N], int start)
{
    int distance[N];

    bool visitedSet[N];

    int parent[N]; // For storing the shortest path tree

    for (int i = 0; i < N; i++) // This will make all distances as infinite and all nodes as unvisited
    {
        parent[0] = -1;
        distance[i] = INT_MAX;
        visitedSet[i] = false;
    }
    distance[start] = 0;
    for (int count = 0; count < N - 1; count++) // Finding the shortest path for all nodes
    {
        int u = minDistance(distance, visitedSet);

        visitedSet[u] = true;

        for (int n = 0; n < N; n++)
            if (!visitedSet[n] && graph[u][n] && distance[u] + graph[u][n] < distance[n])
            {
                parent[n] = u;
                distance[n] = distance[u] + graph[u][n];
            }
    }
    display(distance, N, parent);
}

int main()
{
    printf("***** Dijkstra's Shortest Path Algorithm ***** \n\n");
    int graph[N][N] = { {0, 4, 0, 0, 0, 0, 0, 8, 0 },
                        {4, 0, 8, 0, 0, 0, 0, 11, 0},
                        {0, 8, 0, 7, 0, 4, 0, 0, 2 },
                        {0, 0, 7, 0, 9, 14, 0, 0, 0},
                        {0, 0, 0, 9, 0, 10, 0, 0, 0},
                        {0, 0, 4, 0, 10, 0, 2, 0, 0},
                        {0, 0, 0, 14, 0, 2, 0, 1, 6},
                        {8, 11, 0, 0, 0, 0, 1, 0, 7},
                        {0, 0, 2, 0, 0, 0, 6, 7, 0 }
                      };
    dijkstra(graph, 0);
    printf("\n\n");
    system("pause");
    return 0;
}


texts: DiagnosticAnalyzer for Roslyn that guards against catch-all exception clauses

texts:
Dabbling around with Roslyn and made a small analyzer just now. This one will show a warning in Visual Studio when you have a try-catch statement that only has a catch(Exception e).

I realize the working code (AnalyzeNode) is rather small, but I'm looking for feedback on best-practices (insofar there are already best practices established) and general remarks on scenarios that I might have overlooked.

I have also been looking for a way to unit test this, but haven't come up with a good solution yet. Is there an elegant way to test these analyzers instead of looking over them by hand? Or perhaps an API that exposes some crude methods which I could provide a wrapper for?

Analyzer

[DiagnosticAnalyzer]
[ExportDiagnosticAnalyzer(DiagnosticId, LanguageNames.CSharp)]
class SingleGeneralExceptionAnalyzer : ISyntaxNodeAnalyzer<SyntaxKind>
{
    private const string DiagnosticId = "SingleGeneralException";
    private const string Description = "Verifies whether a try-catch block does not contain just a single Exception clause.";
    private const string MessageFormat = "A catch-all clause has been used.";
    private const string Category = "Exceptions";
    private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning);

    public ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
    {
        get
        {
            return ImmutableArray.Create(Rule);
        }
    }

    public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest
    {
        get
        {
            return ImmutableArray.Create(SyntaxKind.CatchClause);
        }
    }

    public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
    {
        var clause = node as CatchClauseSyntax;
        var exceptionType = clause.Declaration.Type;
        var identifier = semanticModel.GetSymbolInfo(exceptionType);
        var isGeneralException = identifier.Symbol.Name == typeof(Exception).Name;
        var hasMultipleClauses = clause.Parent.ChildNodes().OfType<CatchClauseSyntax>().ToList().Count > 1;

        // Less-specific exceptions can't be caught after a more general exception, or a compile error occurs
        // Therefore we don't need to look at the order of the clauses

        if (isGeneralException && !hasMultipleClauses)
        {
            addDiagnostic(Diagnostic.Create(Rule, clause.Declaration.GetLocation()));
        }
    }
}

Testclass

class SingleExceptionClauseAnalyzer
{
    void SingleException_ShouldCause_Warning()
    {
        try
        {
            int x = Int32.Parse("5");
        }
        catch (Exception e)
        {
            int x = 8;
        }
    }

    void MultipleExceptions_ShouldNotCause_Warning()
    {
        try
        {
            int x = Int32.Parse("5");
        }
        catch (FormatException e)
        {
            int x = 7;
        }
        catch (Exception e)
        {
            int x = 8;
        }
    }

    void SingleException_WithFullyQualifiedName_ShouldCause_Warning()
    {
        try
        {
            int x = Int32.Parse("5");
        }
        catch (System.Exception e)
        {
            int x = 8;
        }
    }

    void MultipleExceptions_WithFullyQualifiedName_ShouldNotCause_Warning()
    {
        try
        {
            int x = Int32.Parse("5");
        }
        catch (System.FormatException e)
        {
            int x = 7;
        }
        catch (System.Exception e)
        {
            int x = 8;
        }
    }
}


texts:
I'm trying to solve one simple task and on first look it's working.
Any advice on how I can optimize this code will be appreciated.
A quick description of the task would be:
You have a file from which you read the integers.

The first line has two values:

The array width
The number of test cases

The second line has actual array values.
After that, you have \$N\$ rows all containing the array range which should be checked.

\$N =\$ the number of test cases.
Here's a link to my code

<?php
$handle = fopen("php://stdin", "r");
$getFirstRow = fgets($handle);
$firstrow = explode(" ", $getFirstRow);
$firstrow1 = intval($firstrow[0]);
$firstrow2 = intval($firstrow[1]);

$getString = fgets($handle);
for ($z=0;$z<$firstrow2;$z++)
{
$getRange = fgets($handle);
$getRagearr = explode(" ", $getRange);
$i=intval($getRagearr[0]);
$j=intval($getRagearr[1]);
$arrResult = array();
$lane = explode(" ", $getString);
for ($p=$i;$p<=$j;$p++)
{
array_push($arrResult, $lane[$p]);
}
$result = min($arrResult);
echo $result.PHP_EOL;
}


texts: A clean and efficient makefile for a simple c program

texts:
I have an instructor who is very stringent on makefiles only containing rules and dependencies that need to be included.

The structure for the program is very basic.  The requirement is to produce two executable files:  a3b and a3m.  There was some code duplication, so I included that in a source code file called myarray.c (with a header by the same name).

I have already tested the makefile, and everything seems to work.  However, can the makefile be cleaner or more accurate (such as removing or adding rules or dependencies)?

The macro names and values were specified by the instructor.

CFLAGS = -g -Wall - Werror
CC = gcc
LD = gcc
PROG1 = a3b
PROG2 = a3m
PROG3 = myarray
OBJ1 = a3b.o
OBJ2 = a3m.o
OBJ3 = myarray.o

all : $(PROG1) $(PROG2) $(PROG3)

$(PROG1) : $(OBJ1) $(PROG3)
    $(LD) $(OBJ1) $(OBJ3) -o $(PROG1)

$(PROG2): $(OBJ2) $(PROG3)
    $(LD) $(OBJ2) $(OBJ3) -o $(PROG2)

$(PROG3): $(OBJ3) $(PROG3).h
    $(LD) $(PROG3).c -c

clean :
    /bin/rm -f *.o a.out $(PROG1) $(PROG2) $(PROG3)


texts: JavaScript to parse json that can be, string, object and array

texts:
I have to parse a json object that can be a string, array, array of strings and array of object. I realised that it's not good from the beginning that one object can be many types, but I can't change the code from upstream so
I'll have to deal it in my code instead. I'm building a pixel library for modern browser so I'm not using jQuery or lodash. I'm supporting most modern browser and IE >= 9

Here's the example of the data that can be returned

"author": {
 "@type": "Person",
 "name": "Author"
}

Or

"author":[{"@type":"Person","name":"Author"}]

Or

"author": 'Author'

Or

"author": ['Author', 'Author1']

And this is my code.

  let obj = {};
  try {
    const json = document.querySelector('div.json');
    if (json) {
      let disc = JSON.parse(json.innerHTML);
      let authors = disc.author;

      if (typeof authors !== 'undefined' && Array.isArray(authors) && authors.length > 0) {
        authors = authors.map((author) => {
          if (typeof author === 'object' && author.name) {
            return author.name;
          } else {
            return author;
          }
        });
      }

      if (typeof authors !== 'undefined' && !Array.isArray(authors) && typeof authors === 'object') {
        authors = [authors.name];
      }

      if (typeof authors !== 'undefined' && typeof authors === 'string') {
        authors = authors.split(',');
      }

      obj.cAu: authors.join(',');
    }
  } catch (e) { }

  return obj;

My question is, is there a better way to do this in a more efficient way?


texts: Looping over files in C++ and changing their names to store data into a single file

texts:
I have a lot of data in separate files generated from a simulation program. All data is clear and formatted via a single space to read in 4 columns. I can open and store data from each file one at a time, but that will get so impossible once I hit more than, say, 10 files of data with the same simulation data columns.

I am just trying to find a better way to open files and store the data using an iterative method instead of typing, for example, "open file, read file data, append to file" over 1000 times.

#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>

using namespace std;

int main ()
{
// INITIALIZE
    int tmax = 80000;

    float time_step[tmax];

    float LEx[tmax];
    float LEy[tmax];
    float LEz[tmax];
    float LE[tmax];

    float AvgLEx;
    float AvgLEy;
    float AvgLEz;
    float AvgLE;

    float Function[tmax];

// FILES
    ifstream infile;
    infile.open("File_1.prn");
// THIS INFILE is where I want to put a loop to change File_1 to File_2 to File_3 and so on and so on to append data from all those files into ONE single file
    if(infile.fail())
    {
        cout << "error reading file" << endl;
        return 1;
    }

    for (int i = 0; i < tmax+1; ++i)
    {
        infile >> time_step[i] >> LEx[i] >> LEy[i] >> LEz[i] >> LE[i];
        AvgLEx = AvgLEx + LEx[i];
        AvgLEy = AvgLEy + LEy[i];
        AvgLEz = AvgLEz + LEz[i];
        AvgLE = AvgLE + LE[i];

    }

    AvgLEx = AvgLEx/tmax;
    AvgLEy = AvgLEy/tmax;
    AvgLEz = AvgLEz/tmax;
    AvgLE = AvgLE/tmax;

    cout << "AvgLE: " << AvgLE << "\n";
    cout << time_step[tmax] << " LEx " << LEx[tmax] << " LEy " << LEy[tmax] << " LEz: " << LEz[tmax] << " LE: " << LE[tmax] << endl;

    cout << "\n";

    infile.close();
    cout << "\nFile read! \n";

// FUNCTIONS

    for (int i = 0; i < tmax+1; ++i)
    {
        Function[i] = LE[i] - AvgLE;
        cout << LE[i] << " " << AvgLE << " " << Function[i] <<  "\n";
    }

    cout << "\n Function set up \n";

// // CONVOLUTION
    float A_t;
    float A_dt;
    int dt, t;

    float max=0;

        for (int dt = 0; dt < 1 + tmax/10; ++dt)
        {
            //dt = 1;
            cout << "dt: " << dt << "\n";
            //A_dt = 0;
            int window = tmax-dt;
            for (int t = 0; t < window; ++t)
            {
                if (t==0)
                {
                    A_t = 0;
                    cout << "A_t was set to zero \n";
                }

                A_t+= Function[t] * Function[t + dt];
                cout << "A_t is accumulation ...: " << A_t << "\n" ;
            }

            A_dt = A_t / window;

            if (A_dt > max)
            {
                max = A_dt;
            }

// OUTPUT
            ofstream AutoCor;
            AutoCor.open ("AutoCor_25.prn", ios::app);
            AutoCor << dt << " " << A_dt << "\n";
            AutoCor.close();
            cout << "A_dt: " << A_dt << " " << "window used: " << window << "\n";

        }

        cout << "max used: " << max << "\n";

// RETURN
    return A_dt;
    return 0;

}


texts: Create Lists for Drop-Down Menus in Different Sheet

texts:
I'm currently working with a workbook utilized at my work that has the following code.  It currently takes about 10 seconds to complete, and needs to be executed several times throughout utilizing the workbook.  Is there any way to speed up this process?

Right now, the user specifies enters the drop down items needed in Sheet2, the code creates an additional sheet named "Filter Builder", enters the data in a column, which is then copied into the corresponding cell in the Filter Options sheet, and finally pulled by Sheet1 to create a drop down list.

Sub Macro1()

'TURNS OFF THE SCREEN UPDATING SO IT BRING YOU TO THE FILTER OPTIONS TAB AFTER THE MACRO IS COMPLETE
Application.ScreenUpdating = False

'FILTERS OUT THE ROWS THAT DO NOT HAVE "SPECIAL VALIDATION" AND HIDES THEM
ActiveSheet.Range("$A$1:$AF$5150").AutoFilter Field:=5, Criteria1:="Special Validation"

'ADDS ANOTHER SHEET FOR THE DATA TO BE ENTERED INTO
Sheets.Add After:=Sheets(Sheets.Count)

'NAMES THE SHEET AS "FILTER BUILDER"
ActiveSheet.Name = "Filter Builder"

'PASTES THE DATA IN FILTER BUILDER THEN DELIMITS IT
Sheets("Checklist Builder").Columns("F:F").EntireColumn.Hidden = False
Sheets("Checklist Builder").Columns("F:F").Copy Sheets("Filter Builder").Columns("A:A")
Sheets("Checklist Builder").Columns("G:G").Copy Sheets("Filter Builder").Columns("B:B")

'DELIMITS THE DATA SO THE TEXT SPLIT UP IN TO DIFFERENT COLUMNS, DIVIDED UP BY COMMAS
Application.CutCopyMode = False
Columns("B:B").TextToColumns Destination:=Range("B1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
    Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
    :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1)), TrailingMinusNumbers:= _
    True

'SELECTS THE DATA TO TRANSPOSE IT
Sheets("Filter Builder").Rows("2:1150").Select

'COPIES AND TRANSPOSES THE DATA IN THE "FILTER BUILDER" EXCEL SHEET TO "FILTER OPTIONS"
Application.CutCopyMode = False
Selection.Copy
 Sheets("Filter Options").Range("K1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True

'AUTO FITS THE COLUMNS IN THE EXCEL SHEET
Sheet3.Cells.EntireColumn.AutoFit

'TURNS OFF THE DISPLAY ALERT TO DELETE THE SHEET
Application.DisplayAlerts = False

'DELETES THE SHEET
Sheets("Filter Builder").Delete

'HIDES COLUMN 'F' IN THE CHECKLIST BUILDER AGAIN
Sheets("Checklist Builder").Columns("F:F").EntireColumn.Hidden = True

'TURNS THE DISPLAY ALERTS BACK ON
Application.DisplayAlerts = True

'TAKES AWAY THE AUTO FILTER THAT WAS APPLIED IN THE "CHECKLIST BUILDER" SHEET
Sheet2.Range("$A$1:$AF$150").AutoFilter Field:=5

'GOES BACK TO THE CHECKLIST BUILDER SHEET
Sheets("Checklist Builder").Select
Range("A1").Select

Application.ScreenUpdating = True

End Sub


texts:
I wanted to store CMTimeRange structures inside managed objects, so I've worked out the following:

@interface Clip : NSManagedObject

@property (nonatomic, retain) NSData * primitiveRange;
@property CMTimeRange range;

@end

Within the data model editor I've set the type of primitiveRange to "Transformable".

The implementation:

@implementation Clip
{
    CMTimeRange _range;
}
@dynamic primitiveRange;

// pre-calculated get
- (void)awakeFromFetch
{
    [super awakeFromFetch];

    NSData *data = [self primitiveValueForKey:@"primitiveRange"];
    if (data) {
        _range = CMTimeRangeMakeFromDictionary((__bridge CFDictionaryRef)[NSKeyedUnarchiver unarchiveObjectWithData:data]);
    }
}

- (CMTimeRange)range
{
    [self willAccessValueForKey:@"primitiveRange"];
    CMTimeRange value = _range;
    [self didAccessValueForKey:@"primitiveRange"];

    return value;
}

// immediate-update set
- (void)setRange:(CMTimeRange)range
{
    NSData *value = [NSKeyedArchiver archivedDataWithRootObject:CFBridgingRelease(CMTimeRangeCopyAsDictionary(range, kCFAllocatorDefault))];

    [self willChangeValueForKey:@"primitiveRange"];
    [self setPrimitiveValue:value forKey:@"primitiveRange"];
    [self didChangeValueForKey:@"primitiveRange"];

    _range = range;
}

This works fine, but is this the proper way of doing things?


texts: Low performance of HTTP request using Haskell wreq

texts:
The program makes HTTP requests (checks video stream status) and calls an external program.

{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Lens ((&), (.~), (^.))
import Network.HTTP.Client (HttpException(..))
import Network.Wreq
import Data.Text (Text, null)
import Data.Aeson.Lens (key, _String)
import Control.Exception as E
import System.Process (callCommand)

streamCheckList :: [(String, String)]
streamCheckList = [ ("tempsnip2", "python bot_n.py 2")
                  , ("tempsnip3", "python bot.py 3"  )
                  , ("tempsnip4", "python bot.py 4"  )
                  ]

tokenAndSignatureBaseUrl :: String -> String
tokenAndSignatureBaseUrl ch = concat [ "https://api.twitch.tv/api/channels/"
                                     , ch, "/access_token" ]

tokenAndSignature :: String -> IO (Response B.ByteString)
tokenAndSignature ch = get $ tokenAndSignatureBaseUrl ch

hlsPlaylistBaseUrl :: String -> String
hlsPlaylistBaseUrl ch = concat [ "http://usher.twitch.tv/api/channel/hls/"
                               , ch, ".m3u8" ]

hlsPlaylist :: (String, Text, Text) -> IO (Response B.ByteString)
hlsPlaylist (ch, token, sig) = let opts = defaults & param "token" .~ [token]
                                                   & param "sig"   .~ [sig]
                               in getWith opts $ hlsPlaylistBaseUrl ch

restartIfNeeded :: (String, String) -> IO ()
restartIfNeeded (ch, cmd) = do streamAccessible <- isStreamAccessible ch
                               if streamAccessible
                               then print $ ch ++ " stream is accessible"
                               else do print $ "restarting " ++ ch
                                       restart cmd

restart :: String -> IO ()
restart existingProcessCmd = (callCommand $ concat [ "pkill --full \""
                                                   , existingProcessCmd
                                                   , "\""
                                                   ]) `E.catch` handler
                               where
                                handler :: E.IOException -> IO ()
                                handler e = print e

-- in fact we try to fetch an hls m3u playlist of stream
isStreamAccessible :: String -> IO Bool
isStreamAccessible ch = do
    E.try (tokenAndSignature ch) >>= tsHandler
      where
        tsHandler :: Either HttpException (Response B.ByteString) -> IO Bool
        tsHandler (Left _) = return False
        tsHandler (Right rToSig)
          = let token = rToSig ^. responseBody . key "token" . _String
                sig = rToSig ^. responseBody . key "sig" . _String
            in if Data.Text.null token || Data.Text.null sig
               then return False
               else E.try (hlsPlaylist (ch, token, sig)) >>= pHandler
        pHandler :: Either HttpException (Response B.ByteString) -> IO Bool
        pHandler (Left _) = return False
        pHandler (Right _) = return True

main :: IO ()
main = mapM_ restartIfNeeded streamCheckList

The problem is that the program uses too much CPU. As explained here, I've built with:

stack build --executable-profiling --library-profiling --ghc-options="-Wall -fprof-auto -rtsopts"

tokenAndSignature takes 26.7% of CPU time with 43.2% allocs. Also it happens so that it's the function which result is used later by lens to decode JSON from. Inner functions of tokenAndSignature contain many decodeLenientWithTable functions (from Data.ByteString.Base64.Internal module) with 550000 entries on average which looks awkward to me.

Yes, I use String type here. But it's only because wreq's library get function requires String as its argument.

stack exec -- test +RTS -sstderr shows that almost 1/3 of time is spent on GC:

MUT     time    1.604s  (  5.535s elapsed)
GC      time    0.514s  (  0.505s elapsed)
...
Productivity  76.9% of total user, 28.2% of total elapsed

What's my mistake?


texts:
Write the find_boundaries function, which will take a list of numbers. The function should return the tuple with the smallest and largest number in the set. If there is an item in the list that is not a number, it should be ignored. If an empty list is entered, the function should return None.

My code:

def find_boundaries(lista):

    if not lista:
        return None

    elif lista:
        max_ = lista[0]
        min_ = lista[0]
        new_lista = []

        for i in lista:
            if int == type(i):
                new_lista.append(i)

        for i in range(len(new_lista)):
            if new_lista[i] > max_:
                max_ = new_lista[i]

            elif new_lista[i] < min_:
                min_ = new_lista[i]

    return max_, min_

I am looking for any opinion/ suggestion on that code. It does what is expected, but would you say that this is the most efficient way to solve that task in Python?


texts:
I recently wrote a simple echo server in Java 7 using the NIO APIs so it was asynchronous and non-blocking. Then I decided, as a learning experience, to redo it with Java 8 hoping to use a more functional style and not have nested callbacks. I'm struggling to understand how to use the new CompletableFuture class with the Futures returned by AsynchronousSocketChannel.

This code currently works but is slower than the Java 7 version. If anyone can point out ways to improve it (or maybe that I'm going about it completely wrong) it would be appreciated. The main problem, to me at least, is that I now have to call get() on three Futures, whereas before I didn't have any blocking operations.

try (final AsynchronousServerSocketChannel listener =
    AsynchronousServerSocketChannel.open()) {

        listener.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        listener.bind(new InetSocketAddress("localhost", 8080));

        while (true) {

            AsynchronousSocketChannel connection = listener.accept().get();
            CompletableFuture<AsynchronousSocketChannel> connectionPromise =
                CompletableFuture.completedFuture(connection);

            CompletableFuture<ByteBuffer> readerPromise = CompletableFuture.supplyAsync(() -> {
                ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
                try {
                    connection.read(buffer).get();
                    return (ByteBuffer) buffer.flip();
                } catch (InterruptedException | ExecutionException e) {
                    connectionPromise.completeExceptionally(e);
                }
                return null;
            });

            readerPromise.thenAcceptAsync((buffer) -> {
                if (buffer != null) {
                    try {
                        connection.write(buffer).get();
                        connection.close();
                    } catch (InterruptedException | ExecutionException | IOException e) {
readerPromise.completeExceptionally(e);
                    }
                }
            });
        }

    } catch (IOException | InterruptedException | ExecutionException e) {
        e.printStackTrace();
}


texts:
I am fairly new to Python 3. Is there a way to implement a +/- function into a single line of code? In this simple quadratic formula solver function I wrote, I used two separate variables and returned them both. Is there a cleaner way to do this?

def Quadratic_Solver(a,b,c):

    """
    This function returns solution to a univariate (single variable)

    quadratic equation 0 = ax2 + bx + c, where a is not 0.

    Args:

    * a (float or int) - the value represents coefficient of degree

                     variable 2

    * b (float or int) - the value represents coefficient of degree

                     variable 1

    * c (float or int) - the value represents the constant

    Returns:

    * two solutions for x (float)

    """
    try:
        a = float(a)
        b = float(b)
        c = float(c)
        sol1 = (-b + (b**2 - 4*a*c)**0.5)/(2*a)
        sol2 = (-b - (b**2 - 4*a*c)**0.5)/(2*a)
        return (sol1, sol2)

    except:
        print("Input variables are not floats")


texts:
This is my second attempt after I started to learn about STL. I am oblivious and need suggestions/advices on if there can be improvements made on this code.

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;

string LongestWord(string sen) {

  vector<string> coll; //initialize vector

  istringstream iss(sen); //read the string "sen"

  copy(istream_iterator<string>(iss), //copy from beginning of iss
    istream_iterator<string>(), //to the end of iss
    back_inserter(coll)); //and insert string to vector
  //istream_iterator by default separates word by whitespace

  string longestWord = coll.at(0);
  int longestCount = longestWord.length();

  for(auto element : coll)
  {
      if(element.length() > longestCount)
      {
          longestWord = element;
      }
  }
    return longestWord;

}