texts: Finding possible subset combination from the user input

texts:
int combiset(int ism,int inarr[],int inpth){
    int r1,r2,r3,r4;
    for(int i=0;i<inpth;i++){
        r1 = inarr[i]+inarr[i+1];
        r2 = r1+inarr[i+2];
        r3 = r2+inarr[i+3];
        r4 = r3+inarr[i+4];

        if(r4==ism){
            printf("%d %d %d %d %d\n",inarr[i],inarr[i+1],inarr[i+2],inarr[i+3],inarr[i+4]);}
        if(r3==ism){
            printf("%d %d %d %d\n",inarr[i],inarr[i+1],inarr[i+2],inarr[i+3]);}
        if(r2==ism){
            printf("%d %d %d\n", inarr[i], inarr[i+1], inarr[i+2]);}
        if(r1==ism){
            printf("%d %d\n", inarr[i], inarr[i+1]);}
    }
}

I am currently designing a function which will calculate and display out the possible combinations of sets from the user input. User will inputs the value of sum that they want to target and the array data such as length and integers inside. For example, if user inputs
array length:10
array data:9 1 5 5 8 9 7 3 1 6
target sum:10

then the result output should look like
9 1
5 5
7 3
3 1 6

Hereby, answer should follow the input array order and answers should be linked, so 1 5 3 1 cannot be an answer.
In my opinion, function which I have designed is too inefficient because user may input the array length as 100 then I have to make r1 until r100 to check whether there is possible combination of sets but with my method, the codes will get tremendously longer. Thus I am thinking of simpler code but I have no idea for it. How can I make my function better to find possible combinations of set?


texts: Numeric and percentage deadband calculation

texts:
Calculate if the value exceeds percentage <> numeric deadbands of the previous value.

The first function is for percentage. It detects if $value is $deadband% greater or less than $previous.

The second is for numeric difference. It detects if the difference between $value and $previous is greater than $deadband.

function percentage_deadband($value,$previous,$deadband)
{
    if($previous==0 || $value==0 || $previous == $value)
    {
        return false; //if previous or value is 0, we can't work. assume false.
    }
    $percentage = $value / $previous * 100;
    if($percentage > 100){
        return $percentage - $deadband > 100;//if percentage - deadband > 100, we know the deadband is exceeded
    }
    if($percentage < 100){
        return 100 - $percentage > $deadband;//if 100 - percentage is greater than deadband, we know the deadband is exceeded
    }
    return false;
}

function numeric_deadband($value,$previous,$deadband)
{
    if($previous==0 || $value==0 || $previous == $value)
    {
        return false;
    }
    if($previous > $value){
        return $previous - $deadband >= $value;
    }else{
        return $value - $previous >= $deadband;
    }
    return false;
}

Testing the functions

$numeric_deadband = 3;
$numeric_set = [
    0=>['value'=>77,'previous'=>80],//true
    1=>['value'=>78,'previous'=>77],//false
    2=>['value'=>81,'previous'=>78],//true
    3=>['value'=>81,'previous'=>81]//false
];
echo 'numeric set:
';
foreach($numeric_set as $row)
{

    var_dump(numeric_deadband($row['value'],$row['previous'],$numeric_deadband));
    echo '
';
}

echo '
';

$percentage_deadband = 10;
$percentage_set = [
    0=>['value'=>27,'previous'=>39],//true
    1=>['value'=>39,'previous'=>40],//false
    2=>['value'=>41,'previous'=>28],//true
    3=>['value'=>28,'previous'=>31]//false
];
echo 'percentage set:
';
foreach($percentage_set as $row)
{

    var_dump(percentage_deadband($row['value'],$row['previous'],$percentage_deadband));
    echo '
';
}

They seem to work correctly with my small set of test data, but I am not so great with math. I'd love a second opinion.


texts:
I am trying to solve this question: https://www.codechef.com/problems/TADELIVE

  Andy and Bob are the only two delivery men of Pizza-chef store. Today,
  the store received N orders. It's known that the amount of tips may be
  different when handled by different delivery man. More specifically,
  if Andy takes the ith order, he would be tipped Ai dollars and if Bob
  takes this order, the tip would be Bi dollars.

  They decided that they would distribute the orders among themselves to
  maximize the total tip money. One order will be handled by only one
  person. Also, due to time constraints Andy cannot take more than X
  orders and Bob cannot take more than Y orders. It is guaranteed that X
  + Y is greater than or equal to N, which means that all the orders can be handled by either Andy or Bob.

  Please find out the maximum possible amount of total tip money after
  processing all the orders

  1 ≤ N ≤ 10⁵
  1 ≤ X, Y ≤ N
  X + Y ≥ N
  1 ≤ Ai, Bi ≤ 10⁴

I have used a dynamic programming approach:

"""
https://www.codechef.com/problems/TADELIV]
"""

"""
https://www.codechef.com/problems/TADELIV]
"""

from functools import lru_cache

@lru_cache(maxsize=None)
def optimal_sum(x, y, i):
    if i >= len(a):
        return 0
    if x == 0:
        return sum(b[i:])
    if y == 0:
        return sum(a[i:])
    sum_with_a = a[i] + optimal_sum(x-1, y, i+1)
    sum_with_b = b[i] + optimal_sum(x, y-1, i+1)
    return max(sum_with_a, sum_with_b)

n, x, y = map(int, input().split())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
ans = optimal_sum(x, y, 0)
print(ans)

Sadly this timed out :( How do I make it run faster?


texts: Capturing temperature information for a patient

texts:
I just finished writing a program that captures temperature information for a patient. I'm looking for suggestions on how to improve the code that I have. Although what I have compiles and does what I want, I wonder if there is any methodology I'm using inappropriately despite it still working.

Some particular areas I worry about are redundant code and my use of the conversion and fever methods (you can ignore the clearly bad math. I just wanted any calculation until I determined functionality).

Temperature.hpp:

#ifndef Temperature_h
#define Temperature_h

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

class Temperature {
private:
    string newPatient;
    float newTemp;
    char newDegree;

public:
    enum TempMethod {oral, arm, leg, bum};

    Temperature();
    Temperature(string, float, char);
    ~Temperature();

    string getPatient() const;
    float getTemp() const;
    char getDegree() const;

    float setFaren();
    float setCels();
    void hasFever();

};

#endif /* Temperature_h */

Temperature.cpp:

Temperature::Temperature(string patient, float temp, char degree){
    newPatient = patient;
    newTemp = temp;
    newDegree = degree;
}

Temperature::~Temperature(){

}

string Temperature::getPatient() const{
    return newPatient;
}

float Temperature::getTemp() const{
    return newTemp;
}

char Temperature::getDegree() const{
    return newDegree;
}

float Temperature::setFaren(){
    float faren = newTemp+32;
    return faren;
}

float Temperature::setCels(){
    float celsi = newTemp-32;
    return celsi;
}

void Temperature::hasFever(){
    if(newTemp >= 100.4){
        cout << "Patient " << newPatient << " has a fever!!\n";
    }
}

main.cpp:

#include <iostream>
#include <string>
#include "Temperature.h"
using namespace std;

int main() {
    string patient;
    float temp;
    float celsius;
    float farenheit;
    char degree;

    cout << "Enter Patient Name: ";
    getline(cin, patient);
    cout << "Enter the tempature: ";
    cin >> temp;
    cout << "Enter degree method (F or C): ";
    cin >> degree;

    Temperature Temp_1(patient, temp, degree);
    cout << "\nPatient Name: " << Temp_1.getPatient() << endl <<
    "Temperature: " << Temp_1.getTemp() << " degrees " << Temp_1.getDegree() << endl;

    if(Temp_1.getDegree() == 'F'){
        celsius = Temp_1.setCels();
        cout << "Temperate in Celsius: " << celsius << " degrees Celsius" << endl;
    }
    else if(Temp_1.getDegree() == 'C'){
        farenheit = Temp_1.setFaren();
        cout << "Temperature in Farenheit: " << farenheit << " degrees Farenheit" << endl;
    }

    Temp_1.hasFever();

    return 0;
}


texts:
I am trying to improve my skill in C, and this time by getting away from strtok. The following code splits the input string into a token_list, an array of strings.

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

#define MAX_LINE_LEN 256
#define NULL_TERM '\0'

/* A function that will print the content of the token_list */
int printcharlist(char **tok_list)
{
    char **pptr = tok_list;

    while (*pptr) {
        printf ("++ %s\n", *pptr);
        pptr++;
    }

    return 0;
}

/* returns the string between 2 pointers (not forgetting to append NULL_TERM */
char *getStr(char *start, char *end)
{
    int length=end-start;
    int i=0;
    char *result = (char *)malloc (sizeof (char) * (length+1));

    while (i < length) {
    result[i] = *start;
    start++;
    i++;
    }

    result[i] = NULL_TERM;

    return result;
}

int main (int argc, char ** argv)
{
    char *input = "something;in;the;way;she;moves";
    char reject = ';';

    char *start = input;
    char *end = input;

    char *token_list[MAX_LINE_LEN] = {NULL};
    int i=0;

    /* Is this predicate okay? I read that certain compiler might raise warnings here */
    while (end=strchr(start, (int)reject)) {

        token_list[i]=getStr(start, end);

        i++;
        end++;
        start=end;
    }

    /* It feels awkward to add one more token after the while loop. Is it standard? Should/can I avoid this? */
    token_list[i]=start;
    printcharlist(token_list);

    return EXIT_SUCCESS;
}

I am interested in any kind of feedback I can get. But if I absolutely must ask questions it would be:

Would something make you react badly if someone sent you this code in a patch/pull-request? If yes, what?
Consider this code is going to production. What are the edge cases that I miss and how can I solve them?


texts: Pushing local repository to remote repository using python Github

texts:
The code should do the following in order:

It should download/clone the public Github repository locally.
It should remove all the git history (and branches)
Use the Github API to create a new Github repository initialized with the input github repository content that you downloaded locally. The new repository should be named using name supplied.
I am able to do steps 1 and 3 but asks for log-in 2 times. I am not able to initialize the new remote repo with local repo. local_repo = repo1 how? And removing git history? where can I find git history in the cloned repo.

import git,os,tempfile,os,fnmatch,sys
from github import Github

username = sys.argv[1]
password = sys.argv[2]
input_repo_url = sys.argv[3]
output_repo_name = sys.argv[4]

tempdir=tempfile.mkdtemp(prefix="",suffix="")
predictable_filename = "myfile"
saved_umask = os.umask(77)

path = os.path.join(tempdir,predictable_filename)
print("Cloning the repository at "+path)

local_repo = git.Repo.clone_from(input_repo_url,path, branch="master")
print("Clone successful!")

g = Github(username,password)
user = g.get_user()
repo1 = user.create_repo(output_repo_name)
print("New repository created at "+username+" account ")
print(repo1)

target_url = "https://github.com/"+username+"/"+output_repo_name+".git"
print(target_url)

print("Pushing cloned repo to target repo")
local_repo.create_remote("new",url=target_url)
local_repo.git.push("new")
print("Success!!")


texts:
This week I started reading "The Rust Programming Language". As I reached the chapters on enumerations and pattern matching I felt I had enough material to put together a simple representation of JSON in Rust, just to play around and get a better feeling of the language.

This is what I came up with:

use std::fmt;

pub enum Json {
    Obj(Vec<(String, JsonVal)>),
    Arr(Vec<JsonVal>),
}

pub enum JsonVal {
    Str(String),
    Num(f64),
    Composite(Json),
    Bool(bool),
    Null,
}

#[allow(unused_must_use)]
impl fmt::Display for Json {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Json::Obj(ref obj) => {
                "{".fmt(f);
                for (n, prop) in obj.iter().enumerate() {
                    if n != 0 {
                        ",".fmt(f);
                    }
                    "\"".fmt(f);
                    prop.0.fmt(f);
                    "\":".fmt(f);
                    prop.1.fmt(f);
                }
                "}".fmt(f);
                Result::Ok(())
            }
            Json::Arr(ref arr) => {
                "[".fmt(f);
                for (n, item) in arr.iter().enumerate() {
                    if n != 0 {
                        ",".fmt(f);
                    }
                    item.fmt(f);
                }
                "]".fmt(f);
                Result::Ok(())
            }
        }
    }
}

impl fmt::Display for JsonVal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "{}",
               match *self {
                   JsonVal::Str(ref string) => format!("\"{}\"", string),
                   JsonVal::Num(number) => number.to_string(),
                   JsonVal::Composite(ref json) => json.to_string(),
                   JsonVal::Bool(boolean) => boolean.to_string(),
                   JsonVal::Null => String::from("null"),
               })
    }
}

The things that "smell" a little bit, in my humble opinion, are three:

The warning suppression before the implementation of the Display trait for Json: I tried aggregating the operations in Vectors and then folding them together but the resulting code looked unnecessarily garbled, so I just ignored the Results. Is there a better way to do this?
In the Display implementation of JsonVal I use the format! macro to basically make a copy of the string (a "technique" which smells by itself); however, as I'm not touching the string in any way, it would be great to just hand out the string itself to the write! macro; returning *string wouldn't make sense as I would be trying to perform a move on a borrowed reference, but just returning the reference would mean that in other branches I'd have to return a reference as well, which gets rejected because the result of the calls to the to_string method go out of scope after the pattern matching. Is there a way out of this, perhaps using lifetimes?
In the Display implementation of JsonVal I use the String::from associated function to return the value of JSON's null. However, if I'm not mistaken, this would mean that I would be creating a new instance of the String every time I have to format a null. A str, being 'static (again, if I'm not mistaken), would solve the problem. Is the something like a static String or a way to be more efficient, perhaps using (again) lifetimes?

Also, I put all the refs because the compiler hinted me to do so and I understand more or less that it has to do with the fact that I'm just borrowing what's inside the struct to use it, but it's not completely clear to me. However, I still have to encounter the ref keyword on the book, so don't bother explaining if you feel like I'm better off RTFM.

You can find an updated version of this code on my Github repo.


texts: Avoid the object/array check and treat the return value the same way with JavaScript spread operator?

texts:
I'm trying to implement a function (a template-helper function) which provides a simple merge-like functionality for both arrays and objects. The two functions are basically looks identical:
const mergeArrays = (first, ...rest) =>
  rest.reduce((acc, curr) => ([ ...acc, ...curr]), first);

const mergeObjects = (first, ...rest) =>
  rest.reduce((acc, curr) => ({ ...acc, ...curr }), first);

One could do a type check and a local variable to write a single function like this:
const mergeArraysOrObjects1 = (first, ...rest) => {
  let reducer = null;
  if ('object' === typeof first && null !== first) {
    reducer = (acc, curr) => ({ ...acc, ...curr });
  }
  if (Array.isArray(first)) {
    reducer = (acc, curr) => [...acc, ...curr];
  }

  if (!reducer) {
    throw new Error('The "merge" filter only works with arrays and hashes.');
  }

  return rest.reduce(reducer, first);
}

... but it seems so ugly to me. Another possibility is a type check and inline conditional:
const mergeArraysOrObjects2 = (first, ...rest) => {
  if ('object' !== typeof first || null === first) {
    throw new Error('The "merge" filter only works with arrays and hashes.');
  }

  return rest.reduce(
    (acc, curr) => Array.isArray(acc) ? [...acc, ...curr] : {...acc, ...curr},
    first
  );
}

I'm still learning JavaScript so I'm guessing if there is a more elegant and concise way to treat the return value the same way.


texts: DRY cursors: preventing T-SQL's FETCH statement from being repeated

texts:
Please assume I've exhaustively tried to come up with a set-based solution to my T-SQL problem, and that I need to use a cursor. The following is the typical1 boilerplate for a T-SQL cursor:

DECLARE @myId AS INT;

DECLARE myCursor CURSOR FAST_FORWARD FOR
SELECT id FROM MyTable;

OPEN myCursor;

FETCH NEXT FROM myCursor INTO @myId; -- COPY...

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Doing the cursor work!';

    FETCH NEXT FROM myCursor INTO @myId; -- ...PASTE! :'(
END;

CLOSE myCursor;
DEALLOCATE myCursor;

On Stack Overflow it's already been asked how to avoid the duplication. Please suppose this is quite important (e.g. it's somehow unavoidable to FETCH many columns into variables). While trying to come up with a solution to DRY the two FETCH statements into one, I ended up with boilerplate similar to the OP's answer to the mentioned question:

DECLARE @myId AS INT;

DECLARE myCursor CURSOR FAST_FORWARD FOR
SELECT id FROM MyTable;

OPEN myCursor;

WHILE 1=1 -- Not very pretty, but required to keep the FETCH statement DRY.
BEGIN
    FETCH NEXT FROM myCursor INTO @myId;
    IF @@FETCH_STATUS <> 0 BREAK;

    PRINT 'Doing the cursor work!';
END;

CLOSE myCursor;
DEALLOCATE myCursor;

Now, my code review question comes down to: is there any elegant way to DRY out duplicate FETCH statements from the "default" boilerplate (1st snippet)? If my second snippet is the easiest way, then I'd love to know if there is any way to get rid of the nasty WHILE 1=1 statement? Or is it a necessary sacrifice?

*Bonus (subjective) question:

Although the WHILE 1=1 bit from the second boilerplate isn't very pretty, I think I prefer it a lot over duplicating the FETCH statement. Any insights as to why the first boilerplate is much more prominent / widespread? Am I missing a major advantage of the first snippet?

1 Taken / adapted from the 70-461 exam training kit.


texts:
I am starting to learn ASP.NET, and I am designing a page for an admin to login and do some stuff. I have the username and password for the admin stored in Web.config (Is that a good practice?).

Second thing, I am checking if the user filled the username and password fields, then I am checking if the values for the admin and password exist in the web.config, then I am checking if these values equal each other, so I am having 3 nested if. Is that a good practice as well?

Here's my code:

if (!string.IsNullOrEmpty(txtLoginId.Text) && !string.IsNullOrEmpty(txtPassword.Text))
            {
                string configLoginID = WebConfigurationManager.AppSettings["AdminLoginID"];
                string configPassword = WebConfigurationManager.AppSettings["AdminPassword"];
                if (!string.IsNullOrEmpty(configLoginID) && !string.IsNullOrEmpty(configPassword))
                {
                    if (txtLoginId.Text == configLoginID && txtPassword.Text == configPassword)
                    {
                        Session["ShoppingAdmin"] = "ShoppingAdmin";
                        Response.Redirect("~/Admin/AddNewProducts.aspx");
                    }
                    else
                    {
                        lblAlert.Text = "Incorrect Username/Password";
                    }

                }
            }
            else
            {
                lblAlert.Text = "Please enter a usernamd and password";
            }

Last thing, checking empty fields using !string.IsNullOrEmpty for each field, is that the right thing to do?

I would like to write a clean code, thanks for helping me with these 3 cases.


texts: Populating and saving checkboxlist items to the database

texts:
I have inherited an application that has code to save and populate values in an ASP.NET checkboxlist control. The existing code is very lengthy and does not appear to be efficient to me. I plan on rewriting this application and have complete control over the database design.

All of the checkboxlist items are stored in an SQL table as bit fields. Each row of checkboxlist values are assigned to a user ID. Once again, my goal is to find a more efficient way to save and populate selected checkboxlist items with less code. I'm open to changing the table design, using Linq or lambda if it helps.  I'm new to ASP.NET but there must be a better way of doing this.

Current table design
UserID  AA  BC  AC
1       1    1  0
2       0    1  1
3       1    1  0
4       1    1  1

'Code to populate selected checkboxlist items(there are a total of 22 bit values)

Dim CodeData as datarow
CodeData = CodeDataTable.Rows(0)
For Each li As ListItem In Me.cblCodes.Items
                    If li.Text = "AA" Then
                       If Not CodeData.IsOneNull Then
                          If CodeData.One = True Then
                               li.Selected = True
                        End If
                    End If
                End If
                  If li.Text = "BC" Then
                    If Not CodeData.IsTwoNull Then
                        If CodeData.Two = True Then
                            li.Selected = True
                        End If
                    End If
                End If
         If li.Text = "AC" Then
                    If Not CodeData.IsTwoNull Then
                        If CodeData.Two = True Then
                            li.Selected = True
                        End If
                    End If
                End If
            ......

Next

'Code to save checkboxlist values
 Dim AA As Boolean = False
 Dim BC As Boolean = False
 Dim AC As Boolean = False
 Dim AD As Boolean = False

 AA = Me.cblCodes.Items.FindByText("AA").Selected()
 BC = Me.cblCodes.Items.FindByText("BC").Selected
 AC = Me.cblCodes.Items.FindByText("AC").Selected
 AD = Me.cblCodes.Items.FindByText("AD").Selected

 CodeTableAdapter.UpdateCodes(UserID,AA,BC,AC,AD.......)


texts:
I implemented the Fibonacci sequence using iterate.

import Data.List

fib :: Int -> Maybe Int
fib n
 | n < 0     = Nothing
 | otherwise = (fmap (snd . fst)) $ find (\(_,i) -> n == i) (zip res [0..])

res :: [(Int, Int)]
res = iterate f (0,1)

f :: (Num a, Num b) => (a, a) -> (a, a)
f (x, y) = (y,x+y)

Testing

> fib (-1)
Nothing
> fib 0
Just 1
> fib 2
Just 2
> fib 3
Just 3
> fib 4
Just 5
> fib 5
Just 8
> fib 6
Just 13

Please review it.


texts:
This class creates dynamic input labels.  You give it a pair of elements and it sets up the event listeners and CSS toggles to accomplish this.

Looking for feedback on code structure and correctness.

Toggle classes do what they say, they toggle one class on and another class off.

/***************************************************************************************************
**SDynInput - provides dynamic input for labels and borders
*/
    var SDynInput = $A.Class.create({
        Name: 'SDynInput',
        A: {

            // CSS classes used to toggle the label
            toggle_label_hide:       'toggle_label_hide',
            toggle_label_obscure:    'toggle_label_obscure',
            toggle_label_show:       'toggle_label_show',

            // CSS classes used to toggle the border
            toggle_border_hide:      'toggle_border_hide',
            toggle_border_obscure:   'toggle_border_obscure',
            toggle_border_show:      'toggle_border_show',

            // speed of label expanding
            speed:                   200
        },

        // elements are passed in as input/label pairs
        set: function (pair_array) {
            var index;
            for (index = 0; index < pair_array.length; index += 2) {
                this.applyEL(pair_array[index], pair_array[index + 1]);
            }
        },

        // apply event listeners to the input elements
        applyEL: function (input_element, label_element) {
            var self = this;
            input_element.addEventListener("blur", function () {
                if (input_element.value === '') {
                    $A.addClass(input_element, self.A.toggle_border_show);
                    $A.addClass(label_element, self.A.toggle_label_show);
                    $A.expandFont(label_element, 'up', self.A.speed);
                }
            }, false);
            input_element.addEventListener("focus", function () {
                if (input_element.value === '') {
                    $A.addClass(input_element, self.A.toggle_border_obscure);
                    $A.addClass(label_element, self.A.toggle_label_obscure);
                }
            }, false);
            input_element.addEventListener("paste", function () {
                $A.addClass(label_element, self.A.toggle_label_hide);
                $A.addClass(input_element, self.A.toggle_border_hide);
            }, false);
            input_element.addEventListener("keypress", function () {
                $A.addClass(label_element, self.A.toggle_label_hide);
                $A.addClass(input_element, self.A.toggle_border_hide);
            }, false);
            input_element.addEventListener("drop", function () {
                $A.setTimeout(function () {
                    $A.addClass(label_element, self.A.toggle_label_hide);
                    $A.addClass(input_element, self.A.toggle_border_hide);
                }, 0);
            }, false);
        }
    }, true);


texts: Why is this divide and conquer algorithm inefficient?

texts:
I was solving one of the problem in USACO 2007 Open Silver:

  Description

  Farmer John has taken his cows on a trip to the city! As the sun sets, the cows gaze at the city horizon and observe the beautiful silhouettes formed by the rectangular buildings.

  The entire horizon is represented by a number line with \$N (1 ≤ N ≤ 40,000\$) buildings. Building \$i\$'s silhouette has a base that spans locations \$Ai\$ through \$Bi\$ along the horizon \$1 ≤ Ai < Bi ≤ 1,000,000,000\$ and has height \$Hi\$ (\$1 ≤ Hi ≤ 1,000,000,000\$).

  Determine the area, in square units, of the aggregate silhouette formed by all \$N\$ buildings.

  Input

  Line 1: A single integer: N
  Lines 2...N+1: Input line i+1 describes building \$i\$ with three space-separated integers: \$Ai\$, \$Bi\$, and \$Hi\$.

  Output

  Line 1: The total area, in square units, of the silhouettes formed by all \$N\$ buildings

  Sample Input

4

2 5 1

9 10 4

6 8 2

4 6 3

  Sample Output

16

I used a divide-and-conquer algorithm to solve this problem, but failed. The feedback of the online judgement system is Time Limit Exceeded. Could you help me to make my code more efficient, readable, and clear?

#include <stdio.h>
#include <malloc.h>

#define INF 10000000000

enum {MAX = 2, DIM = 3};

typedef struct Outline Outline;
struct Outline {
    int pos;
    int height;
};

/* merge two outlines of buildings */
Outline *mergebuilding(Outline *a, Outline *b, int num)
{
    int a_move = 0;
    int b_move = 0;
    int r_count = 0;
    int r_move = 0;
    int pre = -1;
    int x = 0;
    int y = 0;
    Outline *r = (Outline *) malloc(MAX * num * (sizeof(Outline)) + sizeof(Outline));

    while (a[a_move].pos < INF || b[b_move].pos < INF) {
        r[r_move].pos = (a[a_move].pos <= b[b_move].pos) ? a[a_move].pos : b[b_move].pos;
        if (r[r_move].pos == a[a_move].pos) {
            x = a[a_move].height;
            a_move++;
        }

        if (r[r_move].pos == b[b_move].pos) {
              y = b[b_move].height;
             b_move++;
        }

        r[r_move].height = (x >= y) ? x : y;

        if (r[r_move].height != pre) {
            pre = r[r_move].height;
            r[r_move+1] = r[r_move];
             r_move++;
        }
    }
    r[r_move].pos = INF;

    return r;
}

/* divide-and-conquer */
Outline *recursive(Outline **p, int low, int high)
{
    /*
    Recursively divide the set of buildings into two parts
    until one block, then merge two blocks from the bottom to the top.
    */
    Outline *part1, *part2, *merge;
    int mid;

    if (low == high)
        return p[low];

    mid = (low + high) / 2;
    part1 = recursive(p, low, mid);
    part2 = recursive(p, mid+1, high);
    merge = mergebuilding(part1, part2, low+high+1);

    free(part1);
    free(part2);

     return merge;
}

int main()
{
    int **bul;
    int num;
    Outline **p, *cp;

    scanf("%d", &num);
    bul = (int **) malloc(num * sizeof(int));
    p = (Outline **) malloc(num * sizeof(Outline));

    for (int i = 0; i < num; i++) {
        bul[i] = (int *) malloc(DIM * sizeof(int));
        p[i] = (Outline *) malloc(DIM * sizeof(Outline));

        scanf("%d %d %d", &bul[i][0], &bul[i][1], &bul[i][2]);

        p[i][0].pos = bul[i][0];
        p[i][0].height = bul[i][2];
        p[i][1].pos = bul[i][1];
        p[i][1].height = 0;
        p[i][2].pos = INF;
        free(bul[i]);
    }
    free(bul);

    cp = recursive(p, 0, num-1);

    free(p);

    int temp, square;
    square = 0;

    for (int i = 0; cp[i].pos < INF; i++) {
        temp = (cp[i+1].pos - cp[i].pos) * cp[i].height;
        square += temp;
    }
    printf("%d\n", square);
    free(cp);

    return 0;
}


texts: Conditional logic to determine if popup menu should be visible

texts:
I have this small piece of code written in a class. I am looking for a nicer way to write this, preferably avoiding nested if statements like what I currently have:

@Override
  public void popupMenuWillBecomeVisible(PopupMenuEvent e)
  {
    TheatreListDataWrapper[] selectedOperations = getSelectedDatas();
    boolean isOperationFromMulitpleSoc = TheatreListDataWrapper.operationsOfMultiplePatients(selectedOperations);
    if (!isOperationFromMulitpleSoc)
    {
      //passing boolean literal value 'false' instead of variable 'isOperationFromMultipleSoc' since that,
      //at this point it is certain that the operations selected are from a single patient
      CambioAction attentionSignalAction = AttentionSignalDelegator.getAttentionSignalAction(false,selectedOperations);
      if (attentionSignalAction != null)
      {
        if (Framework.getInstance().getActiveSubjectOfCare().id == null
            || !getAcuteListTable().getTableDataByRow(getAcuteListTable().getSelectedRow()).socId.equals(Framework
                .getInstance().getActiveSubjectOfCare().id))
        {
          attentionSignalAction.setEnabled(false);
        }
        else
        {
          attentionSignalAction.setEnabled(true);
        }
      }
    }

    if(selectedOperations != null && selectedOperations.length > 1){
        listRegistraionOpenMenuItem.setEnabled(false);
    }else{
        listRegistraionOpenMenuItem.setEnabled(true);
    }
  }

For me, using that last if checking seems like, I could do it in a better way, using a switch or some other control structure. Is there a way to avoid the null checks?


texts:
I wrote a function to reverse a char-array (string).
Since I'm beginner and didn't work with malloc and stuff before, maybe someone could take a look, if this is fine, what I'm doing here?

char* reverse_string(char* string)
{
    // getting actual length of the string
    size_t length = strlen(string);

    // allocate some space for the new string
    char* new_string = malloc(sizeof(char)*(length+1));

    // index for looping over the string
    int actual_index = 0;

    // iterating over the string until '\0'
    while(string[actual_index] != '\0')
        new_string[length-actual_index-1] = string[actual_index++];

    // setting the last element of string-array to '\0'
    new_string[length] = '\0';

    // free up the allocated memory
    free(new_string);

    // return the new string
    return new_string;
}


texts:
This is my C++ program. I wanted to print out Pascal's triangle. I let the user decide how many rows to print out. The first row is considered as 0, and is just:

  1

I'm using vectors for this task. I think that I do not have to store the full triangle as that would take up too much extra space. I just store the previous row and the next one. I use the SetRow() function to determine the numbers in the next row based on the numbers in the previous row. Then each row is printed out. Please give me some feedback on my code. Is it an effective way to approach this problem? Does my code have any "bad programming practices"? What would you have done differently?

#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::cin;
using std::endl;

void SetRow(vector<int> &old_row, vector<int> &new_row, int row);

int main() {
  int n_num;
  cout << "What row of Pascal's triangle do you want to go up to?" << endl;
  cin >> n_num;
  cout << endl;

  vector <int> row_1 = {1};
  vector <int> row_2;
  vector <int> curr_row;

  cout << row_1.at(0) << endl;

  // loop through all the rows
  for (int i = 1; i < (n_num + 1); i++) {
    if (i % 2 == 1) {
      SetRow(row_1, row_2, i);
      curr_row = row_2;
    } else if (i % 2 == 0) {
      SetRow(row_2, row_1, i);
      curr_row = row_1;
    }
    for (auto k: curr_row) {
      cout << k << ' ';
    }
    cout << endl;
  }

  // This ends the program
  return 0;
}

void SetRow(vector<int> &old_row, vector<int> &new_row, int row) {
  new_row.clear();
  new_row.push_back(1);
  for (int i = 0; i < (row - 1); i++) {
    new_row.push_back(old_row.at(i) + old_row.at(i + 1));
  }
  new_row.push_back(1);
}


texts:
I'm building a database on Microsoft SQL server to teach myself SQL. I am a big UFC fan so I'd like to build a database on UFC fighters. I'm building two tables [fight] and [fighter]. The [fighter] table will have stats like weight, height, birthday, etc. as well as a column for wins, losses, draws, and NC (no contest). The [fight] table will have a winner_id column and a loser_id column as well as is_draw and is_nc columns.

How can I best create a link between the winner_id/loser_id columns from the [fight] table to the wins and losses columns for the [fighter] table?

There is one caveat. Usually MMA fighters will come to the UFC with experience in other organizations. So they will already have a record of wins and losses prior to the UFC. My database will only record UFC fights. So I can't have those previous wins and losses in the [fight] table. For that reason, I've decided to use triggers for now.

Here is the trigger I have created. My question is, is there a better way to do this other than triggers? I'm thinking setting the wins column = a base number + the number of times their fighter_id is listed in the winner_id column. But how would I do that? Would I need to use a view?

CREATE TRIGGER tr_fight_ResultUpdateFighter
ON fight
FOR INSERT
AS
BEGIN
    DECLARE @winner_id int
    DECLARE @loser_id int
    DECLARE @is_draw bit
    DECLARE @is_nc bit
    SELECT
        @winner_id = winner_id,
        @loser_id = loser_id,
        @is_draw = is_draw,
        @is_nc = is_nc
        FROM inserted

    --Wins
    UPDATE fighter
    SET wins = wins+1
    WHERE fighter_id = @winner_id

    --Loss
    UPDATE fighter
    SET losses = losses+1
    WHERE fighter_id = @loser_id

    --Draw
    UPDATE fighter
    SET draws = draws +
        CASE
            WHEN @is_draw = 1
            THEN 1
            ELSE 0
        END
    WHERE fighter_id = @winner_id
    AND fighter_id = @loser_id

    --NC
    UPDATE fighter
    SET nc = nc +
        CASE
            WHEN @is_nc = 1
            THEN 1
            ELSE 0
        END
    WHERE fighter_id = @winner_id
    AND fighter_id = @loser_id

END


texts: Powershell Script for setting DHCP reservation description & host value

texts:
I'm new to Powershell scripting and trying to write a script that will go through printer queues on a print server, get the print queue's port address, then compare the print queues port address to the DHCP reservation associated with the print queue port address on the server. If the port address of the print queue compares, it should then set the description of the DHCP reservation to reflect the print queue name and location. It should then also set the hostname option to be the print queue's name.

#Set DHCP reservation description and host value on server

#DHCP Server for site
$DHCPSvr = "Server1"

#DHCP Server Scope ID
$DHCPSvrScope = "10.224.148.0"

#Get Printer Management list of shared available printers
$PrinterObjects = Get-Printer -ComputerName Server1 * | Select-Object Name, PortName, Shared, Location |
                  Where-Object { ($_.Name -match "^.{6}$") -and ($_.PortName -match "IP*" -or $_.PortName -match '^10*') -and ($_.Shared -EQ $True)} |
                  Sort-Object -Property PortName -Descending

#Get DHCP Reservation list from server
$DHCPSvrReservations = Get-DhcpServerv4Reservation -ComputerName $DHCPSvr -ScopeId $DHCPSvrScope

foreach ($DHCPSvrReservation in $DHCPSvrReservations){
    foreach ($PrinterObject in $PrinterObjects)
       {
        if ($DHCPSvrReservation.IPAddress -eq $PrinterObjects.PortName)
            {
                {Set-DhcpServerv4Reservation -ComputerName $DHCPSvr -IPAddress $PrinterObjects.PortName -Description "$PrinterObjects.Name & $PrinterObjects.Location"}
                {Set-DhcpServerv4OptionValue -ScopeId $DHCPSvrScope -OptionId 12 $PrinterObjects.Name}
            }
    }
}

I'm a bit unsure of the following code within the IF statement, is this the right way to have the loop process the two commands?

{Set-DhcpServerv4Reservation -ComputerName $DHCPSvr -IPAddress $PrinterObjects.PortName -Description "$PrinterObjects.Name & $PrinterObjects.Location"}
{Set-DhcpServerv4OptionValue -ScopeId $DHCPSvrScope -OptionId 12 $PrinterObjects.Name}

Anyway, it would be good if someone could go over what I have at the moment and point out any issues with formatting and so on.


texts: Optimizing code from spectral subtraction algorithm

texts:
This is part of the code from a spectral subtraction algorithm.  I'm trying to optimize it for Android.

Matlab code:

function Seg=segment(signal,W,SP,Window)

% SEGMENT chops a signal to overlapping windowed segments
% A= SEGMENT(X,W,SP,WIN) returns a matrix which its columns are segmented
% and windowed frames of the input one dimentional signal, X. W is the
% number of samples per window, default value W=256. SP is the shift
% percentage, default value SP=0.4. WIN is the window that is multiplied by
% each segment and its length should be W. the default window is hamming
% window.
% 06-Sep-04
% Esfandiar Zavarehei

if nargin<3
    SP=.4;
end
if nargin<2
    W=256;
end
if nargin<4
    Window=hamming(W);
end
Window=Window(:); %make it a column vector

L=length(signal);
SP=fix(W.*SP);
N=fix((L-W)/SP +1); %number of segments

Index=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))';
hw=repmat(Window,1,N);
Seg=signal(Index).*hw;

Java code:

public class MatrixAndSegments
{
    public int numberOfSegments;
    public double[][] res;

    public MatrixAndSegments(int numberOfSegments,double[][] res)
    {
        this.numberOfSegments = numberOfSegments;
        this.res = res;
    }
}

public MatrixAndSegments segment (double[] signal_in,int samplesPerWindow, double        shiftPercentage, double[] window)
{
    //default shiftPercentage = 0.4
    //default samplesPerWindow = 256  //W
    //default window = hanning

    int L = signal_in.length;
    shiftPercentage = fix(samplesPerWindow * shiftPercentage); //SP
    int numberOfSegments = fix ( (L - samplesPerWindow)/ shiftPercentage + 1); //N

    double[][] reprowMatrix =  reprowtrans(samplesPerWindow,numberOfSegments);
    double[][] repcolMatrix = repcoltrans(numberOfSegments, shiftPercentage,samplesPerWindow );

    //Index=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))';
    double[][] index = new double[samplesPerWindow+1][numberOfSegments+1];

    for (int x = 1;  x < samplesPerWindow+1; x++ )
    {
        for (int y = 1 ; y < numberOfSegments + 1; y++) //numberOfSegments was 3
        {
             index[x][y] = reprowMatrix[x][y] + repcolMatrix[x][y];
        }
    }

    //hamming window
    double[] hammingWindow = this.HammingWindow(samplesPerWindow);
    double[][] HW = repvector(hammingWindow, numberOfSegments);

    double[][] seg = new double[samplesPerWindow][numberOfSegments];
    for (int y = 1 ; y < numberOfSegments + 1; y++)
    {
        for (int x = 1; x < samplesPerWindow+1; x++)
        {
            seg[x-1][y-1] = signal_in[ (int)index[x][y]-1 ] * HW[x-1][y-1];
        }
    }
    MatrixAndSegments Matrixseg = new MatrixAndSegments(numberOfSegments,seg);
    return Matrixseg;

}

public int fix(double val) {
    if (val < 0) {
        return (int) Math.ceil(val);
    }
    return (int) Math.floor(val);
}

public double[][] repvector(double[] vec, int replications)
{
    double[][] result = new double[vec.length][replications];

    for (int x = 0; x < vec.length; x++) {
        for (int y = 0; y < replications; y++) {
            result[x][y] = vec[x];
        }
    }

    return result;
}

public double[][] reprowtrans(int end, int replications)
{
    double[][] result = new double[end +1][replications+1];

    for (int x = 1; x <= end; x++) {
        for (int y = 1; y <= replications; y++) {
            result[x][y] = x ;
        }
    }

    return result;
}

 public double[][] repcoltrans(int end, double multiplier, int replications)
{
    double[][] result = new double[replications+1][end+1];

    for (int x = 1; x <= replications; x++) {
        for (int y = 1; y <= end ; y++) {
            result[x][y] = (y-1)*multiplier;
        }
    }

    return result;
}

 public double[] HammingWindow(int size)
{
    double[] window = new double[size];
    for (int i = 0; i < size; i++)
    {

        window[i] =  0.54-0.46 * (Math.cos(2.0 * Math.PI * i / (size-1)));
    }
    return window;
}


texts: A proxy replacement for getters and setters

texts:
Have you ever written proxy objects, instead of using a setter and a getter method? In that case, I'm interested in your opinion on the following design for a templated proxy:
#include <type_traits>
#include <utility>

template <typename Handle, typename Getter, typename Setter>
class proxy {
public:
    using value_type = decltype(std::declval<Getter>()(std::declval<Handle>()) );
    operator value_type() const { return getter_(handle_); }
    proxy& operator=(const value_type& x) { setter_(handle_, x); return *this; }
    proxy& operator=(const value_type&& x) { setter_(handle_, x); return *this; }
    proxy(Handle handle, const Getter& getter, const Setter& setter) :
    handle_(handle), getter_(getter), setter_(setter) { }
protected:
    const Handle handle_;
    const Getter& getter_;
    const Setter& setter_;
};

// Allows for template argument deduction during "construction" - before C++17
template <typename Handle, typename Getter, typename Setter>
proxy<Handle, Getter, Setter>
make_proxy(const Handle& handle, const Getter& getter, const Setter& setter)
{
    return proxy<Handle, Getter, Setter>(handle, getter, setter);
}

Simple example of use:
int my_getter(int *x) { return *x; }
void my_setter(int *x, int val ) { *x = val; }

class foo {
public:
    auto datum() {
        return make_proxy(&x, my_getter, my_setter);
    }
protected:
    int x { 123 };
};

int main() {
    foo my_foo;
    my_foo.datum() = 456;
    return my_foo.datum();
}

GodBolt
(in this example, the getter and setter aren't really necessary because the "raw" field exists. But think about opqaue operating-system resources, or individual bits in a bit-container etc.)

Other than general comments on the design - I was also thinking about the choice of template parameters. I might be able to drop the Handle type - if I could manager to extract that information from Getter; or alternatively, I could add the value_type as a template parameter - as otherwise it could be confusing to the person seeing an instantiation to understand what type they should actually use with the proxy.
Also, I was wondering whether I should provide comparators (seeing how this class is convertible to value_type's, which we should be able to compare).
Finally, I was also thinking of not keeping the getter_ and setter_ at all, and only instantiating them on use. But I'm worried this will make the class too convoluted to write and/or use.
Note: This needs to be C++11-compatible.


texts:
Here is MaxHeap implementation in pure JavaScript:

/**
 * We initialize index 0 because, calculations for finding
 * children of a node and the parent of a node is easier
 * parent = [ k/2 ], children: [ k*2, k*2+1 ]
 */
class Heap {
    constructor() {
        this.queue = [0];
    };

    /**
     * Bottom-up reheapify (swim) : If the heap order is violated because a node's key
     * becomes larger than that node's parents key, then we can make progress
     * toward fixing the violation by exchanging the node with its parent
     *
     * @param {Number} k
     */
    swim(k) {
        while ( k>1 && this.less(k, Heap.flr(k/2)) ) {
            this.exch(k, Heap.flr(k/2) ) ;
            k = Heap.flr(k/2);
        }
    };

    /**
     * Top-down heapify (sink) :  If the heap order is violated because a node's key becomes
     * smaller than one or both of that node's children's keys, then we can make progress
     * toward fixing the violation by exchanging the node with the larger of its two children.
     *
     * @param {Number} k
     */
    sink(k) {
        while ( 2*k <= this.n() ) {
            const c1 = 2*k;
            const c2 = 2*k + 1;
            const j = this.more(c1,c2)?c2:c1;

            if (this.more(k, j) ) {
                this.exch(k, j);
            } else {
                break;
            }
            k = j;
        }
    };

    /**
     *
     * @param {Number} i
     * @param {Number} j
     */
    less(i,j) {
        return this.queue[i]>this.queue[j];
    };

    /**
     *
     * @param {Number} i
     * @param {Number} j
     */
    more(i,j) {
        return this.queue[i]<this.queue[j];
    };

    /**
     *
     * @param {Number} i
     * @param {Number} j
     */
    exch(i, j) {
        const tmp = this.queue[i];
        this.queue[i] = this.queue[j];
        this.queue[j] = tmp;
    };

    /**
     * Inserts element into the internal queue
     * @param {Number} k
     */
    insert(k) {
        this.queue.push(k);
        this.swim(this.n());
    };

    /**
     * Returns max element in the internal queue
     */
    max() {
        if (!this.isEmpty() ) {
            return this.queue[1];
        }
        return false;
    };

    /**
     * Deletes and returns max element from the internal queue
     */
    delMax() {
        if (!this.isEmpty()) {
            const mx = this.queue[1];
            this.queue[1] = this.queue.pop();
            if (!this.isEmpty()) {
                this.sink(1);
            }
            return mx;
        };
        return false;
    };

    /**
     * Checks for emptyness (here we consider the queue empty if the length of the queue is 1)
     */
    isEmpty() {
        return this.queue.length === 1;
    };

    /**
     * Returns last element index in the internal queue
     */
    n() {
        return this.queue.length-1;
    };

    /**
     * in JS dividing odd number by even number gives fraction not integer,
     * we need to get rid of this part
     * @param {Number} i
     */
    static flr(i) {
        return Math.floor(i);
    }
}

Is the implementation correct? What are the shortcomings that can be fixed?


texts: Go web application with a mock user repository

texts:
I'm new to go and struggling to create structure of web application. I read about clean architecture and Ben Johnsons blog post about package layout. Now i want to put it all together. This is just scratch. Service abstraction looks redundant but in real project there will be services that contains more than one repository. What is your opinion in structuring project like this? And how i bootstrap it together.

import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "strconv"
)

type user struct {
    name string
}

type userRepository interface {
    getByID(id int) (*user, error)
}

type userService struct {
    userRepository userRepository
}

func (us *userService) findUser(id int) (*user, error) {
    return us.userRepository.getByID(id)
}

type mockUserRepo struct{}

func (mr *mockUserRepo) getByID(id int) (*user, error) {
    return &user{"John Doe"}, nil
}

type safeHandlerFunc func(http.ResponseWriter, *http.Request) error

type mainHandler struct {
    //session
    //logger
    view *template.Template
}

func (h *mainHandler) handle(sh safeHandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("x-custom-header", "random")
        if err := sh(w, r); err != nil {
            //return some error view
            //log error
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    }
}

type userHandler struct {
    *mainHandler
    userService *userService
}

func (uh *userHandler) getUser(w http.ResponseWriter, r *http.Request) (err error) {
    sid := r.URL.Query().Get("user_id")
    id, err := strconv.Atoi(sid)
    if err == nil {
        return
    }

    u, err := uh.userService.findUser(id)
    if err != nil {
        return
    }
    return uh.view.ExecuteTemplate(w, "user.gohtml", u)
}

func main() {
    fmt.Println("Starting web server...")

    mock := new(mockUserRepo)

    h := &mainHandler{
        view: template.Must(template.ParseGlob("views/*")),
    }
    uh := &userHandler{h, &userService{mock}}

    http.HandleFunc("/", uh.handle(uh.getUser))
    log.Fatal(http.ListenAndServe(":8888", nil))
}


texts: Playframework (Scala) custom exception handling

texts:
I am using play framework with scala and here is a scenario on which I would like to have your opinion.

Let's say I have 2 custom exceptions that I can throw, which are EmailTaken and AuthFail. What I need to do here is, whenever any of these 2 exceptions happen, I need to return a json with 3 keys success, errorCode and message, in case of all other exceptions let Play's default error handling take charge. Now for all custom exceptions success will always be false, each exception would have a unique errorCode integer value and a unique message string both of which remain fixed for a particular exception.

Now I saw people using case class(they can be pattern matched) or class(saw some java examples) for exception but I didn't see the point of creating them because for any particular exception I don't see the point of creating more than 1 object because its attributes don't have to be changed (I could create a case class with all default parameters but why?). So I created an object for each exception and then I throw that exception object in the controller and then in the Global object I rely on the getCause of the exception.

// custom exceptions code

trait AppException extends Exception {

  val success = false
  def errorCode: Int
  def message: String

  override def fillInStackTrace(): Throwable = {
    this
  }
}

object EmailTaken extends AppException {
  val errorCode = 1
  val message = "email already used"
}

object AuthFail extends AppException {
  val errorCode = 2
  val message = "id/password dont match"
}

// in Play's controller

object Application extends Controller {
def test = Action {
    throw EmailTaken
    Ok("Test Page")
  }
}

// in Play's Global object

object Global extends GlobalSettings {

  override def onError(request: RequestHeader, ex: Throwable) = {
    ex.getCause match {
      case c: AppException =>     // a known custom exception
        Future.successful(InternalServerError(
          Json.toJson(Json.obj(
            "success"-> c.success,
            "message"-> c.message,
            "errorCode"-> c.errorCode
          ))
        ))
      case _ =>
        super.onError(request, ex)
    }
  }
}

I understand that if AuthFail was A case class I would have returned new AuthFail() and pattern matched on that exception object. Also, I could have used isInstanceOf[AppException] to check for custom exceptions. But are there any problems with this approach? Also, what are the other good approaches I can take? I don't have much experience with Scala or Java.


texts:
I need to write an IntArray implementation for college. I'm wondering if my code could be better and if it is efficient. In the header file are the methods listed that we need to write.

Header file:

 #ifndef INTARRAY_H_
 #define INTARRAY_H_

 #include <iostream>
 using namespace std;

 class IntArray{
 private:
     int length;
     int * data;
public:
    IntArray(int size = 0);
    IntArray(const IntArray& other);
    IntArray& operator=(const IntArray& original);

    int getSize() const { return length; };
    int& operator[](unsigned int i);
    void resize(unsigned int size);
    void insertBefore(int value, int index);

    friend ostream& operator<<(ostream& out, const IntArray& list);

    ~IntArray(){ delete[] data; };

 };
 #endif

Cpp file:

    IntArray::IntArray(int size){
        length = size;
        data = new int[size];
        for(int i = 0;i<size;i++){
             data[i] = 0;
        }
    }
    IntArray::IntArray(const IntArray& other){
        length = other.length;
        data  = new int[length];
        for(int i =0;i<length;i++){
        data[i] = other.data[i];
        }
    }

IntArray& IntArray::operator=(const IntArray& other){
    if(this = &other){
        return *this;
    }
    length = other.length;
    data = new int[length];
    for(int i = 0; i <length;i++){
        data[i] = other[i];
    }
    return *this;
}
void IntArray::resize(unsigned size){
      if (size <= length){
        length = size;
        return;
     }
     int * temparr = new int[size];
     // copy data
     for (int i = 0; i < length; ++i){
        temparr[i] = data[i];
     }
     delete [] data;
     data = temparr;
     length = size;
}

int& IntArray::operator [](unsigned i){
    if(i >= length || i < 0){
        throw "index out of bounds";
    }
    return data[i];
 }

 void IntArray::insertBefore(int d, int index){
     if(index >= length){
         throw "index out of bounds";
     }
     resize(length + 1);
     for(int i = length -1;i>index;i--){
          data[i] = data[i-1];
     }
     data[index] = d;
 }


texts: Can I use mapWriterT instead of mapM/mapM_ (Haskell)?

texts:
First off, I'm just learning Haskell and I'm not proficient in that language yet.

I wrote this Haskell module to look for files in a Linux filesystem. It can use regular expressions as search patterns. I wrote two variants: one of them sends the search results to stdout, the other (shown here) gives a list with the search results.

For example (in GHCi): searchToList "conf" "." >>= return . take 1 (being "." my home directory) would give [".config"]

I made the function searchWriterT recursive using mapM_, but I know there is mapWriterT in the module Control.Monad.Writer.

Could anyone give me a hint about what I shall do to replace mapM_ with mapWriterT (if it's possible)?

Thanks in advance.

module FileSearch where

import System.Directory (getDirectoryContents, doesDirectoryExist)
import Control.Monad (filterM, unless)
import Data.List ((\\))
import Text.Regex.Posix ((=~))
import Control.Monad.Writer

data Dir = Dir { path :: FilePath -- path of the current directory
               , files :: [FilePath] -- files in the directory
               , subdirs :: [FilePath] } -- subdirectories
               deriving (Show)

dontSearch :: [FilePath]
dontSearch = ["/proc", "/sys"]

-- listDir takes the name of a directory and gives a Dir with
-- that name, a list of the files in the directory and a list of
-- its subdirectories, all prefixed with the path of the current
-- directory.
-- listDir will list neither /proc nor /sys
listDir :: FilePath -> IO Dir
listDir f
    | f `elem` dontSearch = return Dir { path = f
                                       , files = []
                                       , subdirs = [] }
    | otherwise = do
        c' <- getDirectoryContents f
        let c = map (appendPath f) (deleteDot c')
        d <- filterM doesDirectoryExist c
        return Dir { path = f
                   , files = (c \\ d)
                   , subdirs = d }

appendPath :: FilePath -> FilePath -> FilePath
-- if the path is "/", do not add another "/"
appendPath "/" y = concat ["/", y]
appendPath x y = concat [x, "/", y]

-- remove "." and ".." entries in directories
deleteDot :: [FilePath] -> [FilePath]
deleteDot = filter (`notElem` [".", ".."])

searchWriterT :: String -> FilePath -> WriterT [FilePath] IO ()
searchWriterT s f = do
    d <- liftIO $ listDir f
    let found = filter (=~ s) (files d)
    tell found
    unless (null (subdirs d)) $
        mapM_ (searchWriterT s) (subdirs d)

searchToList :: String -> FilePath -> IO [FilePath]
searchToList s f = execWriterT (searchWriterT s f)


texts: Mersenne Prime Checker using Lucas-Lehmer Formula

texts:
Previously I created a C# script that used trial division to check to see whether or not certain Mersenne numbers were prime. Since these numbers are so big, I employed some math shortcuts to reduce the amount of division I needed to do. It was brought to my attention that using the Lucas-Lehmer formula would speed up the process significantly. Here's a link to the post I made before. Link

In this new script, I have included functions for two versions of the formula. The first is the original, while the second one uses bit shifting and is said to be more memory efficient and take fewer operations compared to the first.

using System;
using System.Numerics;

namespace Prime
{
    public class LucasLehmer
    {
        static int exp = 74207281;
        static BigInteger two = 2;
        static BigInteger mersenne = BigInteger.Pow(two, exp) - 1;

        public static void Main(string[] args)
        {
            for (int i = 0; true; i++)
            {
                LucasLehmerFuncBinary(exp, mersenne);
                exp++;
            }

        }

        private static void LucasLehmerFunc(int exp, BigInteger mersenne)                //regular lucas lehmer formula
        {
            BigInteger s = 4;
            BigInteger result = 0;

            for (int i = 0; i < (exp - 2); i++)
            {
                result = ((s*s) - 2) % mersenne;
                s = result;
                Console.WriteLine(i + " , " + s); //debug statement
            }

            if (result == 0)
            {
                Console.WriteLine("Two to the power " + exp + " minus one is prime.");
            }
            else
            {
                Console.WriteLine("Two to the power " + exp + " minus one is not prime.");
            }
        }
    }

    private static void LucasLehmerFuncBinary(int exp, BigInteger mersenne) //a more memory and time efficient binary modification of the formula
    {
        BigInteger s = 2;
        BigInteger result = 1;
        while (exp > 0)
        {
            if (exp % 2 == 1)
            {
                result = (result * s) % mersenne;
                Console.WriteLine("result length: " + result.ToString().Length); //debug statement
            }

            exp = exp >> 1;
            s = (s * s) % mersenne;
            Console.WriteLine("exp: " + exp); //debug statement
            Console.WriteLine("s: " + s.ToString().Length); //debug statement
        }

        if (result == 0)
        {
            Console.WriteLine("Two to the power " + exp + " minus one is prime.");
        }
        else
        {
            Console.WriteLine("Two to the power " + exp + " minus one is not prime.");
        }
    }
}

Concerning the lines

result = ((s*s) - 2) % mersenne;
result = (result * s) % mersenne;
s = (s * s) % mersenne;

all of these get incredibly big after just a few iterations.

I was thinking about using scientific notation to make the process of multiplying much easier because it's easier multiplying numbers in this form. Could anyone help me figure out how best to implement this?

Are there any other methods I could use to make it easier for a computer to do math with numbers that are, as it turns out, hundreds of thousands of digits long, if not millions?


texts:
I have a JSF project composed by some Maven Modules.

I have one module that needs to read and write some files on server. To do this I need to know the "real" full path of the application/server.

The way it is coded, only the View layer can access this information by this method:

public final static String getRealPath(String relativePath) {
    FacesContext fc = FacesContext.getCurrentInstance();
    ServletContext context = (ServletContext)fc.getExternalContext().getContext();

    return context.getRealPath(relativePath);
}

Can my module (not in View layer) call some Faces methods like FacesContext.getCurrentInstance()? Am I breaking some rule, layer or pattern? Or should I pass this path through all layers as a method parameter?


texts:
Hopefully this is not too complicated. I have this code that will generate a username based on the pre-configured schema the admin types in. The fields they can use are:

<first_initial>
<last_initial>
<first_name>
<last_name>
<role>

So, if my name were John Doe, and I had the role of "author" in the system, the function would translate these UsernameSchema thusly:

<first_name>.<last_name>         = john.doe
<first_intitial><last_name>      = jdoe
<first_name>.<last_name>-<role>  = john.doe-author
<last_initial>                   = d

Obviously, it needs to check for duplicates. Below is the working code I have (will be called either after_initialize or before_create (not sure which at this point):

  def set_username
    schema = UsernameSchema.where(:active => true).first! || "<first_initial><last_name>"
    fname = self.first_name
    lname = self.last_name
    finit = fname[0]
    linit = lname[0]
    urole = self.role
    # Question 2:
    replacement_dict = {"<first_initial>" => finit, "<last_initial>" => linit, "<first_name>" => fname, "<last_name>" => lname, "<role>" => urole}
    replacement_regex= /(<first_initial>)|(<last_initial>)|(<first_name>)|(<last_name>)|(<role>)/
    proposed_username = schema.gsub(replacement_regex, replacement_dict).downcase
    self.username = find_free_name(proposed_username)
  end

  # Question 3, IDE complains about next line
  def find_free_name(un)
    user = User.find_by_username(un)
    if user
      num = user.scan(/\d+$/).first
      if num
        new_num = num.to_i + 1
        next_user = un.gsub(num, new_num.to_s)
      else
        next_user = un + "1"
      end
      find_free_name(next_user)
    else
      un
    end
  end

I guess I have these concerns with my code:

Is this a dumb way of doing it?
Where my "Question 2" comment is in the above code, that seems redundant... is there a more succinct way?
My IDE says I'm doing it wrong (and I don't know what it wants):

  All custom “finds” accessed from more than one place in the code use
  named_scope instead of a custom method.


texts: Simple trie implementation in JavaScript

texts:
After experimenting with a sorted trie implementation in C, I felt that I understood tries pretty well, but was having trouble explaining how they work. Since the C code was based on existing code, I wanted to try it again in another language, from scratch.

Here's what I came up with. I tried to make it as minimal as possible. These tries aren't sorted, and nodes only reference a child and next node; parent and prev aren't used. I did give the "leaves" of the trie a name property, which is the full key. This isn't currently used, but it's useful for debugging, and it would be useful if a trie iterator were added (like Trie_dump from the question linked above).

I'm interested in feedback on the code itself this time, but not so much on things like white space, braces, semicolons, etc. I'm comfortable with the formatting the way it is. I'd be interested in an alternative to that labeled loop, though, and all other feedback is welcome.

Trie structure

Each node in the trie can have a key, a value, a next node, and a child node. In this diagram, each node is represented by a circle. The "root" node is at the left, the green "leaf" nodes are at the right, and the "branch" nodes are in the middle.

Each key is a single character (circled letters below). The "branches" have keys, while each "leaf" holds a value.

In the diagram, nodes appear to have multiple children. For example, the first "r" node has "u" and "o" children. Internally, nodes just have a child property; the first child. The next child is available in the first child's next property, and so on. It may help to think of child as "first child" and next as "next sibling."

trie.js

function Trie(parent, prev, key, value) {
    if (key !== void 0)
        this.key = key;      // single-character key
    if (value !== void 0)
        this.value = value;  // user-defined value
    if (prev)
        prev.next = this;    // next sibling node
    else if (parent)
        parent.child = this; // first child node
}

// put a key/value pair in the trie
Trie.prototype.put = function(name, value) {
    var i = 0, t = this, len = name.length, prev, parent;
    down: while (t.child) {
        parent = t;
        t = t.child;
        // if first child didn't match, get next sibling
        while (t.key != name[i]) {
            if (!t.next) {
                prev = t;
                t = parent;
                break down;
            }
            t = t.next;
        }
        // key already exists, update the value
        if (++i > len) {
            t.value = value;
            return;
        }
    }
    // found any existing parts of the key, add the rest
    t = new this.constructor(t, prev, name[i]);
    while (++i <= len)
        t = new this.constructor(t, null, name[i]);
    t.name = name;
    t.value = value;
};

// get a value from the trie at the given key
Trie.prototype.get = function(name) {
    var i = 0, t = this.child, len = name.length;
    while (t) {
        if (t.key == name[i]) {
            if (i == len)
                return t.value;
            t = t.child;
            ++i;
        } else {
            t = t.next;
        }
    }
};

Demos

Here are links to a few demos. The simple demo puts some test data in a trie, gets it back out, and dumps it to the console. The fancy demo puts the same test data in a trie and draws a diagram like the one above.

Simple demo: http://jsfiddle.net/4Yttq

Fancy demo: http://jsfiddle.net/4Yttq/1/


texts:
this is my code to implement DFS with recursion but no stack. I ran few test cases which turned out to be positive but wanted to check the efficiency of the code.

graph = {'A': set(['B', 'C']),
         'B': set(['A', 'D', 'E']),
         'C': set(['A', 'E']),
         'D': set(['B', 'F']),
         'E': set(['C', 'B', 'F']),
         'F': set(['D', 'E'])}
visited_nodes = set()
is_visited = {}
#seen_nodes = set()
seen_nodes = []

def unseen_neighbors(start_node):
    unseen = []
    for i in graph[start_node]:
        if is_visited.get(i, 'NA') == 'NA':
            unseen.append(i)
    print ('start node and unseen ', start_node, unseen)
    return unseen

def DFS(graph, start_node):
    is_visited[start_node] = True
    #seen_nodes.append(start_node)
    #print ('seen ', seen_nodes)
    #add_neighbors(start_node)
    unseen = unseen_neighbors(start_node)
    if len(unseen) == 0:
        return
    for i in unseen:
        if is_visited.get(i, 'NA') == 'NA':
            seen_nodes.append(i)
            DFS(graph, i)

if __name__ == "__main__":
    seen_nodes.append('A')
    DFS(graph, 'A')
    print ("DFS Traversal ", seen_nodes, set(seen_nodes))


texts: Logging util with static lambda function

texts:
So again, I am a bit confused about some notes that i'am getting from my reviewer. I have some kind of utils, to print/prepare log messages. Yea, maybe I am a bit fanatic java 8 lambda guy but I think it is still under control. :)

So its looks like that [I hide 'sensitive' data]

public class ExceptionUtils {

  private static final BiFunction<String, String, String> CUSTOM_EXCEPTION_MESSAGE_FORMAT =
    (typeOfError, typeOfEndpoint) -> "[XXX] " + typeOfError + " Error during process bulk " + typeOfEndpoint + " events. "
        + "Event "
        + "occurrences time: %d "
        + "event retry count: %d, "
        + "session: %s";

  public static String validationMessageException(String endpoint, long timestamp, int retryCount, String sessionToken) {
    return String.format(CUSTOM_EXCEPTION_MESSAGE_FORMAT.apply("Validation", endpoint), timestamp, retryCount, sessionToken);
  }

  public static String unknownMessageException(String endpoint, long timestamp, int retryCount, String sessionToken) {
    return String.format(CUSTOM_EXCEPTION_MESSAGE_FORMAT.apply("Unknown", endpoint), timestamp, retryCount, sessionToken);
  }
}


texts: Constructor start, destructor end timer in C++

texts:
The following is a short timing utility I've written for a larger project that I'm working on. The larger project is designed to be called (via ffi) from a Scala/Java codebase, which makes using standard profiling tools somewhat difficult - especially at the granularity that we want.

Essentially, we want to be able to track roughly how long a few key functions are taking, and we want a low overhead way of doing so. The following code is my implementation of a timer class that starts timing when constructed, and then finishes (and reports data) when it destructs.

I chose this way of doing things as it gives quite a succinct way of benchmarking a function, take for example, a function foo that we wanted to benchmark, all we would have to do is the following:

void foo(/*some arguments*/) {
  auto timer = CSDSTimer("foo", "example");
  /*do some more stuff*/
}

I think this is quite a nice solution, but I'd be interested in feedback on my implementation, especially of my handling of streams, and whether there's any way to set the stream statically (see the commented out code).

Thanks!

#pragma once

#include <chrono>
#include <ctime>
#include <iostream>

class CSDSTimer {

public:
  // Construct and start the timer
  CSDSTimer(std::string name, std::string context = "global",
            std::ostream &stream = std::cout)
      : _name(name), _context(context), _default_str(&stream) {
    _start = std::chrono::system_clock::now();
  }

  // Destruct and stop the timer, reporting the elapseed time
  ~CSDSTimer() {
    _end = std::chrono::system_clock::now();
    std::chrono::duration<double> elapsed_seconds = _end - _start;
    *_default_str << "PROFILING_DATUM(\"" << _name << "\", \"" << _context
                  << "\", " << elapsed_seconds.count() * 1000 << ", \"C++\")"
                  << std::endl;
  }

  // static void SetStream(std::ostream &str) { _default_str = &str; }

private:
  std::string _name;
  std::string _context;
  std::chrono::time_point<std::chrono::system_clock> _start, _end;
  std::ostream *_default_str;

  // static std::ostream *_default_str;
};


texts:
This question is the second version of the code here.

I'm writing a general tree class. Specifically, each node should have oen parent, some number of children, and hold a value.

I'm looking for general advice on how to make this code more idiomatic. I'm also looking for thoughts on the traverse function, any functions that should be present in a general tree class but aren't, and also any way to simplify the existing functions.

// Code to review
class Node {
 constructor(value = 0, children = []) {
  this.value = value;
  this.children = children;
 }

 traverse({ preorder, postorder, levelorder }) {
  if (levelorder) {
   let nodes = [this];
   while (nodes.length > 0) {
    const current = nodes.shift();
    levelorder(current);
    nodes = nodes.concat(current.children);
   }
  }
  else {
   if (preorder) preorder(this);
   this.children.forEach(n => n.traverse({ preorder, postorder }));
   if (postorder) postorder(this);
  }
  return this;
 }

 clone() {
  const copy = n => Object.assign(new Node(), n);
  let that = copy(this);
  that.traverse({ preorder: n => n.children = n.children.map(copy) });
  return that;
 }

 map(callback) {
  let that = this.clone();
  that.traverse({ levelorder: n => n.value = callback(n.value) });
  return that;
 }

 reduce(callback, initial) {
  let a = initial;
  this.traverse({ levelorder: n => a = (n === this && initial === undefined)? n.value: callback(a, n.value) });
  return a;
 }

 filter(callback) {
  let that = this.clone();
  that.traverse({ levelorder: n => n.children = n.children.filter(m => callback(m.value)) });
  return that;
 }

 every(callback) {
  return Boolean(this.reduce((a, b) => a && callback(b), true));
 }

 some(callback) {
  return Boolean(this.reduce((a, b) => a || callback(b), false));
 }

 find(callback) {
  return this.reduce((a, b) => (callback(b)? a.push(b): null, a), []);
 }

 includes(value) {
  return this.some(a => a === value);
 }
}

// Testing code
let tree = new Node(0);
let a = new Node(1);
let b = new Node(2);
let c = new Node(3);
let d = new Node(4);
let e = new Node(5);
let f = new Node(6);
tree.children = [a, b, c];
a.children = [d];
d.children = [e, f];

console.log("\nmap", tree.map(a => a + "2"));
console.log("\nreduce", tree.reduce((a, b) => String(a) + String(b)));
console.log("\nfilter", tree.filter(a => a < 3));

console.log("\nevery", tree.every(a => a < 3));
console.log("\nsome", tree.some(a => a < 3))

console.log("\nfind", tree.find(a => a > 2));
console.log("\nincludes", tree.includes(3));


texts: Store object in memory or de-reference it for performance

texts:
I have a GUI that contains a Table Object (for displaying columns of data) and a Table Model.  The Table Object contains the Table Model.

Is it better to store the Table Model as a object in the User interface or de-reference it as needed?  Is there any performance gain keeping it separate?  If there is, is it a good design to implement this?

For example:

public GUI {
    private Table table;
    private TableModel model;

    public UI() {
        this.table = new Table();
        this.model = table.getModel();
        }
        public void actionPerformed() {
           // Performance improvement
           // without having to de-reference it from table
           model.setRowLimit();
        }
    // OR
    public void actionPerformed() {
        // Slower but is it better OO Design
        table.getModel().setRowLimit();
    }
}

The GUI has 10 public methods exposed where the model could be updated or changed.


texts: Effecient Use Sieve of Eratosthenes algorithm

texts:
Given this as a the Problem Statement

  Given two numbers, find the sum of prime numbers between them, both
  inclusive.

  Input:

  The first line contains the number of test cases T. Each test case
  contains two space separated integers.

  Output:

  Print the answer on a new line for each case.

  Constraints:

  1 <= T <= 100

  1 <= a,b < 10^6

. Here is the working code of mine, that has been accepted.

class TestClass {

    public static void main(String args[] ) throws Exception {
        BufferedReader keyboard= new BufferedReader(new InputStreamReader(System.in));
        int t=Integer.parseInt(keyboard.readLine());

        while(t>0 && t<=100){
            String[] tempInt=keyboard.readLine().split(" ");
            int n=Integer.parseInt(tempInt[0]);
            int m=Integer.parseInt(tempInt[1]);

            int sum=primeSum(n,m);
            System.out.println(sum);
            t--;
        }
    }

private static int primeSum(int n, int m) {
        int sum=0;
        int maxFactor= (int)Math.sqrt(m);
        boolean[] isPrime=new boolean[m + 1];
        int len=isPrime.length;
        Arrays.fill(isPrime,true);
        isPrime[0]=false;
        isPrime[1]=false;
        for(int i=0;i<=maxFactor;i++){
            if(isPrime[i]){
                for(int j=i+i;j<len;j+=i){
                    isPrime[j]=false;
                }
            }
        }
        for(int i=n;i<=m;i++){
            if(isPrime[i]){
                sum=sum+i;
            }
        }
        return sum;
    }

}

But what is really bugging me is this line boolean[] isPrime=new boolean[m + 1];. Where i Have to use really large block of space. How could i avoid such large allocation while being effiecient too.? What are futher way of improvement of this code apart from array allocation ?


texts:
Ask user to input 10 integers and then print the largest odd number that was entered. If no odd number was entered, print a message to that effect.

I've written this code as my solution to the above exercise from chapter 2 of Computation and Programming Using Python by John Guttag. The book is meant to be used with Python 2.x. I need to know if the code can be "straightened up" in any way. So far, the book has covered variable assignment, print function, conditional branching, and loops.

largestOddNumber = None

for _ in range(10):  # '_' is a throw-away var
    number = int(raw_input('Enter an integer: '))
    if number % 2 != 0 and number > largestOddNumber:
        largestOddNumber = number

print largestOddNumber or 'No odd number was entered.'


texts: Watermark and join videos in bulk using ffmpeg

texts:
I have this batch file using ffmpeg to add a logo to my videos and then add an intro but it's taking anywhere from 10 hours to a day depending on how many I have to watermark, is there a more efficient way to achieve this? The videos sometimes have different resolutions so I can't remove the conversion to the 1280*720 size.

for %%I in ("C:\Users\Administrator\Desktop\work\*.mp4") do ffmpeg.exe -y -i "%%I" -i white.png -filter_complex "[0:v]scale=iw:ih[v0];[1:v][v0]scale2ref=iw/6:ih/18[logo][0v];[0v][logo]overlay=W-w-3:H-h-1[v]" -map "[v]" -map 0:a -codec:v libx264 -preset ultrafast -crf 23 -codec:a copy "C:\Users\Administrator\Desktop\Complete-videos\%%~nI.mp4"

for %%I in ("C:\Users\Administrator\Desktop\work\*.mp4") do ffmpeg -y -i %%I -c copy -vbsf h264_mp4toannexb -f mpegts -s 1280*720 %%I.ts && ffmpeg -y -i "concat:out1.ts|%%I.ts|out1.ts" -c:v libx264 -strict experimental -bsf:a aac_adtstoasc -ar 48000 -r 20 "C:\Users\Administrator\Desktop\Complete-videos\%%~nI.mp4"
pause


texts:
Following is my code to calculate gcd of two numbers. My intension is not to use any specialised algorithm, just simple maths. Do you see any problem in my solution?

#include <iostream>
#include <algorithm>

int main() {
    int n1, n2;

    std::cin >> n1 >> n2;

    int smaller = min(n1, n2);
    int greater = max(n1, n2);

    if(greater % smaller == 0)
    {
        std::cout << smaller;
        return 0;
    }

    int gcd = 1;

    for (int i = 2; i <= smaller / 2; i++) {
        if(smaller % i == 0 && greater % i == 0)
            gcd = i;
    }

    std::cout << gcd;
    return 0;
}


texts: Handling two datepickers in a form with angularjs

texts:
Here's I am using simple form with angularjs. Everything works fine. I am having watchgroup for EndDateFrom & EndDateTo datepickers. When it's defined I am logging the value to console. I am constructing an expression based on my if conditions if value is defined from datepickers, But i feel my code is little messy. Is there any better way to format this to make more simple.

I know we can't use switch case for this, but just checking if there is any other way to make less messy

$scope.$watchGroup(['$scope.EndDateFrom', '$scope.EndDateTo'], function () {

        if (!angular.isUndefined($scope.EndDateFrom) && !angular.isUndefined($scope.EndDateTo)) {

           return console.log(('expr://' + $filter('date')(new Date($scope.EndDateFrom), 'MM/dd/yyyy') + ' and ' + $filter('date')(new Date($scope.EndDateTo), 'MM/dd/yyyy')));
            // $scope.Test1 = 'expr://' + $filter('date')(new Date(disbursementsScheduleVm.processEndDateFrom), 'MM/dd/yyyy') + ' and ' + $filter('date')(new Date(disbursementsScheduleVm.processEndDateTo), 'MM/dd/yyyy');
        }
        else if(!angular.isUndefined($scope.EndDateFrom))
        {
            return console.log(('expr://' + $filter('date')(new Date($scope.EndDateFrom), 'MM/dd/yyyy')));
        }
        else if (!angular.isUndefined($scope.EndDateTo))
        {
            return console.log(('expr://' + $filter('date')(new Date($scope.EndDateTo), 'MM/dd/yyyy')));
        }

    });


texts: Searching for files in a specified directory

texts:
I am currently writing a program that allows me to search for files in a user-specified directory. My current code is as follows:

if os.path.exists(file_path)!= True:
    print('\n******* Path does not exist. *******\n')

else:
    while True:
        aa = '''\nWhich search characteristics would you like to use? \n 1. Search by name: N \n 2. Search by extension: E \n 3. Search by size: S
            \n    Please enter your choice: '''

        answer = input(aa).strip()

        if answer not in 'NnEeSs' or answer=='':
            print('\n***** Invalid choice. *****')

        elif answer in 'Nn':
            while True:
                try:
                    name = input ('\nEnter file name: ')
                    rr = search_by_name(name, file_path)
                    if not rr:
                        print('\n***** File not found *****\n')
                    else:
                        break

                except WindowsError:
                    print('\n***** Oops! Access denied.*****\n')
                    continue

        elif answer in 'Ee':
            while True:
                try:
                    ending = input ('\nEnter the file extension: ')
                    rr = search_by_extention(ending, file_path)
                    if not rr:
                        print('\n***** No File(s) found *****\n')
                    else:
                        break

                except WindowsError:
                    print('\n***** Oops! Access denied. *****\n')
                    continue

        elif answer in 'Ss':
            while True:
                try:
                    size = int(input('\nPlease enter file size: '))
                    rr = search_by_size(size, file_path)
                    if not rr:
                        print('\n***** No file(s) found *****\n')
                    else:
                        break

                except ValueError:
                    print('\n***** Enter an numeric value. *****\n')
                    continue

                except WindowsError:
                    print('\n***** Oops! Access denied. *****\n')
                    continue

Each of the search functions returns a list containing the result.

The try and except statements are concerning, and I feel they can be improved.

In each of these cases, or generally, how can the code be improved, or simplified?


texts: Unloading external DLL library after 10 seconds in order to release file locks

texts:
In my web application, I'm utilizing a PDF library which is using a native DLL.

I'm using it for two very different purposes in two completely separate (and isolated by NuGet) parts of the web application.

Upon application start, I load the library DLL and thus lock the file. Then, rebuild requires completely terminating the application which takes much time and disrupts our workflow.

We cannot load and unload the DLL on every operation, as the operation will be executed lots of times in bursts. This will also not be thread safe.

So in order to alleviate this, I have decided to make a small wrapper to the PDF library that:

for every operation (it will only have 2) it will check if the library is loaded.
If not, it loads it. After the operation, it sets a timer that will unload the DLL in, let's say 10 seconds.
If another operation is executed within this timeframe, the timer is reset.

This is the code I have written so far to achieve this, appreciate any pointers.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace PdfLibrary
{
    public static class PdfLibrary
    {
        static object Lock = new object();
        static TimeSpan Timeout = new TimeSpan(0, 0, 10);
        static bool IsLoaded = false;
        static Timer UnloadTimer = new Timer();

        static PdfLibrary()
        {
            UnloadTimer.Interval = Timeout.TotalMilliseconds;
            UnloadTimer.Elapsed += (_, __) => Unload();
        }

        private static void Unload()
        {
            UnloadTimer.Stop();

            lock (Lock)
            {
                // ... unloads pdf library ...
            }
        }

        static void DoWhenLoaded(Action action)
        {
            if (!IsLoaded)
            {
                lock (Lock)
                {
                    if (!IsLoaded)
                    {
                        // ... loads pdf library ...
                    }
                }
            }

            action();

            UnloadTimer.Stop();
            UnloadTimer.Start();
        }

        public static IEnumerable<string> ExtractText(Stream inputStream)
        {
            IEnumerable<string> result = null;

            DoWhenLoaded(() => {
                // ... sets result ...
            });

            return result;
        }
    }
}


texts: Refactored to use polymorphism in place of case statements

texts:
The purpose of the below code is to return different types of job objects based on an argument named "jobType."

The original code for the below methods was implemented as a switch statement. I refactored the code removing the switch statement, and in place creating different classes representing different types of jobs.

I would like feedback on my below implementation. The code works, and is released in production, but perhaps there is a better approach.

public bool RunNextJob()
    {
        //  Return true if we found a job to run
        DeferredJob dJob = _jobRepository.GetNextJob();
        SessionProvider sessionProvider = ObjectFactory.GetInstance<SessionProvider>();

        if(dJob != null)
        {
            Logger.Info(string.Format("Running job type: {0} Id: {1}", dJob.JobType, dJob.Id));
            dJob.ProcessedDate = DateTime.Now;
            _jobRepository.Update(dJob);
            sessionProvider.Flush();

            var jobType = new JobType();
            var job = jobType.GetJobType(dJob.JobType);

            if (job != null)
                job.RunJob(dJob);
        }

public class JobType : IJobType
{
    public IJob GetJobType(string jobTypeCode)
    {
        if(jobTypeCode == JobTypeToProcess.Notify.ToString())
            return new NotifyJob();

        if (jobTypeCode == JobTypeToProcess.ConflictedAppointmentMessageJobType.ToString())
            return new ConflictedAppointmentMessageJob();

        if (jobTypeCode == JobTypeToProcess.UnifiedExport.ToString())
            return new UnifiedExportReportJob();

        return jobTypeCode == JobTypeToProcess.FTPJobType.ToString() ? new FTPJob() : null;
    }
}


texts: Simulation for repeatedly taking gloves until a matching pair is found

texts:
I created the following code that simulates a person taking a random glove from a drawer until he/she gets a matching pair of gloves:

LinkedList<String> glovesList = new LinkedList<String>();
        LinkedList<String> matchList = new LinkedList<String>();
        Random rand = new Random();
        String[] glovesAvailable = {"red left", "red left", "red left", "red left", "red left",
                                    "red right", "red right", "red right", "red right", "red right",
                                    "yellow left", "yellow left", "yellow left", "yellow left",
                                    "yellow right", "yellow right", "yellow right", "yellow right",
                                    "green left", "green left", "green right", "green right"};

        // adding the gloves inside the list
        for(int i = 0; i < glovesAvailable.length; i++) {
            glovesList.add(glovesAvailable[i]);
        }

        // taking out the gloves from the drawer
        while(glovesList.size() != 0) {
            int n = rand.nextInt(glovesList.size());
            System.out.println("Removed a " + glovesList.get(n));
            matchList.add(glovesList.remove(n));
            if((matchList.contains("red left") && matchList.contains("red right")) ||
               (matchList.contains("yellow left") && matchList.contains("yellow right")) ||
               (matchList.contains("green left") && matchList.contains("green right"))) {
                System.out.println("Pair found!");
                break;
            }
        }

        // rechecking list if there are no more items
        System.out.println("Iterations till a matching pair is found: " + matchList.size());
        System.out.println("List of gloves taken out: " + matchList);
        System.out.println("Remaining gloves: " + glovesList.size());

The code works, but I am interested in making it more efficient. How can this code be improved?


texts:
I have started programming a couple of months ago and have recently applied for an internship. One of the assignments was to create a console application, the assignment can be seen here - > HERE

My implementation is this:

I have created an abstract class called DiscountCard which holds all the info, getters and setters, and has one abstract method of calculateDiscountRate.

public abstract class DiscountCard {

    private String owner;
    private int turnover;
    private int purchaseValue;
    private double discountRate;

    public DiscountCard(int turnOver, int purchaseValue){

        setTurnover(turnOver);
        setPurchaseValue(purchaseValue);

    }

    abstract void calculateDiscountRate();

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public int getTurnover() {
        return turnover;
    }

    public void setTurnover(int turnOver) {

        if(turnOver>=0) {
            this.turnover = turnOver;
        }else{
            System.out.println("Turnover can't be less than 0.");
        }

    }

    public int getPurchaseValue() {
        return purchaseValue;
    }

    public void setPurchaseValue(int purchaseValue) {

        if(purchaseValue>=0) {
            this.purchaseValue = purchaseValue;
        }else{
            System.out.println("Purchase value can't be less than 0.");
        }
    }

    public void setDiscountRate(double discountRate) {
        this.discountRate = discountRate;
    }

    public double getDiscountRate() {
        return discountRate;
    }
}

Then, there are 3 Card classes (Bronze,Silver,Gold) which implement the above class and override its abstract method:

 package com.test.DiscountCards;

    public class GoldDiscountCard extends DiscountCard {

        public GoldDiscountCard(int turnOver, int purchaseValue){

            super(turnOver,purchaseValue);
            calculateDiscountRate();
        }

        @Override
        void calculateDiscountRate() {

            setDiscountRate(2);

            setDiscountRate(getTurnover()/100 + getDiscountRate());

            if(getDiscountRate()>10){
                setDiscountRate(10);
            }

        }

    }

Next is the StoreCalculator Class which takes an instance of DiscountCard class and calculates the discount and total.

package com.test;

import com.practice.DiscountCards.DiscountCard;

public class StoreCalculator {

    private DiscountCard discountCard;

    public StoreCalculator(DiscountCard discountCard){
        this.discountCard = discountCard;
    }

    public double calculateDiscount(){
        return discountCard.getPurchaseValue() * discountCard.getDiscountRate()/100;
    }

    public double calculateTotal(){
        return discountCard.getPurchaseValue() - calculateDiscount();
    }
}

And at last i have a class that takes the info from DiscountCard class and Calculator class and prints it to a console.

import com.test.DiscountCards.DiscountCard;

public class PayDesk {

    public static void print(DiscountCard discountCard){

        StoreCalculator calculator = new StoreCalculator(discountCard);

        System.out.println("Purchase value: $"+ discountCard.getPurchaseValue() );
        System.out.println("Discount rate: "+ discountCard.getDiscountRate()+"%" );
        System.out.println("Discount: $"+ calculator.calculateDiscount() );
        System.out.println("Total: $"+ calculator.calculateTotal());

    }
}

My question is if this code implements OOP and is there something i should improve. I have send this code for a review to a company, i just want to know if there can be an improvement so i can learn more.


texts: Visualize the runtimes of list algorithms

texts:
I wrote a small script to visualize the runtimes of list algorithms.

The script works by creating a list of lists with sampled lengths from 1 to max_size. Next, I map the given algorithm over each list element and replaced the list with the resulting runtime. The runtimes of each list are plotted against the length of each list to generate a runtime plot.

My questions are:

Does my code deviate from best practices?
Could my code get a performance increase by using co-routines or some
other type of concurrency (like asyncio)?

from time import time
from random import randrange

from concurrent.futures import ThreadPoolExecutor
from functools import partial

from matplotlib import pyplot as plt

def func_timer(func, *params, verbose=False):
    """Takes in a function and some parameters to the function and returns the execution time"""

    start = time()
    func(*params)
    t = time() - start

    if verbose:
        print('function {func_name} took {time} seconds to complete given parameters'.format(
        func_name=func.__name__, time=t))
    return t

def list_generator(max_size, num_samples, n=10, upper_num=100):
    """Generates random integer lists with (sampled) lengths from range 1 to max_size.
    The difference between lengths (length spacing) of each list is delta, where delta is
    defined as the floor division of max_size and num_samples.

    max_size: int
    The max length of a generated list
    num_samples: int
    The number of lists to generate
    returns:
    lst_of_rand_lsts: list of lists
    """

    def get_rand_list(n):
        """Returns a  list of random numbers."""
        return [randrange(upper_num) for x in range(n)]

    assert max_size > num_samples
    delta = max_size // num_samples # uses the floor function to get difference between each sample.
    lst_lengths = [delta*x for x in range(1, num_samples + 1)] # Shift range by 1 to avoid making an empy list.

    return (get_rand_list(x) for x in lst_lengths)

def runtime_generator(func, lists):
    """Maps func over each list in a list of lists and replaces each list element with the function runtime."""

    partial_func_timer = partial(func_timer, func)

    with ThreadPoolExecutor(max_workers=5) as executor:
        res = executor.map(partial_func_timer, lists)

def rtviz(func, *args, max_size=1000, num_samples=500, viz=True, verbose=True):
    """Takes in a function that receives an iterable as input.
    Returns a plot of the runtimes over iterables of random integers of increasing length.

    func: a function that acts on an iterable"""

    def subplot_generator(lst_lengths, func_times_lst):
            plt.plot(lst_lengths, func_times_lst, 'bo')
            plt.xlabel('length of random lists')
            plt.ylabel('function runtime (sec)')
            plt.title('Runtime of function {}'.format(func.__name__))
            return

    lst_of_lsts = list(list_generator(max_size, num_samples))
    lsts_len = [len(elem) for elem in lst_of_lsts]

    start = time()
    runtime_gen = runtime_generator(func, lst_of_lsts)
    t = time() - start

    if verbose == True:
        print('%s took %0.3fms.' % (func.__name__, t*1000.))

    subplot_generator(lsts_len, list(runtime_gen))

    if viz == True:
        plt.show()

    return

if __name__ == "__main__":

    rtviz(sorted)


texts: Toggling dropdowns using jQuery, with binding and unbinding

texts:
This code is used to toggle some dropdowns. I've added the click event on the document to close the dropdown on click outside, but I'm not sure if I'm doing it the right way. I want it to be optimized for better performance.

Let me know if you have a better way to bind/unbind the events.

$('.header-top-bar .toggle').each(function (index) {
  var $this = $(this),
      $parent = $this.parent(),
      $dropdown = $this.siblings('.toggle-content');

  $this.on('click.toggle' + index, function (event) {
    event.preventDefault();

    $dropdown.toggleClass('isOpen');

    // Outside
    $document.on('click.toggle' + index, function (event) {
      if (!$(event.target).closest($parent).length) {
        $dropdown.removeClass('isOpen');
        $document.off('click.toggle' + index);
      }
    });
  });
});

jsFiddle


texts:
I have decided to go PDO and have started implementing it on one of my webprojects. I have limited programing skills but can usually pull it off with some tutorials and forums.

Here is my code this far and it works fine but how is the code correct regarding the picking up errors, syntax, order and begintransaction etc.? Have I missunderstood anything? Is anything unneccesary?

connect.php

 <?php
try {
    $DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password, array(
        PDO::ATTR_PERSISTENT => true
    ));
    $DBH -> exec("set names utf8");
}
catch(PDOException $e) {
    echo $e->getMessage();
}
?>

query.php

try {
        $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $DBH->beginTransaction();

        $STH = $DBH->prepare('SELECT id from users where uid = :uid');
        $STH->setFetchMode(PDO::FETCH_ASSOC);
        $STH->bindParam(':uid', $uid); // $uid value is set
        $STH->execute();

        $uid_in_db = $STH->rowCount();
        if($uid_in_db==0){ //=new user, insert info in db.
            $STH = $DBH->prepare("INSERT INTO USERS (uid,namn) VALUES (:uid, :name)");
            $STH->bindParam(':uid', $uid);
            $STH->bindParam(':namn', $_POST['namn']); // a value posted form user input
            $STH->execute();
        }

        $DBH->commit(); //

    } catch (Exception $e) {
        $DBH->rollBack();
        echo "Fel: " . $e->getMessage();
    }
}else{
    $error=1;
}