Search files from large directory and sub-directories Essentially I have a large directory with many sub-folders and different formats of files.  It reads through XML, JAVA, .txt, etc, in search of a selected String inputted by the user.  The results come back as snippets, reading a certain amount of characters previous and after the selected string has been found.

It does function as planned...I send the results as snippets and links to the main pages through REST calls via Spring and AJAX.  It does take about 5 - 7 seconds on a localhost server to return the results for a directory that is 19,405 Files, 9,610 Folders.

private ArrayList<String> pathNames = new ArrayList();
private HashMap<String, String> snippets = new HashMap<String, String>();

public HashMap readFiles(String search, String dirPath) {

    snippets.clear();
    InputStream stream = null;

    //Method to get all the files in main and sub folders
    listDirectory(dirPath);

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

        try {
            stream = new FileInputStream(pathNames.get(i));
            BufferedReader br = new BufferedReader(new    InputStreamReader(stream));

            Field chars = br.getClass().getDeclaredField("cb");
            chars.setAccessible(true);

            Field f = br.getClass().getDeclaredField("nChars");
            f.setAccessible(true);

            Field ff = br.getClass().getDeclaredField("nextChar");
            ff.setAccessible(true);

            String line;
            //not used
            int lineNum = 0;
            String path = pathNames.get(i);
            while ((line = br.readLine()) != null) {

                //Getting through to Java Source Code - uh oh

                // int charCount = (int) f.get(br);
                char[] cb = (char[]) chars.get(br);
                int nextChar = (Integer) ff.get(br);

                //not used
                lineNum++;

                if (line.contains(search)) {
                    String lines = "";
                    for (int t = nextChar - 200; t < nextChar + 100; t++) {
                        lines += cb[t];
                    }

                    snippets.put(pathNames.get(i), lines);

                }
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchFieldException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return snippets;
}

//not used
        int lineNum = 0;

            //not used
            lineNum++;

So it's in your code because...?

stream = new FileInputStream(pathNames.get(i));

and then later...

String path = pathNames.get(i);

You could assign to string variable first, and then make the inputstream from the string variable.

    } catch (FileNotFoundException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchFieldException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    }

Use multi-catch:

    } catch (FileNotFoundException | IOException | IllegalArgumentException | NoSuchFieldException | SecurityException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    }

Some of these might be subclasses and thus require removing. But there's no need to have the same line of code 6 times.

        Field f = br.getClass().getDeclaredField("nChars");
        f.setAccessible(true);

This field is unused as well.

                String lines = "";
                for (int t = nextChar - 200; t < nextChar + 100; t++) {
                    lines += cb[t];
                }

Consider declaring a char[] variable and using System.arraycopy. Strings are immutable, so whatever performance benefit you had with ripping open the BufferedReader, you completely waste it and then some here. You can then put the char[] into a new String.

snippets.put(pathNames.get(i), lines);

Why declare path if you're not going to use it?

Also, why do you not continue; here? HashMap.put will override any previous value, so you're only gonna see the last snippet of a file.

        stream = new FileInputStream(pathNames.get(i));
        BufferedReader br = new BufferedReader(new    InputStreamReader(stream));

None of these are getting closed.

Since you've got a try in there anyway, why not use try-with-resources?

String path = pathNames.get(i);
BufferedReader br;
try(stream = new FileInputStream(path);
        br = new BufferedReader(new InputStreamReader(stream))){
    ...
}

It works something like that.

private ArrayList<String> pathNames = new ArrayList();
private HashMap<String, String> snippets = new HashMap<String, String>();

Your variable definitions don't program to interfaces, so any setter would have to accept ArrayList only which makes your code hard to use for anyone else. Also, use diamond type inference - let the compiler get the generics from the type definition.

                char[] cb = (char[]) chars.get(br);
                int nextChar = (Integer) ff.get(br);

These reflection calls; you make them every iteration, but you only need them if the search string is found. Move them down.

Lastly, you should consider finding a way to get rid of the reflection. It's making the code slow, ugly and dangerous.

"Cleaned" version (will probably not compile; check syntax around try-with-resources and the multi-catch):

private List<String> pathNames = new ArrayList<>();
private Map<String, String> snippets = new HashMap<>();

public HashMap readFiles(String search, String dirPath) {

    snippets.clear();
    InputStream stream = null;
    BufferedReader br = null;

    //Method to get all the files in main and sub folders
    listDirectory(dirPath);

    for (int i = 0; i < pathNames.size(); i++) {
        String path = pathNames.get(i);
        try (stream = new FileInputStream(path);
            br = new BufferedReader(new InputStreamReader(stream))){

            Field chars = br.getClass().getDeclaredField("cb");
            chars.setAccessible(true);

            Field ff = br.getClass().getDeclaredField("nextChar");
            ff.setAccessible(true);

            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains(search)) {
                    //Getting through to Java Source Code - uh oh
                    char[] cb = (char[]) chars.get(br);
                    int nextChar = (Integer) ff.get(br);
                    char[] charBuffer = new char[300];
                    System.arraycopy(cb, nextChar - 200, charBuffer, 0, 300);
                    snippets.put(path, new String(charBuffer));
                    continue;

                }
            }

        } catch (FileNotFoundException | IOException | IllegalArgumentException | NoSuchFieldException | SecurityException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return snippets;
}


Finding multiples of 3 or 5 with MIPS assembly (Project Euler #1) I just started learning MIPS assembly at my university and I would like some feedback on this code. The program is Project Euler Problem #1, finding the sum of multiples of 3 or 5 less than 1000. It works but I am interested to hear what I could do to improve it (best practice, efficiency, etc). I found x86 solutions to this problem but it seems very different than MIPS.

$
# Testing.asm
    .text

main:

    li  $t0, 1000       # number of iterations
    li  $t1, 3          # starting number
    li  $t2, 0          # sum of multiples of 3 or 5
    li  $t6, 3          # constant of 3
    li  $t7, 5          # constant of 5

    loop:
    beq $t1, $t0, end   # end loop if iterator and number of iterations is equal
    div $t1, $t6        # divide iterator by 3
    mfhi    $t3         # $t3 is remainder of iterator divided by 3
    beq $t3, 0, equal       # if remainder is 0, go to equal label
    div $t1, $t7        # divide iterator by 5
    mfhi    $t3         # move remainder into $t3
    beq $t3, 0, equal       # go to equal if remainder is 0
    add $t1, $t1, 1     # increment iterator by 1
    j   loop

    equal:
    add $t2, $t2, $t1       # increment $t2 by iterator
    add $t1, $t1, 1     # increment iterator by 1
    j   loop            # jump back to loop

    end:
    move    $a0, $t2        # load answer into $a0
    li  $v0, 1          # set syscall to print_int
    syscall

    li  $v0, 10         # terminate program
    syscall

Your code is very clean and simplistic, which is a good thing. There is just one glaring problem that I see.

div
As you may already know, the div instruction is very slow instruction. I don't know precisely how slow, but on the x86 systems, the instruction has a latency of about 70.
A better solution would be to treat two registers as counters for the numbers 3 and 5. Here is what I mean by that:

Load register A with 3
Load register B with 5
Subtract 1 from A
Subtract 1 from B
If A == 0, increment the total by the iterator. Load A with 3 and go to step 3.
If B == 0, increment the total by the iterator. Load B with 5 and go to step 5.

By replacing these steps with the div instruction, your code will run significantly faster.

If you would like me to show you how your code would look with the above change, let me know in a comment.


Is this thread pool implementation OK? There are things that I am not 100% sure.
Is it possible that dangling references can be create in add_task method?
Is it possible that this implementation will deadlock?
I had to use shared_ptr in order to store packaged_task in the queue. Is there a better way to do it?
class ThreadPool {
public:
    ThreadPool(int number_of_workers) {
        for (int i=0; i<number_of_workers; ++i) {
            worker_threads.push_back(std::thread{std::bind(&ThreadPool::thread_func, this)});
        }
    }

    ~ThreadPool() = default;

    ThreadPool(const ThreadPool&) = delete;
    ThreadPool(ThreadPool&&) = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;
    ThreadPool& operator=(ThreadPool&&) = delete;

    template<typename Func, typename... Args>
    decltype(auto) add_task(Func&& func, Args... args) {
        using ReturnType = decltype(func(args...));
        auto ptask = std::make_shared<std::packaged_task<ReturnType()>>(
            std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
        auto fut = ptask->get_future();
        {
            std::unique_lock lk{pool_mutex};
            task_queue.push([pt = std::move(ptask)]() { (*pt)(); });
        }
        cond.notify_one();
        return fut;
    }

    void stop() {
        {
            std::unique_lock lk{pool_mutex};
            stopped = true;
        }
        cond.notify_all();
        for (auto& th : worker_threads) {
            if (th.joinable()) {
                th.join();
            }
        }
    }

private:
    void thread_func() {
        while(true) {
            std::unique_lock lk{pool_mutex};
            if (task_queue.empty() && stopped) {
                break;
            }

            if (task_queue.empty()) {
                cond.wait(lk, [this]() { return !task_queue.empty() || stopped; });
            }

            if (!task_queue.empty()) {
                auto callable = std::move(task_queue.front());
                task_queue.pop();
                lk.unlock();
                callable();
            }
            else if (stopped) {
                break;
            }
        }
    }

private:
    std::mutex pool_mutex;
    std::vector<std::thread> worker_threads;
    bool stopped = false;
    std::condition_variable cond;
    std::queue<std::function<void()>> task_queue;
};

Note, that add_task returns a future that can be used to wait for a specific task to complete.

~ThreadPool() = default;

We need to call stop() in the destructor!

template<typename Func, typename... Args>
decltype(auto) add_task(Func&& func, Args... args) {
    using ReturnType = decltype(func(args...));

For perfect forwarding we need to use && for args:
template<typename Func, typename... Args>
decltype(auto) add_task(Func&& func, Args&&... args) {
    using ReturnType = decltype(func(std::forward<Args>(args)...));

ThreadPool(int number_of_workers) {

We need to check that this number is greater than zero. Also it might be better to use an unsigned int to match the result of std::thread::hardware_concurrency().

void thread_func() {
    while(true) {
        std::unique_lock lk{pool_mutex};
        if (task_queue.empty() && stopped) {
            break;
        }
        ...

I'm not sure that we should wait for the task_queue to be empty before stopping. I'd suggest that stop() should prevent threads taking any more tasks from the queue (i.e. provide a way to "cancel" tasks that haven't started executing yet).
If we wait for the queue to be empty when calling stop(), we're waiting for all the tasks to complete, so calling stop() doesn't really do much. (The calling code is already in control of whether or not it adds more tasks and waits for futures).
        if (task_queue.empty()) {
            cond.wait(lk, [this]() { return !task_queue.empty() || stopped; });
        }

We don't really need to put cond.wait() in an if statement. It will check the condition before waiting.
I'd probably go for something more like:
void thread_func() {
    while(true) {

        std::unique_lock lk{pool_mutex};
        cond.wait(lk, [this]() { return !task_queue.empty() || stopped; });

        if (stopped)
            break;

        assert(!task_queue.empty());

        auto callable = std::move(task_queue.front());
        task_queue.pop();

        lk.unlock();

        callable();
    }
}


Right triangle side length calculation My code compiles and executes.  I would like to hear any comments or suggestions pertaining to my use of C++.

#include <iostream>
#include <math.h>

bool error_check(){
    if(!std::cin){
        std::cin.clear();
        std::cin.ignore(256,'\n');
        return true;
    }
    else
        return false;
};

int main(){

//This line outputs directions for the user to follow.
std::cout << "\nEnter real numbers for side lengths.\n" <<
                 "\nEnter zero for an unknown side length.\n" <<
                 "\nTo exit enter zero for all side lengths.\n" << std::endl;

while(true){

    //This line prompts the user to enter a side length.
    std::cout << "side a: ";
    //This line initializes and stores user input into a variable for calculation.
    float sidea = 1; std::cin >> sidea;
    //This condtional branch handles bad user input which is in this case anything but real numbers.
    if(error_check()){
        std::cout << "\nYou must enter a real number.\n" << std::endl;
        continue;
    }

    //This line prompts the user to enter another side length.
    std::cout << "side b: ";
    //This line initializes and stores user input into a variable for calculation.
    float sideb = 1; std::cin >> sideb;
    //This condtional branch handles bad user input which is in this case anything but real numbers.
    if(error_check()){
        std::cout << "\nYou must enter a real number.\n" << std::endl;
        continue;
    }

    //This line prompts the user to enter a final side length.
    std::cout << "side c: ";
    //This line initializes and stores user input into a variable for calculation.
    float sidec = 1; std::cin >> sidec;
    //This condtional branch handles bad user input which is in this case anything but real numbers.
    if(error_check()){
        std::cout << "\nYou must enter a real number.\n" << std::endl;
        continue;
    }

    //This conditional branch calculates and outputs the unknown side length.
    if(sidea == 0){
        sidea = sqrt(pow(sidec,2) - pow(sideb,2));
        std::cout << "side a= " << sidea << "\n" << std::endl;
    }
    else if(sideb == 0){
        sideb = sqrt(pow(sidec,2) - pow(sidea,2));
        std::cout << "side b= " << sideb << "\n" << std::endl;
    }
    else if(sidec == 0){
        sidec = sqrt(pow(sidea,2) + pow(sideb,2));
        std::cout << "side c= " << sidec << "\n" << std::endl;
    }
    else{
        std::cout << "\nYou must enter zero for an unknown side length.\n" << std::endl;
        continue;
    }

    //This conditional branch checks to see if the user wants to exit.
    if(sidea == 0 and sideb == 0 and sidec == 0)
        break;
    else
        continue;

}
return 0;
};

Holy comments Batman!

You have too many useless comments which makes your code harder to follow.

  Comments should explain why something is done, not what is done.

Good code makes it obvious what is done, if you feel that you need to comment what is being done then your code can be improved instead.

I'm going to link an answer to another question that explains commenting in a very good way (IMHO).

Prefer && to and

This code if(sidea == 0 and sideb == 0 and sidec == 0) had me do a double take, the and totally threw me off as I'm very used to see && used instead.

Keep it simple

One simplification you can make is to change bool error_check() into float read_real(). You should also extract your exit critera into a function and use it as a loop condition instead of breaking out of an infinite loop. This makes it much more clearer and removes the need for the comment. You can also extract computations from the conditional block when calculating the unknown side.

Like this:

float read_real(){
    float ans;
    std::cin >> ans;
    if(!std::cin){
        std::cin.clear();
        std::cin.ignore(256,'\n');
        throw std::invalid_argument("Please enter a real number");
    }
    return ans;
};

bool should_exit(float a, float b, float c){
    return a == 0 && b == 0 && c == 0;
}

...

float sidea = 1.0f;
float sideb = 1.0f;
float sidec = 1.0f;
while(!should_exit(sidea, sideb, sidec)){
    try{
        std::cout << "side a: ";
        sidea = read_real();

        std::cout << "side b: ";
        sideb = read_real();

        std::cout << "side c: ";
        sidec = read_real();

        // The unknown side must be 0, so this will work for all cases.
        float unknown = sqrt(abs(sidea*sidea + sideb*sideb - sidec*sidec));
        if(sidea == 0){
            std::cout << "side a= " << unknown << "\n" << std::endl;
        }
        else if(sideb == 0){
            std::cout << "side b= " << unknown << "\n" << std::endl;
        }
        else if(sidec == 0){
            std::cout << "side c= " << unknown << "\n" << std::endl;
        }
        else{
            throw std::invalid_argument("You must enter zero for an unknown side length.");
        }
    } catch (std::invalid_argument e){
        std::cout<<"\n Error: "<<e.what()<<std::endl;
    }
}


Merge Sort Implementation Efficiency In Python I wasn't able to find a standardized source for a working example of Merge Sort.

Each learning site had a slightly different take on the algorithm implementation, disregarding the bottom-top implementation.

I wrote my own code for this but unsure if it's the most efficient or if efficiency can be improved?

Any other syntax/logic improvements are welcomed to be pointed out.

def merge(left, right):
    i = 0 #left index
    j = 0 #right index

    sorted_list = []

    while len(left) > i and len(right) > j:
        if left[i] > right[j]:
            sorted_list.append(right[j])
            j += 1
        else:
            sorted_list.append(left[i])
            i += 1

    sorted_list += left[i:] + right[j:]

    return sorted_list

def MergeSort(MyList):
    if len(MyList) > 1:
        mid = len(MyList) // 2
        left = MyList[mid:]
        right = MyList[:mid]

        left = MergeSort(left)
        right = MergeSort(right)

        sorted_list = merge(left, right)

        return sorted_list
    return MyList

Also, a source where I can find standardized code for most algorithms in Python would be nice?
By standardized; I mean code that is deemed efficient and the most up-to-date by the Python community.

PEP-8

The Style Guide for Python Code enumerates a set of rules that all Python programs should follow.  Of particular note is the Naming Conventions, which indicates that function names and variable names should all be snake_case, not CapitalizedWords.  So MergeSort should be renamed merge_sort, and MyList should be renamed my_list.

Private functions

merge is an internal helper function for MergeSort.  PEP-8 also recommends naming internal helpers with a leading underscore, to indicate it is private, and should not be used externally, so merge should be named _merge.

Repeated computations and lookups

    while len(left) > i and len(right) > j:
        if left[i] > right[j]:
            sorted_list.append(right[j])
            j += 1
        else:
            sorted_list.append(left[i])
            i += 1

This code has some inefficiencies.

Every iteration is recomputing len(left) and len(right).
Every iteration is performing 3 indexing operations, first looking up left[i] and right[j], and then looking up either left[i] or right[j] depending on which branch of the if/else is taken.

You only need to test len(left) > i when i changes, and len(right) > j when j changes:

    while True:
        if left[i] > right[j]:
            sorted_list.append(right[j])
            j += 1
            if len(right) > j:
                break
        else:
            sorted_list.append(left[i])
            i += 1:
            if len(left) > i:
                break

Now, the len() function should be called half as often, and only the part of the expression that is changing is being evaluated, and so this code, while longer, should actually run faster.

Similarly, we can remove the repeated indexing operations, by only performing the indexing operation when the corresponding index changes:

    left_value = left[i]
    right_value = right[j]

    while True:
        if left_value > right_value:
            sorted_list.append(right_value)
            j += 1
            if len(right) > j:
                break
            right_value = right[j]
        else:
            sorted_list.append(left_value)
            i += 1:
            if len(left) > i:
                break
            left_value = left[i]

Again, more code, but it should run faster.

Iterators

The above code is complicate because we are responsible for testing if the indices get to the end of the list, looking up the values at the given indices, and incrementing the indices.

Python has iterators, which do all of these operations for us!  So the above code could simply be written as:

    left_iter = iter(left)
    right_iter = iter(right)

    left_value = next(left_iter)
    right_value = next(right_iter)

    while True:
        if left_value > right_value:
            sorted_list.append(right_value)
            right_value = next(right_iter)
        else:
            sorted_list.append(left_value)
            left_value = next(left_iter)

This takes the left and right lists, creates iterators for them, extracts the first values of each, and then adds the smaller of the two values to the sorted_list, and then fetches the next value from the corresponding iterator.

The only problem is it will raise a StopIteration exception when one of the two iterators runs out.  We just need to catch this, and add the remaining entries from the non-expired iterator.  But which one?  Actually this is easy, since the values for left_value and right_value haven't changed, left_value > right_value will reveal which branch of the if/else the exception was raised in.

The only "tricky" part to remember is that if the next(left_iter) raised an exception, then right_value should be added to the sorted_list before the rest of the values from right_iter, and vis-versa. sorted_list.extend() is an easy way of adding the remaining items from the non-expired iterator.

def _merge(left, right):
    left_iter = iter(left)
    right_iter = iter(right)

    sorted_list = []

    # These should never fail because both left & right have one or more elements.
    left_value = next(left_iter)
    right_value = next(right_iter)

    try:
        while True:
            if left_value > right_value:
                sorted_list.append(right_value)
                right_value = next(right_iter)
            else:
                sorted_list.append(left_value)
                left_value = next(left_iter)

    except StopIteration:
        if left_value > right_value:
            sorted_list.append(left_value)
            sorted_list.extend(left_iter)
        else:
            sorted_list.append(right_value)
            sorted_list.extend(right_iter)

    return sorted_list

We've approximately double the number of lines of code in _merge(left, right), but the code should be faster, since all of the indexing, is now being handled by Python itself.


Should I write my fadeTo function differently? fadeTo = function(obj, time, to, cChange ){
    if ( typeof( time ) == "undefined" )
        time = 1000;
    if ( typeof( to ) == "undefined" )
        to = 1;

    if ( time <= 0 )
        return true;

    objSt = obj.style;
    objOpac = parseFloat(objSt.opacity) + 0;

    if ( typeof( cChange ) == "undefined" )
    {
        cChange = (to - objOpac)/(time/10);
    }

    objSt.opacity = objOpac + cChange;

    setTimeout( function(){
            fadeTo( obj, time - 10, to, cChange);
        }, 10);
};

This code was written as a replacement for fadeIn and fadeOut. I made this for learning purposes and it works fine.

I'm just not sure if I could write it better, and if it could cause problems in the future. I feel that I should use two functions instead: one as an init function, and one to finish the process without asking all the extra ifs and simple variable settings.

Well written animation functions typically use a tweening algorithm that checks the system clock to see how much time is actually remaining in the originally specified time allotment and then adjusts the animation increment to put things back on time, even if the timer events weren't coming in exactly on time or the browser was super busy and you weren't getting all the cycles you might want or the host CPU just isn't very fast.  Done well, this can even allow you to adjust the step value for smoother animations on more capable computers and coarser steps on less capable computers.

As you have it, you have a hard coded step function in time of 1/10th the time and thus 1/10th the total opacity change.  On capable computers, you can run much, much smoother than this.

Here's an example:

function now() {
    return new Date().getTime();
}

function fadeTo(obj, time, to, doneFn){

    // sanitize optional arguments
    if ( typeof time === "undefined" )
        time = 1000;
    if ( typeof to === "undefined" )
        to = 1;

    if ( time <= 0 )
        return true;

    var objSt = obj.style,
        originalOpacity = parseFloat(getComputedStyle(obj, null).getPropertyValue("opacity")),
        deltaOpacity = to - originalOpacity,
        sanitizeOpacity,
        minT = 30,
        startTime = now();

    // based on whether we're going up or down, set our santize function
    if (deltaOpacity > 0) {
        sanitizeOpacity = function(x) {
            // not more than 1
            return Math.min(x, 1);
        }
    } else {
        sanitizeOpacity = function(x) {
            // not less than zero
            return Math.max(x, 0);
        }
    }

    function step() {
        // calculate how much time has elapsed since start
        // and then calculate what the opacity should be set
        // to for the animation to be perfectly on time
        var elapsed = now() - startTime, completion;

        // if all our time has elapsed, then just set to final opacity
        if (elapsed >= time) {
            objSt.opacity = to;
            // we're done, call the completion function
            // with the this pointer set to the object that was animating
            if (doneFn) {
                doneFn.apply(obj);
            }
        } else {
            // still some time remaining
            // calculate ideal opacity value to be "on time"
            completion = elapsed/time;
            objSt.opacity = sanitizeOpacity((deltaOpacity * completion) + originalOpacity);
            // schedule next step
            setTimeout(step, minT);
        }

    }
    // start the animation
    setTimeout(step, minT);
}

Working demo: http://jsfiddle.net/jfriend00/hG3Wj/

In other comments:

You MUST use var in front of variables that should be local variables.
You need to be getting the original opacity as the computedStyle, not just reading opacity directly because you need to include style sheet opacity, if nothing is set directly on the object.
If you want to know if an argument is truly undefined, you need to use === to test for it so there can be no automatic type conversions.
I find it more efficient to define an inner function that is called repeatedly because then all of our argument sanitization and what/not only has to happen once, not on each iteration and we can have state variables in the outer closure.


Checking if a username is valid I'm learning about how to create a good and clean code. I just need to review something like that, and I really not sure how can I fix this code into a clean code.
bool isValidUserName(const std::string& username)
{
    bool valid = false;

    if (username.length() >= MIN_NAME_LENGTH)
    {
        if (username.length() <= MAX_NAME_LENGTH)
        {
            if (isalpha(username[0]))
            {
                bool foundNotValidChar = std::find_if(username.begin(), username.end(), isNotValid) != username.end();
                if (!foundNotValidChar)
                {
                    valid = true;
                }
            }
        }
    }

    return valid;
}

We can avoid the excessive indentation by returning early.
Instead of checking for validity:
if (username.length() >= MIN_NAME_LENGTH)
{
    ... additional nested checks...
}

we reverse the check and return as soon as possible:
if (username.length < MIN_NAME_LENGTH)
    return false; // done!

So overall we'd get something like:
if (username.length() < MIN_NAME_LENGTH || username.length() > MAX_NAME_LENGTH)
    return false;

if (username.empty() || !std::isalpha(static_cast<unsigned char>(username.front()))) // paranoia: avoid crashing with empty username
    return false;

if (std::find_if(username.begin(), username.end(), isNotValid) != username.end())
    return false;

return true;

Note that isalpha is in the std:: namespace in C++. Technically we should also cast to unsigned char when calling the function. (We could wrap that in a function of our own).


Merge both sql queries into one to get the performance Currently i am using 2 queries - one for reattemptdate & one for holddate.... if we  merge both queries & get the results in single query , than will it give better performance? if so how to merge ?

1st query :

$sql = "SELECT employeename, DATE(reattemptdate) as date,
COUNT(*) as count FROM orders
WHERE DATE(reattemptdate)  = CURDATE()
GROUP BY employeename, date";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];

foreach ($results as $result)
{
    echo $result['employeename'].'|'.$result['date'].'|'.$result['count']."
";
}

echo "
";

2nd query :

$sqla = "SELECT employeename, DATE(holddate) as date,
COUNT(*) as count FROM orders
WHERE DATE(holddate)  = CURDATE()
GROUP BY employeename, date";
$resultsa = $db_handle->runSelectQuery($sqla);
$numrowsresulta =$resultsa[0]['count'];

foreach ($resultsa as $resulta)
{
    echo $resulta['employeename'].'|'.$resulta['date'].'|'.$resulta['count']."
";
}

echo "
";

if we merge both queries & get the results in single query , then will it give better performance?

There are various aspects of performance here:

time
memory

My inclination is that you are leaning towards reducing time but maybe you mean memory or should at least consider it.

And consider that if the queries were merged into one, there are variables that would affect performance, including:

number of results
separation of data sets (i.e. display on-hold counts vs re-attempted counts in separate lists).

Generally it is best perform as few database queries as are necessary. If there were queries executed inside of a loop where data was selected based on a filter condition, it may make sense to perform one query and filter the data inside of the loop. But in this case, there are simply two similar but unique queries.

You didn't include the implementation for $db_handle->runSelectQuery() but the implementation might affect the answer as well. If that method uses a function to get all results at once (e.g. mysqli_fetch_all()) then it might be better for performance, but otherwise if it fetches results one at a time (e.g. using mysqli_fetch_all() until NULL is returned) then that might add a lot of overhead with looping over results in that method and then your code looping over the results for display purposes.

So in order to get a better answer, you must experiment with your data.

  if so how to merge ?

There are multiple ways to do this. One approach is to simply use UNION. The SQL for the second SELECT query can be appended after the first query and the keyword UNION.

$sql = "SELECT employeename, DATE(reattemptdate) as date,
COUNT(*) as count, 0 as Held FROM orders
WHERE DATE(reattemptdate)  = CURDATE()
GROUP BY employeename, date

UNION

SELECT employeename, DATE(holddate) as date,
COUNT(*) as count, 1 as Held  FROM orders
WHERE DATE(holddate)  = CURDATE()
GROUP BY employeename, date
";

Notice also that those queries have an extra field Held. A field like that can be used to separate the data. That way after the results are fetched, they can be separated into the re-attempted and the held results - perhaps using array_filter().

//formerly $results
$reattemptedResults = array_filter($results, function($result) {
    return $result['Held'] == 0;
});
//formerly $resultsa
$heldResults = array_filter($results, function($result) {
    return $result['Held'] == 1;
});

But keep in mind that this would be iterating over the results potentially 5 times- once to read rows from query results, once for each filtering and then once for each display (though it would be a subset), in that sense performance may actually be worse.

Another option is to use CASE in the queries to conditionally select and filter results:

$sql = "SELECT employeename, CASE WHEN DATE(reattemptdate)  = CURDATE() THEN DATE(reattemptdate) ELSE DATE(holddate) END as date,
COUNT(*) as count, CASE DATE(holddate) WHEN CURDATE() THEN 1 ELSE 0 END as Held
FROM orders
WHERE DATE(reattemptdate)  = CURDATE() OR  DATE(holddate)  = CURDATE()
GROUP BY employeename, date, Held";

And the data would still need to be filtered in PHP after the results are fetched. For small sets of data this likely won't be an issue but for large data sets it has a high potential. I suggest measuring the time with your data in both cases to see how the time compares. I tried it on a small set of data - one distinct employee name, two re-attempted orders and one held order on today's date. The query with CASE was slightly quicker than the original, even with two calls to  filter the data using array_filter().


Brainf**k interpreter in Ruby I wrote this interpreter for a code challenge. Can this be written any cleaner/smaller? Could I reduce the amount of nested conditional/loops?

def brain_luck(code, input)
  output = ''
  cp = 0 # code pointer
  dp = 0 # data pointer
  ip = 0 # input pointer
  data = Array.new(10, 0)
  while cp < code.length
    case code[cp]
    when '>'
      dp += 1
      if dp == data.length
        data.push(0)
      end
    when '<'
      dp -= 1
      if dp == -1
        dp = 0
        data.unshift(0)
      end
    when '+'
      data[dp] = (data[dp].ord+1)%256
    when '-'
      data[dp] = (data[dp].ord-1)%256
    when '.'
      output += data[dp].chr
    when ','
      data[dp] = input[ip].ord
      ip += 1
    when '['
      if data[dp] == 0
        nest_count = 1
        while nest_count > 0
          case code[cp += 1]
          when '[' then nest_count += 1
          when ']' then nest_count -= 1
          end
        end
      end
    when ']'
      if data[dp] != 0
        nest_count = 1
        while nest_count > 0
          case code[cp -= 1]
          when ']' then nest_count += 1
          when '[' then nest_count -= 1
          end
        end
      end
    end
    cp += 1
  end
  output
end

Sure it can!

Steps I see to make it clean:

Create a class, define state attrs:

private

attr_reader :output, :code_pointer, :data_pointer, :input_pointer

define initialize method

def initialize(args = {})
  @code = args[:code]
  @input = args[:input]
  @output = ''
  @code_pointer, @data_pointer, @input_pointer = 0, 0, 0
end

define whens as a methods and give it right names: next_cell, prev_cell, increment, decrement, write_byte, read_byte and so on
define constant for configuration:

OPERATORS = {
  '>' => :next_cell,
  '<' => :prev_cell,
  '+' => :increment,
  ...
}

define method to evaluate code:

def evaluate_code
  code.each { |operator| public_send OPERATORS[operator] }
end

Finally instantiate object of your class and call evaluate_code

BrainLuck.new(code: code, input: input).evaluate_code

I think you'll love your object oriented result.


Efficient image padding in C I am currently implementing pyramids in Lucas Kanade algorithm for optical flow. To be able to build pyramids, I need to pad the images (mirror edge matrix elements) for the required amount of rows/cols determined by parameter half_window.

I have written this code which works but I am new to C programming and it looks overly complex to me. How would an experienced C programmer write this?

image_t is a struct for storing image data I am required to use. Rest is my code. It first adjusts sizes of output which is a pointer to struct image_t object. Then it builds padded image row by row as follows:

skip first half_window rows
mirror first half_window columns of the row
copy original elements of that row
mirror the last half_window columns of the row
skip last half_window rows

Then

mirror first half_window rows with memcpy
mirror last half_window rows with memcpy

struct image_t {
  enum image_type type;   // The image type
  uint16_t w;             // Image width
  uint16_t h;             // Image height
  struct timeval ts;      // The timestamp of creation

  uint8_t buf_idx;        // Buffer index for V4L2 freeing
  uint32_t buf_size;      // The buffer size
  void *buf;              // Image buffer (depending on the image_type)
};

void pad_image(struct image_t *input, struct image_t *output, uint8_t half_window)
{
    uint8_t *input_buf = (uint8_t *)input->buf;

    output->h = input->h + 2*half_window;
    output->w = input->w + 2*half_window;
    output->buf_size = sizeof(uint8_t) * output->h * output->w;
    free(output->buf);
    output->buf = malloc(output->buf_size);
    uint8_t *output_buf = (uint8_t*)output->buf;

    for (int i = half_window; i != (output->h-half_window); i++){

        for (int j=0; j!=half_window; j++)
            output_buf[i*output->w + (half_window -1 - j)] = input_buf[(i-half_window)*input->w + j];

        for (int j=half_window; j!=output->w-half_window;j++)
            output_buf[i*output->w + j] = input_buf[(i-half_window)*input->w + (j - half_window)];

        for (int j=0; j!=half_window;j++)
            output_buf[i*output->w + output->w - half_window + j] = output_buf[i*output->w + output->w - half_window -1 - j];
    }

    for (int i=0; i!=half_window; i++){
        memcpy(&output_buf[(half_window-1)*output->w - i*output->w], &output_buf[half_window*output->w + i*output->w], sizeof(uint8_t)*output->w);
        memcpy(&output_buf[(output->h - half_window)*output->w + i*output->w], &output_buf[(output->h-half_window-1)*output->w - i*output->w], sizeof(uint8_t)*output->w);

    }
}

Input:

   1    2    3    4
   5    6    7    8
   9   10   11   12
  13   14   15   16

Expected output for half_window = 2:

   6    5    5    6    7    8    8    7
   2    1    1    2    3    4    4    3
   2    1    1    2    3    4    4    3
   6    5    5    6    7    8    8    7
  10    9    9   10   11   12   12   11
  14   13   13   14   15   16   16   15
  14   13   13   14   15   16   16   15
  10    9    9   10   11   12   12   11

I have made some changes to the code I feel make things more clear, I will post them here in case someone needs something similar.

Code below is used in my function and is work of Freek van Tienen (part of open source software Paparazzi):

struct image_t {
  enum image_type type;   ///< The image type
  uint16_t w;             ///< Image width
  uint16_t h;             ///< Image height
  struct timeval ts;      ///< The timestamp of creation

  uint8_t buf_idx;        ///< Buffer index for V4L2 freeing
  uint32_t buf_size;      ///< The buffer size
  void *buf;              ///< Image buffer (depending on the image_type)
};

void image_create(struct image_t *img, uint16_t width, uint16_t height, enum image_type type)
{
  // Set the variables
  img->type = type;
  img->w = width;
  img->h = height;

  // Depending on the type the size differs
  if (type == IMAGE_YUV422) {
    img->buf_size = sizeof(uint8_t) * 2 * width * height;
  } else if (type == IMAGE_JPEG) {
    img->buf_size = sizeof(uint8_t) * 2 * width * height;  // At maximum quality this is enough
  } else if (type == IMAGE_GRADIENT) {
    img->buf_size = sizeof(int16_t) * width * height;
  } else {
    img->buf_size = sizeof(uint8_t) * width * height;
  }

  img->buf = malloc(img->buf_size);
}

My code for image padding:

void pad_image(struct image_t *input, struct image_t *output, uint8_t expand)
{
    image_create(output, input->w + 2 * expand, input->h + 2 * expand, input->type);

    uint8_t *input_buf = (uint8_t *)input->buf;
    uint8_t *output_buf = (uint8_t *)output->buf;

    // Skip first `expand` rows, iterate through next input->h rows
    for (uint16_t i = expand; i != (output->h - expand); i++){

        // Mirror first `expand` columns
        for (uint8_t j = 0; j != expand; j++)
            output_buf[i * output->w + (expand - 1 - j)] = input_buf[(i - expand) * input->w + j];

        // Copy corresponding row values from input image
        memcpy(&output_buf[i * output->w + expand], &input_buf[(i - expand) * input->w], sizeof(uint8_t) * input->w);

        // Mirror last `expand` columns
        for (uint8_t j = 0; j != expand; j++)
            output_buf[i * output->w + output->w - expand + j] = output_buf[i * output->w + output->w - expand -1 - j];
    }

    // Mirror first `expand` and last `expand` rows
    for (uint8_t i = 0; i != expand; i++){
        memcpy(&output_buf[(expand - 1) * output->w - i * output->w], &output_buf[expand * output->w + i * output->w], sizeof(uint8_t) * output->w);
        memcpy(&output_buf[(output->h - expand) * output->w + i * output->w], &output_buf[(output->h - expand - 1) * output->w - i * output->w], sizeof(uint8_t) * output->w);
    }
}


Basic folder tree with a list of strings I am building up a basic folder tree with a list of strings in the form /root/node/node/node. Here is the basic algorithm I am using currently to build this collection and fill in my TreeGridView:

// This method gets the list of folders and leaves, then trims out any folder paths
// that are already encompassed in a larger folder path, the idea is that it causes
// less work when adding the actual tree nodes (I may be wrong in this assumption)
List<string> BuildFinalList()
{
    // This list is a collection of root folder paths and leaf folder names
    // i.e. pair("/root/node/node", "node"), pair("/root/node", "node)
    List<KeyValuePair<string, string>> folders = GetListOfFolders();
    var paths = new List<string>();
    foreach(var folder in folders)
    {
        var leaf = folder.Value;
        var root = folder.Key;
        paths.Add(string.Concat(root, "/", leaf);
    }
    paths.Sort(_INVERSE_LENGTH_COMPARE); // this sorts the list longest to shortest

    // Iterate the computed paths from longest to shortest, if a path is not
    // encompassed by an existing path in the final list, add it to the
    // final list, otherwise just move to the next path
    var finalList = new List<string>();
    foreach(var path in paths)
    {
        bool found = false;
        foreach(var item in finalList)
        {
            if (item.StartsWith(path, StringComparison.Ordinal))
            {
                found = true;
                break;
            }
        }

        if (!found)
        {
            finalList.Add(path);
        }
    }
    return finalList;
 }

Once I have the final list built, I then add the nodes to the tree (for simplification, I have removed the calls to end update and begin update of the tree that contains the root node):

void FillTreeNodes(TreeNode root)
{
    var rootText = root.Text;
    var rootTextLength = rootText.Length;
    var nodeStrings = BuildFinalList();
    foreach(var nodeString in nodeStrings)
    {
        var roots = nodeString.Split(new char[] { '/' },
            StringSplitOptions.RemoveEmptyEntries);

        // The initial parent is the root node
        var parentNode = root;
        var sb = new StringBuilder(rootText, nodeString.Length + rootTextLength);
        for(int rootIndex = 0; rootIndex < roots.Length; rootIndex++)
        {
            // Build the node name
            var parentName = roots[rootIndex];
            sb.Append("/");
            sb.Append(parentName);
            var nodeName = sb.ToString();

            // Search for the node
            var index = parentNode.Nodes.IndexOfKey(nodeName);
            if (index == -1)
            {
                 // Node was not found, add it
                 var temp = new TreeNode(parentName, 1, 1);
                 temp.Name = nodeName;
                 parentNode.Nodes.Add(temp);
                 parentNode = temp;
            }
            else
            {
                 // Node was found, set that as parent and continue
                 parentNode = parentNode.Nodes[index];
            }
        }
    }
}

One improvement that comes to mind is:

bool found = false;
foreach(var item in finalList)
{
    if (item.StartsWith(path, StringComparison.Ordinal))
    {
        found = true;
        break;
    }
}

Finding out whether a condition is met for any item in a collection is a common enough problem that LINQ has a method for that: Enumerable.Any. Using that the above code can be written as just:

bool found = finalList.Any(item =>
    item.StartsWith(path,StringComparison.Ordinal);

Which is both shorter and simpler.


Inserting a parenthesized nickname Given two strings, for example

  s1 = "Valentino   Rossi" (which may contain as many spaces between the 2 words as I like)
   s2 = "Vale"

I have to create a function that requests these two strings and that it outputs another one like this one: "Valentino (Vale) Rossi".

So for example if I have

  s1 = "Mario       Belli"
  s2 = "Mar"

the returned string must be "Mario (Mar) Belli".

#include <stdio.h>
#include <string.h>
#define STR_LEN 32

char *makeNickname(char *s1, char *s2, char *s3);

int main() {
    char nomeCognome[] = "Corrado     Righetti";
    char nickname[] = "Cora";
    char nameNickname[STR_LEN];
    makeNickname(nomeCognome, nickname, nameNickname);
    printf("%s\n\n", nameNickname);
}

char *makeNickname(char *s1, char *s2, char *s3) {
    char *p = s1, *q = s2, *k = s3;
    while (*p) {
        if (*p != ' ') {
            *k++ = *p++;
        } else {
            *k++ = *p;
            *k++ = '(';
            while (*q) {
                *k++ = *q;
                q++;
            }
            *k++ = ')';
            *k++ = *p;
            while (*p == ' ') p++;
        }
    }
    return s3;
}

Naming

Your variable names are polyglot, cryptic, and inconsistent.  Don't mix Italian with English — stick with English if you can.  Instead of s1…s3, pick more meaningful names.  Instead of p, q, and k, it would have been better to use p1, p2, and p3 — but again, more meaningful names would be even better.

Function signatures

In modern C, you should mark strings as const if you're not going to write to them.

It is customary to put main() at the end, so that you don't need to declare your functions.

Approach

You aren't writing a '\0' terminator character to out, so your function won't work if the buffer is unclean.

Your solution is not robust to unexpected input, such as extra spaces at the end of s1.

Character-by-character manipulation isn't very readable.  You wouldn't want to write code like this in a larger project.  Instead, make use of the existing library functions for working with strings.  (You have already written #include <string.h>, so why not?)

char *makeNickname(const char *names, const char *nickname, char *out) {
    const char *firstSpace = strchr(names, ' ');
    const char *lastName = firstSpace + strspn(firstSpace, " ");
    sprintf(out, "%.*s (%s) %s", (int)(firstSpace - names), names, nickname, lastName);
    return out;
}

Note that this solution, like yours, doesn't check for buffer overflow.  It would be good practice to also pass the size of the buffer to enable such a check.


Reader for graph-file with ugly return and questionable use of streams I wrote a class that contains a static method that reads in files from NetworkRepository and converts them into a list of integer-arrays, each representing an edge. The file format from NetworkRepository is, that each line which is not a comment contains two integer numbers, the IDs of vertices connected by an edge, seperated by whitespace (tabs/spacebar).
Example:

corresponds to:

1 2
1 3
2 3
3 4

Can my code for this be improved? I really don't like the unreachable return null, but I don't need error-handling except that I know I provided the wrong path.

public static List<Integer[]> edges_from_path(final String filePath) {
    //captures only lines that consist of two positive integer numbers separated by whitespace (each line encodes an edge)
    final String LINE_DATA_FORMAT = "\\d+\\s+\\d+";
    final String SEPARATOR = "\\s+";
    try {
        return Files.lines(Paths.get(filePath))
                .filter(str -> str.matches(LINE_DATA_FORMAT))
                .map(str -> Arrays.stream(str.split(SEPARATOR)).map(Integer::parseInt).toArray(Integer[]::new))
                .collect(toList());
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

My method doesn't return a graph because I want to be able to create graphs from different sources, and a list of integer-pairs is the interface the constructor for graphs is supposed to use.

Exception Handling

What are you doing in the exceptional case?

Printing an error message (ugly stack trace, actually) and returning null.  Now the caller has to handle the problem of the function returning null.

You've said:

  I don't need error-handling except that I know I provided the wrong path.

Well, want is the caller doing when it gets the null?  Does it say, "I couldn't open that file, please enter a different filename"?  That too is error handling, and you've have it in two places: the try ... catch here, and the if (list == null) by the caller.

Better is to ignore the exception here, and let the caller handle it, or the caller's caller.

public static List<Integer[]> edges_from_path(final String filePath) throws IOException {
    //captures only lines that consist of two positive integer numbers separated by whitespace (each line encodes an edge)
    final String LINE_DATA_FORMAT = "\\d+\\s+\\d+";
    final String SEPARATOR = "\\s+";
    return Files.lines(Paths.get(filePath))
                .filter(str -> str.matches(LINE_DATA_FORMAT))
                .map(str -> Arrays.stream(str.split(SEPARATOR)).map(Integer::parseInt).toArray(Integer[]::new))
                .collect(toList());
}

  My method doesn't return a graph because I want to be able to create graphs from different sources, and a list of integer-pairs is the interface the constructor for graphs is supposed to use.

This is even more reason not to catch the error and return null; the other sources would need to have the same behaviour.  They could fail in different and diverse ways; the exception will provide more details about the failure than null return value will.

List of Integer-Pairs

To say I almost threw-up when I saw List<Integer[]> would be an exaggeration, but only slightly.  Mixing collections and raw arrays is cringe worthy.  But a list of a raw arrays of a boxed type???  Yikes!

The raison d'être for "boxed types" is so they can be placed into the various Collection<E> containers, which require objects instead of raw types.  But here, you're not putting the integers into a Collection<E>; you're putting them into an array ([]), so they don't actually need to be boxed.

To see how wrong this is, each element of the List<> is an object Integer[], which holds two references to two Integer objects.  That is 3 objects allocated in the heap (ignoring interning) for every edge in the list.

If instead you used List<int[]>, then element of the List<> would be an int[] object, which directly contains the two integers, instead of references.  No extra objects need to be allocated.  Less memory is required, and the data is faster to access because an extra level of memory indirection has been removed.

Still, we eschew lists of raw arrays.  They are inconsistent; you need different access methods to get to the data at different levels, such as list.get(idx1)[idx2].  The array of integers doesn't convey any requirement on the number of values; you could be given a lists of lengths other than two.  It would be better to wrap the edge information into a POD (plain old data) object:

class Edge {
    public final int from;
    public final int to;
    Edge(int _from, int _to) {
        from = _from;
        to = _to;
    }
}

And then you could return a List<Edge>.  Change your graph constructor from taking a list of arrays of boxed integers of arbitrary lengths to taking a list of edges.  That is a much clearer interface contract.


Reducing the amount of List in a WebScraper At the moment, I'm learning and experimenting on the use of web scraping content from different varieties of web pages. But I've come across a common smelly code among several of my applications. I have many repetitive List that has data being append to them.

from requests import get
import requests
import json
from time import sleep
import pandas as pd

url = 'https://shopee.com.my/api/v2/flash_sale/get_items?offset=0&limit=16&filter_soldout=true'
list_name = []
list_price = []
list_discount = []
list_stock = []

response = get(url)
json_data = response.json()

def getShockingSales():
    index = 0
    if response.status_code is 200:
        print('Response: ' + 'OK')
    else:
        print('Unable to access')
    total_flashsale = len(json_data['data']['items'])
    total_flashsale -= 1
    for i in range(index, total_flashsale):
        print('Getting data from site... please wait a few seconds')
        while i <= total_flashsale:
            flash_name = json_data['data']['items'][i]['name']
            flash_price = json_data['data']['items'][i]['price']
            flash_discount = json_data['data']['items'][i]['discount']
            flash_stock = json_data['data']['items'][i]['stock']
            list_name.append(flash_name)
            list_price.append(flash_price)
            list_discount.append(flash_discount)
            list_stock.append(flash_stock)
            sleep(0.5)
            i += 1
        if i > total_flashsale:
            print('Task is completed...')
            return

getShockingSales()
new_panda = pd.DataFrame({'Name': list_name, 'Price': list_price,
                          'Discount': list_discount, 'Stock Available': list_stock})

print('Converting to Panda Frame....')
sleep(5)
print(new_panda)

Would one list be more than sufficient? Am I approaching this wrongly.

Review

Creating functions that read and modify global variables is not a good idea, for example if someone wants to reuse your function, they won't know about side effects.
index is not useful, and range(0, n) is the same as range(n)
Using == is more appropriate than is in general, hence response.status_code == 200
If response.status_code != 200, I think the function should ~return an empty result~ raise an exception like said by @Ludisposed.
You use json_data["data"]["items"] a lot, you could define items = json_data["data"]["items"] instead, but see below.
Your usage of i is totally messy. Never use both for and while on the same variable. I think you just want to get the information for each item. So just use for item in json_data["data"]["items"]:.
Actually, print("Getting data from site... please wait a few seconds") is wrong as you got the data at response = get(url). Also, sleep(0.5) and sleep(5) don't make any sense.
Speaking from this, requests.get is more explicit.
You can actually create a pandas DataFrame directly from a list of dictionaries.
Actually, if you don't use the response in another place, you can use the url as an argument of the function.
Putting spaces in column names of a DataFrame is not a good idea. It removes the possibility to access the column named stock (for example) with df.stock. If you still want that, you can use pandas.DataFrame.rename
You don't need to import json.
The discounts are given as strings like "59%". I think integers are preferable if you want to perform computations on them. I used df.discount = df.discount.apply(lambda s: int(s[:-1])) to perform this.
Optional: you might want to use logging instead of printing everything. Or at least print to stderr with:

from sys import stderr

print('Information', file=stderr)

Code

import requests
import pandas as pd

def getShockingSales(url):
    response = requests.get(url)
    columns = ["name", "price", "discount", "stock"]
    response.raise_for_status()
    print("Response: OK")
    json_data = response.json()
    df = pd.DataFrame(json_data["data"]["items"])[columns]
    df.discount = df.discount.apply(lambda s: int(s[:-1]))
    print("Task is completed...")
    return df

URL = "https://shopee.com.my/api/v2/flash_sale/get_items?offset=0&limit=16&filter_soldout=true"
df = getShockingSales(URL)


Managing rendering targets in XNA using IDisposable I came up with the following class that I can use as an XNA service to manage rendering to things other than the screen as I didn't want to be passing Games/GraphicsDevices around all over the place for testing reasons. I can't see anything wrong with it, but I'm curious what other people think about the design/etc. of it and the general theory of it. Is this abusing IDisposable, or is this an ok way to do things?

Typical Usage:

using(Services.GetService<IRenderTargetController>().SetRenderTarget(renderTarget, Color.Black)) {
    // [snip] Render stuff as normal here.
}

Implementation:

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

sealed class RenderTargetController : IRenderTargetController
{
    private readonly GraphicsDevice _graphicsDevice;
    private readonly Stack<RenderTarget2D> _targets;

    public RenderTargetController(GraphicsDevice graphicsDevice)
    {
        _graphicsDevice = graphicsDevice;
        _targets = new Stack<RenderTarget2D>();
    }

    public IDisposable SetRenderTarget(RenderTarget2D target)
    {
        return SetRenderTarget(target, Color.Transparent);
    }

    public IDisposable SetRenderTarget(RenderTarget2D target, Color resetColor)
    {
        _targets.Push(target);
        _graphicsDevice.SetRenderTarget(target);
        _graphicsDevice.Clear(resetColor);

        return new TargetManager(this);
    }

    private class TargetManager : IDisposable
    {
        private readonly RenderTargetController _controller;

        public TargetManager(RenderTargetController controller)
        {
            _controller = controller;
        }

        public void Dispose()
        {
            _controller._targets.Pop();

            RenderTarget2D target = null;
            if (_controller._targets.Count > 0)
            {
                target = _controller._targets.Peek();
            }

            // Setting render target to null returns control to the screen.
            _controller._graphicsDevice.SetRenderTarget(target);
        }
    }
}

An approach itself is fine IMO, but the API is misleading. Why would SetXXX method ever return something, let alone return an IDisposable? Maybe come up with a better name.


Split Inputvalue into 2 hex encoded bytes if Input>255 I'm assigning a HEX-Value to a byte in a byte array and then send this byte array to a serial port. If the value is bigger than 255 the corresponding HEX-Value is supposed to be split into two.

Example: 750 = 0x2EE so A[0] = 0x2 and A[1] = 0xEE

Is this an efficient way to do the task that I want it to do? From what I read so far the conversion should be okay here or can I skip the 0x and still get the same result after the Convert.ToByte?

    private void button3_Click(object sender, EventArgs e)
    {
        byte[] A = new byte[2];
        string f = "0x" + Convert.ToInt32(textBox3.Text).ToString("X");
        textBox2.Text = Convert.ToString(f.Length);  //to test length
        if (f.Length < 5)
        {
            A[0] = 0x00;
            A[1] = Convert.ToByte(f,16);
            textBox1.Text = "A";
        }
        else if (f.Length == 5)
        {
            A[0] = Convert.ToByte(f.Substring(0,3),16);
            A[1] = Convert.ToByte("0x" + f.Substring(3),16);
            textBox1.Text = "B" + "Sub0: " + f.Substring(0, 3) + "\r\n Sub1 :" + "0x" + f.Substring(3); //to test
        }
        else
        {
            textBox1.Text = "Falsche Eingabe";
        }
    }

Why try and manipulate the number as a string?

Personally I would convert the input to a number and then manipulate it and finally convert it back to a string, if you need to.  However I would have thought C# has a way of making a text box accept Hex numbers and returning an Int (I don't know I don't do GUIs.)

Using your example number 0x2ee.
If the number if greater than 0xFF then it will take more than one byte to store it.  So to split the value you can do lowerByte = number % 256.  The upper byte is simply upperByte = (number - lowerByte) >> 8

So putting this into code

static byte[] SplitNumber (Int16 number)
{
    byte[] returnValue = new byte[2];
    returnValue[0] = Convert.ToByte(number % 256);
    returnValue[1] = Convert.ToByte((number - returnValue[0]) >> 8);
    return returnValue;
}

Now you have your bytes, you can format them in the text box as you like,


Simulation of Conway's Game of Life with periodic boundary conditions This is exercise 2.4.20. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Implement a class that simulates Conway’s Game of Life.
One thing to note: I did not want my grid to have passive edges and so in my program I considered the grid to be an opened torus (for example in a 10-by-10 grid represented by an array: a[9+1][9+1] == a[0][0]). I also tried to make the name of the methods and variables as self-explanatory as possible.
Here is my program:
public class GameOfLife
{
    public static boolean[][] randomGridMaker(int n, double p)
    {
        // n is the number of grid cells in each row or column
        // p is the probability of a cell being alive
        boolean[][] grid = new boolean[n][n];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (Math.random() < p)
                {
                    grid[i][j] = true;
                }
            }
        }
        return grid;
    }
    public static boolean[][] gridEqualizer(boolean[][] a)
    {
        int n = a.length;
        boolean[][] b = new boolean[n][n];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                b[i][j] = a[i][j];
            }
        }
        return b;
    }
    public static int liveNeighborCounter(boolean[][] a, int i, int j)
    {
        int counter = 0;
        int n = a.length;
        if (a[(i-1)%n][(j-1)%n]) counter++;
        if (a[(i-1)%n][j%n]) counter++;
        if (a[(i-1)%n][(j+1)%n]) counter++;
        if (a[i%n][(j+1)%n]) counter++;
        if (a[(i+1)%n][(j+1)%n]) counter++;
        if (a[(i+1)%n][j%n]) counter++;
        if (a[(i+1)%n][(j-1)%n]) counter++;
        if (a[i%n][(j-1)%n]) counter++;
        return counter;
    }
    public static boolean[][] gridUpdater(boolean[][] a)
    {
        int n = a.length;
        boolean[][] b = new boolean[n][n];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                b[i][j] = a[i][j];
            }
        }
        for (int i = 1; i < n; i++)
        {
            for (int j = 1; j < n; j++)
            {
                int liveNeighbors = liveNeighborCounter(a, i, j);
                if (!a[i][j] && liveNeighbors == 3) b[i][j] = true;
                if (a[i][j])
                {
                    if (liveNeighbors == 1) b[i][j] = false;
                    if (liveNeighbors > 3) b[i][j] = false;
                }
            }
        }
        return b;
    }
    public static void gridDrawer(boolean[][] a)
    {
        int n = a.length;
        StdDraw.setXscale(0,n);
        StdDraw.setYscale(0,n);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (a[i][j]) StdDraw.filledSquare(i+0.5,j+0.5,0.47);
            }
        }
    }
    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        double p = Double.parseDouble(args[1]);
        StdDraw.setPenColor(StdDraw.BOOK_BLUE);
        StdDraw.enableDoubleBuffering();
        boolean[][] a = new boolean[n][n];
        boolean[][] b = new boolean[n][n];
        a = randomGridMaker(n, p);
        while (true)
        {
            StdDraw.clear();
            gridDrawer(a);
            StdDraw.show();
            StdDraw.pause(50);
            StdDraw.clear();
            b = gridUpdater(a);
            gridDrawer(b);
            StdDraw.show();
            StdDraw.pause(50);
            a = gridEqualizer(b);
        }
    }
}

StdDraw is a simple API written by the authors of the book. I checked my program and it works. Here are two different instances of it:
Instance 1: n = 20 and p = 0.1:

Instance 2: n = 100 and p = 0.5:

Is there any way that I can improve my program (especially its performance)?
Thanks for your attention.

Nice implementation, few suggestions:
Naming conventions
In Java methods should be verbs and classes should be nouns.

method randomGridMaker can be renamed to makeRandomGrid (or similar)
method liveNeighborCounter can be renamed to countAliveNeighbors
method gridDrawer could be drawGrid, etc..

Java Naming Convetions
Input validation
The program needs two arguments to start, better to provide a message to the user:
if(args.length != 2) {
    System.out.println("Size and probability not provided");
    System.exit(1);
}

Encapsulation
The grid is passed around in almost every method. Would be better to have the grid as state of GameOfLife:
public class GameOfLife {

    private boolean[][] grid;
    private int n;
    private double p;

    public GameOfLife(int n, double p) {
        grid = new boolean[n][n];
        this.n=n;
        this.p=p;
    }
//...
}

This will also make GameOfLife easier to reuse.
Main loop
while (true)
    {
        StdDraw.clear();
        gridDrawer(a);
        StdDraw.show();
        StdDraw.pause(50);
        StdDraw.clear();
        b = gridUpdater(a);
        gridDrawer(b);
        StdDraw.show();
        StdDraw.pause(50);
        a = gridEqualizer(b);
    }

The method gridDrawer already knows how to use the library StdDraw, so the the methods clear and show can be moved there

There is no need of gridEqualizer if a new grid is already created in gridUpdater

The two calls to pause(50) can now become pause(100)

The result would be:
GameOfLife gol = new GameOfLife(n,p);
gol.initRandom();
while (true){
    drawGrid(gol.getGrid());
    StdDraw.pause(100);
    gol.update(); // this is gridUpdater
}

Notice that:

GameOfLife doesn't know how to draw itself, therefore is independent of the library StdDraw
Only GameOfLife can modify the grid

Performance
There are no big issues about performances, just few suggestions.
There are many operations in liveNeighborCounter:
public static int liveNeighborCounter(boolean[][] a, int i, int j)
    {
        int counter = 0;
        int n = a.length;
        if (a[(i-1)%n][(j-1)%n]) counter++;
        if (a[(i-1)%n][j%n]) counter++;
        if (a[(i-1)%n][(j+1)%n]) counter++;
        if (a[i%n][(j+1)%n]) counter++;
        if (a[(i+1)%n][(j+1)%n]) counter++;
        if (a[(i+1)%n][j%n]) counter++;
        if (a[(i+1)%n][(j-1)%n]) counter++;
        if (a[i%n][(j-1)%n]) counter++;
        return counter;
    }

I noticed that there is no need to use % so often, but only when the index oveflows.
It can be simplified like this:
private int countAliveNeighbors(int i, int j) {
    int counter = 0;
    for(int x=i-1 ; x<=i+1; x++) {
        for(int y=j-1; y<=j+1; y++) {
            // Skip given position
            if(x==i && y==j)
                continue;
            if(isAlive(castIndex(x),castIndex(y))) {
                counter++;
            }
        }
    }
    return counter;
}

private boolean isAlive(int i, int j) {
    return grid[i][j];
}

private int castIndex(int i) {
    if(i>=n) return 0;
    return i<0 ? n-1 : i;
}

Regarding memory, I noticed that there are some initializations that can be avoided like:
boolean[][] a = new boolean[n][n];
a = randomGridMaker(n, p);

The initialization is already done in the method randomGridMaker, so you can directly have:
boolean[][] a = randomGridMaker(n, p);

Same for other parts in the code. I will just paste here the code refactored.
Refactored code
public class GameOfLife {

    private boolean[][] grid;
    private int n;
    private double p;

    public GameOfLife(int n, double p) {
        grid = new boolean[n][n];
        this.n=n;
        this.p=p;
    }

    public void initRandom() {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (Math.random() < p)
                {
                    grid[i][j] = true;
                }
            }
        }
    }

    private boolean isAlive(int i, int j) {
        return grid[i][j];
    }

    private int castIndex(int i) {
        if(i>=n) return 0;
        return i<0 ? n-1 : i;
    }

    private int countAliveNeighbors(int i, int j) {
        int counter = 0;
        for(int x=i-1 ; x<=i+1; x++) {
            for(int y=j-1; y<=j+1; y++) {
                // Skip given position
                if(x==i && y==j)
                    continue;
                if(isAlive(castIndex(x),castIndex(y))) {
                    counter++;
                }
            }
        }
        return counter;
    }

    private boolean[][] cloneGrid(){
        boolean[][] b = new boolean[n][n];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                b[i][j] = grid[i][j];
            }
        }
        return b;
    }

    public void update() {
        boolean[][] b = cloneGrid();
        for (int i = 1; i < n; i++)
        {
            for (int j = 1; j < n; j++)
            {
                int liveNeighbors = countAliveNeighbors(i,j);
                if(isAlive(i,j)) {
                    if (liveNeighbors == 1 || liveNeighbors > 3) {
                        b[i][j] = false;
                    }
                } else if (liveNeighbors == 3){
                    b[i][j] = true;
                }
            }
        }
        grid=b;
    }

    public boolean[][] getGrid(){
        return grid;
    }

    public static void drawGrid(boolean[][] a)
    {
        int n = a.length;
        StdDraw.clear();
        StdDraw.setXscale(0,n);
        StdDraw.setYscale(0,n);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (a[i][j]) StdDraw.filledSquare(i+0.5,j+0.5,0.47);
            }
        }
        StdDraw.show();
    }
    public static void main(String[] args)
    {
        if(args.length != 2) {
            System.out.println("Size and probability not provided");
            System.exit(1);
        }
        int n = Integer.parseInt(args[0]);
        double p = Double.parseDouble(args[1]);
        StdDraw.setPenColor(StdDraw.BOOK_BLUE);
        StdDraw.enableDoubleBuffering();
        GameOfLife gol = new GameOfLife(n,p);
        gol.initRandom();
        while (true)
        {
            drawGrid(gol.getGrid());
            StdDraw.pause(100);
            gol.update();
        }
    }
}


Calendar events based on user feedback Here's a bit of one of my web forms which is reached by clicking on a link in a calendar.  Based on what you click, you end up at this page with a different QueryString.  Based on that QueryString, we hide/show and enable/disable controls related to actions associated with the QueryString, as well as the role of user.

We have three different types of events:

VacationDays (days where people took paid vacation)
VacationDaysUnpaid (days where people took unpaid vacation)
CalendarEvents (everything else such as meetings and client visits)

Here's a slimmed down version of how the page is prepared:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        InitializePage();
    }
}

private void InitializePage()
{
    CheckRoles();

    if (!String.IsNullOrEmpty(Request.QueryString["CalendarEventID"]))
    {
        if (!HttpContext.Current.User.IsInRole("Guest"))
        {
            //if this is just a regular calendar event, allow non-guests to edit
            btnedit.Enabled = true;
            btndelete.Visible = false;
        }
    }
    if (!String.IsNullOrEmpty(Request.QueryString["VacationDayID"]))
    {
        if (!HttpContext.Current.User.IsInRole("Guest"))
        {
            //for vacation days, edits are not allowed, but the ability to delete is
            btnedit.Visible = false;
            btndelete.Enabled = true;
            btndelete.Visible = true;
        }
    }
    if (!String.IsNullOrEmpty(Request.QueryString["VacationDayUnpaidID"]))
    {
        //unpaid vacation days can only be deleted by administrators
        if (HttpContext.Current.User.Identity.Name.ToString().ToLower() == "administrator")
        {
            btndelete.Visible = true;
        }
        else
        {
            btndelete.Visible = false;
        }
    }
}

private void CheckRoles()
{
    if (HttpContext.Current.User.IsInRole("Guest"))
    {
        //disable all write controls if guest
        btnedit.Visible = false;
        btndelete.Visible = false;
        btnsave.Visible = false;
    }
}

It's jumbled, it's confusing, and it's difficult to maintain.  Is there any kind of common design or plan of attack for doing what I'm trying to do here?  I mean this works, I can work with it, I guess, but I really feel like there must just be some technique that I don't know about which will help improve this into something much easier and manageable.

One idea that I'm considering, and that I know will work, is to separate the code related to the different types of events into separate files as "partial"

That way in my InitializePage() method, for each type of QueryString, I'll have code that says like EnableCalendarEventMode(), which would be located in the partial class and would contain all the code related to calendar events.  This idea will make it easier to manage for me personally, but it still doesn't change the code, it just moves it around.

For one thing, everything is just setting booleans. Condense down all those nested if blocks down into boolean statements and use good names, and it'll even make sense in "plain English".

protected void Page_Load(object sender, EventArgs e) {
    if (IsPostBack) return;
    Func<string, bool> QueryStrHas = key => !String.IsNullOrEmpty(Request.QueryString[key]);
    var isCalEvent = QueryStrHas("CalendarEventID");
    var isVacDay  = QueryStrHas("VacationDayID");
    var isUnpaidVac = QueryStrHas("VacationDayUnpaidID");

    var user = HttpContext.Current.User;
    var isGuest = user.IsInRole("Guest");
    var isAdmin = user.Identity.Name.ToString().ToLower() == "administrator";

    // guests cannot edit
    // non-guests can edit regular calendar events, but not vacation days
    // non-guests can delete vacation days
    // unpaid vacation days can only be deleted by administrators
    btnedit.Enabled = !isGuest && isCalEvent && !isVacDay;
    btndelete.Enabled = !isGuest && isVacDay;
    btndelete.Visible = !isGuest &&
                        (isVacDay||
                        (isAdmin && isUnpaidVac));
}

Make sure you double-check the boolean arithmetic by testing it though. There're some missing cases (kind of), and you should make sure it's all well-defined.

Oh, by the way, just cosmetically "hiding" the btnedit when a user isn't an Admin does not count for true security. Anybody can actually modify all these values when it reaches their browser client-side.


Looping through arrays in VBA I supplied the following code as an answer to this question on SO, but I was wondering if there was a better way to write out all those array loops (i.e. perhaps using a Collection/Dictionary?) It seems clunky/cumbersome as-is.

Function ContainedInMonth(OriginalStartDate As String, _
    OriginalEndDate As String) As Boolean

    Dim MonthSet As Variant
    Dim AryCounter As Integer, ISOOffset As Integer
    Dim StartYear As Integer, EndYear As Integer
    Dim StartWeek As Integer, EndWeek As Integer
    Dim StartDay As Integer, EndDay As Integer
    Dim FormattedStartDate As Date, FormattedEndDate As Date

    ' This section may (will) vary, depending on your data.
    ' I'm assuming "YYYY-WW" is passed...
    ' Also, error/formatting checking for these values is needed
    ' and wil differ depending on that format.
    StartYear = Val(Left(OriginalStartDate, 4))
    StartWeek = Val(Right(OriginalStartDate, 2))
    EndYear = Val(Left(OriginalEndDate, 4))
    EndWeek = Val(Right(OriginalEndDate, 2))

    If StartYear <> EndYear Or StartWeek > EndWeek Then
        ContainedInMonth = False
    ElseIf StartWeek = EndWeek Then
        ContainedInMonth = True
    Else

        ' Using the calculation from wikipedia. Honestly, I'm not sure that
        ' I understand this bit, but it seemed to work for my test cases.
        ISOOffset = Weekday(CDate("1/4/" & StartYear), vbMonday) + 3
        StartDay = (StartWeek * 7) - ISOOffset ' Adding 0 for start of week
        EndDay = (EndWeek * 7) + 6 - ISOOffset ' Adding 6 for end of week

        ' Set the starting day for each month, depending on leap year.
        If StartYear Mod 4 = 0 Then
            MonthSet = Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
        Else
            MonthSet = Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
        End If

        FormattedStartDate = 0:FormattedEndDate = 0

        For AryCounter = 11 To 0 Step -1
            If StartDay > MonthSet(AryCounter) And FormattedStartDate = 0 Then
                ' Using MM/DD/YYYY format - this may be different for you
                FormattedStartDate = CDate(AryCounter + 1 & _
                    "/" & StartDay - MonthSet(AryCounter) & "/" & StartYear)
            End If

            If EndDay > MonthSet(AryCounter) And FormattedEndDate = 0 Then
                FormattedEndDate = CDate(AryCounter + 1 & _
                    "/" & EndDay - MonthSet(AryCounter) & "/" & EndYear)
            End If
        Next AryCounter

        ContainedInMonth = IIf(Month(FormattedStartDate) = Month(FormattedEndDate), True, False)
    End If

End Function

I had considered something like:

If StartYear Mod 4 = 0 Then
    TempArray = LeapSet
Else
    TempArray = NonLeapSet
End If

'Now do loops

This is the final result of what was done with this code, though the code pertaining to the root question remained unchanged.

Function ContainsWhatMonths(OriginalStartDate As String, _
    OriginalEndDate As String) As Variant

    Dim MonthSet As Variant
    Dim AryCounter As Integer, ISOOffset As Integer
    Dim StartYear As Integer, EndYear As Integer
    Dim StartWeek As Integer, EndWeek As Integer
    Dim StartDay As Integer, EndDay As Integer
    Dim StartWeekStartDate As Date, StartWeekEndDate As Date
    Dim EndWeekStartDate As Date, EndWeekEndDate As Date
    Dim FormattedStartDate As Date, FormattedEndDate As Date
    Dim TotalMonths As Integer, OutputMonths As String

    StartYear = Val(Right(OriginalStartDate, 4))
    StartWeek = Val(Left(OriginalStartDate, 2))
    EndYear = Val(Right(OriginalEndDate, 4))
    EndWeek = Val(Left(OriginalEndDate, 2))

    If StartYear <= EndYear Then

        ' Using the calculation from wikipedia. Honestly, I'm not sure that
        ' I understand this bit, but it seemed to work for my test cases.
        ISOOffset = Weekday(CDate("1/4/" & StartYear), vbMonday) + 3
        StartDay = (StartWeek * 7) - ISOOffset ' Adding 0 for start of week
        EndDay = (EndWeek * 7) + 6 - ISOOffset ' Adding 6 for end of week

        ' Set the starting day for each month, depending on leap year.
        If StartYear Mod 4 = 0 Then
            MonthSet = Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
        Else
            MonthSet = Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
        End If

        For AryCounter = 11 To 0 Step -1
            If StartDay > MonthSet(AryCounter) Then
                ' Using MM/DD/YYYY format - this may be different for you
                StartWeekStartDate = CDate(AryCounter + 1 & _
                    "/" & StartDay - MonthSet(AryCounter) & "/" & StartYear)
                StartWeekEndDate = StartWeekStartDate + 6

                If Month(StartWeekStartDate) <> Month(StartWeekEndDate) Then
                    FormattedStartDate = DateSerial(StartYear, Month(StartWeekEndDate), 1)
                Else
                    FormattedStartDate = DateSerial(StartYear, Month(StartWeekEndDate) + 1, 1)
                End If

                Exit For
            End If
        Next AryCounter

        If EndYear Mod 4 = 0 Then
            MonthSet = Array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
        Else
            MonthSet = Array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
        End If

        For AryCounter = 11 To 0 Step -1
            If EndDay > MonthSet(AryCounter) Then
                EndWeekStartDate = CDate(AryCounter + 1 & _
                    "/" & EndDay - MonthSet(AryCounter) & "/" & EndYear)
                EndWeekEndDate = EndWeekStartDate + 6

                If Month(EndWeekStartDate) <> Month(EndWeekEndDate) Then
                    FormattedEndDate = CDate(Month(EndWeekEndDate) & "/1/" & EndYear) - 1
                Else
                    FormattedEndDate = CDate(Month(EndWeekEndDate) & "/1/" & EndYear)
                End If

                Exit For
            End If
        Next AryCounter

        ' Switch the commenting on these two lines to return the string
        'ContainsWhatMonths = Array()
        ContainsWhatMonths = vbNullString

        TotalMonths = (Year(FormattedEndDate) - Year(FormattedStartDate)) * 12 + _
            Month(FormattedEndDate) - Month(FormattedStartDate)

        If TotalMonths >= 0 Then

            For AryCounter = 0 To TotalMonths
                OutputMonths = OutputMonths & "," & _
                    Format(DateAdd("m", AryCounter, FormattedStartDate), "MM/YYYY")
            Next

            OutputMonths = Right(OutputMonths, Len(OutputMonths) - 1)

            ' Switch the commenting on these two lines to return the string
            'ContainsWhatMonths = Split(OutputMonths, ",")
            ContainsWhatMonths = OutputMonths
        End If

    End If

End Function


Convert decimal to binary This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.

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

void print_out_reversed(char string[])
{
    int index = strlen(string);

    while (string[index] != '\0')
        index--;

    for (int i = index; i >= 0; i--)
        putchar(string[i]);
    putchar('\n');
}

void print_decimal_number_binary(int number)
{
    if (number == 0)
    {
        printf("0\n");
        return;
    }

    char bits[sizeof(int) * 8 + 1] = {0};
    int index = 0;

    while (number > 0)
    {
        if (number % 2 == 0)
        {
            bits[index] = '0';
        }
        else
        {
            bits[index] = '1';
        }
        number = number / 2;
        index++;
    }

    print_out_reversed(bits);
}

int main()
{
    printf("enter number: ");
    int number;
    scanf("%i", &number);
    print_decimal_number_binary(number);
}

Terminology

It's important to be able to understand (and describe) what's actually going on. Your program

converts from an integer decimal string representation to an integer using scanf. This integer is then represented as a binary number in the processor.
converts from that integer back into a string representation, but rather than it being decimal, it's binary.

So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".

Use const

void print_out_reversed(char string[])

doesn't modify string, so write const char string[].

Simplify your strlen usage

This:

int index = strlen(string);

while (string[index] != '\0')
    index--;

for (int i = index; i >= 0; i--)
    putchar(string[i]);

can be

for (int i = strlen(string)-1; i >= 0; i--)
    putchar(string[i]);

It seems that you don't trust what strlen is doing, which is why you have that intermediate while loop. But that loop won't have any effect, because the null terminator will always be where strlen says it is.

Use math instead of if

This:

    if (number % 2 == 0)
    {
        bits[index] = '0';
    }
    else
    {
        bits[index] = '1';
    }

can be

bits[index] = '0' + (number & 1);

Use combined operation and assignment

This:

number = number / 2;

should be

number /= 2;

or, for speed (which the compiler will do for you anyway)

number >>= 1;


Merge adjacent numeric intervals Given a list of pairs of integers that represent closed numeric intervals, I need to output a list of intervals where the adjacent intervals are merged together. The code assumes that the intervals do not overlap and that a <= b in all pairs (a, b).

Intervals (a,b) and (c,d) are adjacent if b + 1 == c.

merge []         = []
merge [x]        = [x]
merge ((a, b):(c, d):xs)
    | b + 1 == c = merge ((a, d):xs)
    | otherwise  = (a, b):(merge ((c, d):xs))

Maybe I can simplify this and use fold or something like that? Also, would converting this to a tail recursive version make sense here?

A fold isn't a great fit for this problem, they don't support any sort of pushback so you'd have to get fancy with the accumulator value and it certainly wouldn't get any prettier.

Tail recursion isn't an important concept in Haskell ([1], [2], &c). If you have a specific performance concern feel free to bring it up, but I don't see any particular reason to think your function is more likely to blow the stack than any other.

I can't come up with any appreciably simpler solutions than yours, but you might like this version which has more reusable components.

redistributeIn :: [(a, b)] -> Maybe (a, [(b, a)], b)
redistributeIn []             = Nothing
redistributeIn xs@((a0, _):_) = (a0, insides xs, b0)
  where
    (_, b0) = last xs

    insides ((_, b):xs@((a, _):_)) = (b, a) : insides xs
    insides _                      = []

redistributeOut :: (a, [(b, a)], b) -> [(a, b)]
redistributeOut (a0, xs, b0) = outsides a0 xs b0
  where
    outsides a_i ((b_i, a_j):xs) b_z = (a_i, b_i) : outsides a_j xs b_z
    outsides a   []              b   = (a  , b  )

merge :: [(Int, Int)] -> [(Int, Int)]
merge [] = []
merge xs = redistributeOut . second (filter (not . adjacent)) . fromJust . redistributeIn $ xs
  where
    second f (a, b, c) = (a, f b, c)

    adjacent (a, b) = a + 1 == b


Create a tree from a list of nodes with parent pointers only I want you to pick my code apart and give me some feedback on how I could make it better or more simple.

class TreeNode {
    private TreeNode left;
    private TreeNode right;
    private TreeNode parent;
    int item;

    public TreeNode (TreeNode left, TreeNode right, TreeNode parent, int item) {
        this.left = left;
        this.right = right;
        this.parent = parent;
        this.item = item;
    }

    public int getItem() {
        return item;
    }

    public void setItem(int item) {
        this.item = item;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }

    public TreeNode getParent() {
        return parent;
    }

    public void setParent(TreeNode parent) {
        this.parent = parent;
    }
}

public class Ebay {

    private TreeNode root;

    public Map<TreeNode, List<TreeNode>> getMap (List<TreeNode> listOfTreeNodes) {
        final Map<TreeNode, List<TreeNode>> map = new HashMap<TreeNode, List<TreeNode>>();
        for (TreeNode treeNode : listOfTreeNodes) {
            if (map.get(treeNode.getParent()) != null) {
                map.get(treeNode.getParent()).add(treeNode);
            } else {
                List<TreeNode> list = new ArrayList<TreeNode>();
                list.add(treeNode);
                map.put(treeNode.getParent(), list);
            }
        }
        return map;
    }

    public void soStuff (List<TreeNode> listOfTreeNode)  {

        final Map<TreeNode, List<TreeNode>> map = getMap (listOfTreeNode);
        root = map.get(null).get(0);

        constructTree ( map , root);
    }

    public TreeNode constructTree (Map<TreeNode, List<TreeNode>> map, TreeNode node) {
        if (map.containsKey(node)) {
            List<TreeNode> list = map.get(node);
            node.setLeft(constructTree(map, map.get(node).get(0)));
            if (list.size() == 2) {
                node.setRight(constructTree(map, map.get(node).get(1)));
            }
        }
        return node;
    }

Your TreeNode class is mostly allright. But you have to be careful when handling trees with parent pointers, or the tree could go out of sync, and deteriorate to a weird class. A setParent on its own is silly. The setLeft and setRight should also make sure to set the parent of the new child node:

public void setLeft(TreeNode left) {
  this.left = left;
  left.parent = this;
}

Do not force a user of your class to do this bookkeeping.

Your item is weird. It is the only non-private field, and is an int. Use generics, so that your tree can carry any type.

A usable tree implementation will implement certain collection interfaces like Iterable.

Your Ebay class is very weird.

The methods getMap and constructTree are public, but are not very useful outside of that class. Both should also be static.

It is not immediately obvious what soStuff does. In seems to be a constructor, or initializer. Why not name it as such?

You use a HashMap, but do not provide a custom hashing method for TreeNode. While you inherit one from Object, this isn't terribly advisable.

What these three methods do is:

You get a list of TreeNodes which only point to their parent. The task is to link these to a full tree.
You build a map that maps parent nodes to a list of childs.
You then assign the first item in each list to parent.left, the 2nd to parent.right, if applicable.

Your solution has the advantage that it builds the tree top-down, recursively, and won't touch any nodes that will not be in the final tree. It comes at the cost of building an entirely unneccessary HashMap. The following implementation assumes that no unrelated nodes are in the input list:

/**
 * Expects a TreeNode collection where each node points to its parent.
 * Builds the full tree and returns the root (which has to have a
 * null parent).
 */
public static TreeNode linkToTree(Iterable<TreeNode> nodes) {
  /* Building the tree.
   *
   * At some point, we *will* find the root, thus getting a
   * handle on the tree. If not, "null" will be returned, which
   * is a good error case.
   *
   * Each node already knows its parent, so we just add the node
   * as a new child to the parent. We treat a "null" slot as empty.
   * First, we fill the left slot, then overwrite the right slot
   * without any checks – last one wins out.
   */

  TreeNode root;

  for (TreeNode node : nodes) {
    final TreeNode parent = node.getParent();

    // try to detect the root node
    if (parent == null) {
      root = node;
    }
    // add this node to the parent's left slot if it's empty
    else if (parent.getLeft() == null) {
      parent.setLeft(node);
    }
    // … else overwrite right slot
    else {
      parent.setRight(node);
    }
  }

  return root;
}

What did I do differently?

This method is public static. It is reusable, and does not modify any instance members.
It takes any Iterable, not just a List. Why be unneccessarily specific?
It is documented. Note that I have a large comment inside my method explaining why I wrote my code this way, and point out a certain edge case (not finding any root). Inside my if/else, I have smaller comments pointing out what each test means.
I did not use recursion. While recursion can be very elegant, it is to be avoided on the JVM.
It uses less memory than your solution, is shorter, and more elegant. Due to all of the comments, the implementation shouldn't be harder to understand than your code, even though the underlying algorithm is slightly more difficult.
I don't use nondescriptive variable names like map.


Optimization on List key comparisons and return value with HashMap Consider this code:

           public class DataSt {

            DataType time;
            DataType memory;

            public DataSt(DataType time, DataType memory)
            {
                this.time=time;
                this.memory=memory;
            }

            private static void saveIt(DataSt p, DataSt p2, String keyval, List<DataSt> comp) {
                  ...
                }

            private static void saveIt( String keyval, List<DataSt> comp) {
                     ...
         }

            public static List<DataSt> compO(List<DataSt> curR, List<DataSt> prevR) {
                Map<String,DataSt> cur = new HashMap<>();Map<String,DataSt> prev= new HashMap<>();
                for(DataSt abc:curR)
                {
                    DataSt v = new DataSt (abc.time,abc.memory);
                    cur.put(abc.key,v);
                }

                for(DataSt abc:prevR)
                {
                    DataSt values = new DataSt (abc.time,abc.memory);
                    prev.put(abc.key,v);
                }

                List<DataSt> comp = new ArrayList<DataSt>();

                for (Entry < String, DataSt > abc: cur.entrySet()) {
                    if (prev.containsKey(abc.getKey())) {
                        saveIt(abc.getValue(), prev.get(abc.getKey()), abc.getKey(), comp);
                    } else {
                        saveIt(abc.getKey(), comp);
                    }
                }

                for (Entry<String, DataSt> abc: prev.entrySet()) {
                    if (!(cur.containsKey(abc.getKey()))) {
                        saveIt(abc.getKey(), comp);
                    }
                }
                return comp;
            }
        }

With reference to the link "https://stackoverflow.com/questions/45230104/list-key-comparisons-and-return-value". It would be great if someone could review the code and suggest optimizations.

public static List<DataSt> compO(List<DataSt> curR, List<DataSt> prevR) {

    Map<String,DataSt> cur = new HashMap<>();Map<String,DataSt> prev= new HashMap<>();
   curR.parallelStream().forEach(entry -> cur.put(entry.key,new DataSt (entry.time,entry.memory)));
   prevR.parallelStream().forEach(entry -> prev.put(entry.key,new DataSt (entry.time,entry.memory)));

    List<DataSt> comp = new ArrayList<DataSt>();
    for (Entry < String, DataSt > abc: cur.entrySet()) {
        final String key = abc.getKey();
        if (prev.containsKey(key)) {
            saveIt(abc.getValue(), prev.get(key), key, comp);
        } else {
            saveIt(key, comp);
        }
    }

    for (Entry<String, DataSt> abc: prev.entrySet()) {
        final String key = abc.getKey();
        if (!(cur.containsKey(key))) {
            saveIt(key, comp);
        }
    }
    return comp;
}

Also you can try to use parallel stream on map, but it should not be HashMap, and I'm not sure that it will be faster.