texts: Finding a repeated pattern and doing something with the match

texts:
I have several implementations of finding a repeated pattern and acting on the matching input if it is found.

So I want to find this <pattern><pattern><pattern>... or, using regular expression-like syntax: <pattern>* without any additional input before or after the pattern.

The additional requirements I've put to myself are:

code captures meaning well;
regular expression simply captures pattern (no spurious characters
including ^ or $);
each character evaluated only once by regular expression;
matching will stop once a non-pattern is found (disqualifies find()
method);
single throws statement if string does not consist of repeated
pattern;
minimum number of branches, minimum of local variables;

Below is the fourth try which I think is as close to optimal as I can get:

/**
 * Goal: Match input against "<pattern>*" doing stuff with each match.
 * No spurious characters may be present at the head or tail of the input.
 *
 * Requirements:
 * <nl>
 *
code captures meaning well

 *
regular expression simply captures pattern (no spurious characters
 * including ^ or $)

 *
each character evaluated only once by regular expression

 *
matching will stop once a non-pattern is found (disqualifies find()
 * method)

 *
single throws statement if string does not consist of repeated
 * pattern

 *
minimum number of branches, minimum of local variables

 * </nl>
 *
 * @param hex
 *            the hexadecimal input
 * @return the byte array containing the hexadecimal match
 */
private static byte[] fromHex4(final String hex) {
    // setup array
    final byte[] data = new byte[hex.length() / 2];

    final Pattern hexDigits = Pattern.compile("\\p{XDigit}{2}");
    final Matcher m = hexDigits.matcher(hex);
    // optimization, m.regionEnd() could also be hex.length() I suppose
    final int end = m.regionEnd();
    // m.lookingAt() allows input to be present *after match*
    while (m.lookingAt()) {
        // do stuff with the match
        data[m.start() / 2] = (byte) Integer.parseInt(m.group(), 16);
        // start next lookingAt at end of last match
        m.region(m.end(), end);
    }
    // m.requireEnd() cannot be used here, the last find may not have
    // resulted in a match
    if (m.regionStart() != end) {
        throw new IllegalArgumentException(
                "No hexadecimal encoded byte present at character index " + m.regionStart());
    }
    return data;
}

The hexadecimal parsing is only used as an example. I know how to optimize hexadecimal parsing (up to requiring a single for loop and a single if statement if need arises). It isn't a given that the pattern always needs to capture a constant amount of characters.

Notes:

I've not used a constant value for the Pattern to aid readability for code review;
in case you're unfamiliar with the Java regexp engine: \\p{XDigit} matches a single hexadecimal character;

I've ended up using the relatively unfamiliar lookingAt, any remarks on this choice are welcome (readability, compatibility with other regex engines).


texts:
I am new to node.js and I am just wondering what you think about this code. For me, it seems there are too many conditions in the code. Is there any way to refactor it?

  var removeQuestions = function(questions) {
    if (questions.length < 1)
      return;

    var group_name = questions[0].group;
    var metagroup_name = questions[0].metagroup;

    // update count in groups
    QuestionGroupModel.find({group: group_name}).exec(function(err, groups) {
      if(!err) {
        groups[0].cnt = groups[0].cnt - questions.length;

        if(groups[0].cnt > 0) {
          groups[0].save(function(err2) {
            if(err2)
              console.info('error while updating group info');
            });
        } else {
          QuestionGroupModel.find({group: groups[0].group}).remove(function(err3) {
            if(!err3) {
              console.info('groups %s was deleted', groups[0].group);
            } else {
              console.info('error while deleting group');
            }
          });
        }
      } else {
        console.info('error while lookup group info');
      };
    });

    // delete questions
    for (var i = 0; i < questions.length; i++) {
      QuestionModel.remove({ _id: questions[i]._id }, function(err) {
        if(!err) {
          log.info("question removed");
        }
      });
    }
  };


texts: JSON API Scraper v2: Limited concurrency AJAX from a shared queue (ES2017)

texts:
Essentially the AJAX component of this question, reimplemented in ES2017 style async/await. The code connects to a remote JSON API and scrapes it using a limited number of streams to avoid triggering rate limiting when the number of pages is large. Each stream retries on server-side errors and when rate limiting kicks in, up to 3 times by default. A rate limiting 429 response also results in a 5-second wait before further requests, increasing 50% each time up to 30 seconds. Other network errors result in a thrown error with a custom message.

const Module = {};

Module.HttpError = class HttpError extends TypeError {
    constructor(result = "Network Error", ...args) {
        super(result, ...args);
        this.message =
            "Network access failed with status code " +
            result.status + ": " + result.statusText +
            " at " + result.url + ". Check your network connection.";
    }
};

/**
 * Local copy of a remote API endpoint.
 */
Module.Remote = class Remote {
    constructor(path, query = {}) {
        this.remote = new URL(path, "https://online-go.com/api/v1/");
        this.remote.searchParams.set("format", "json");
        for (let i of Object.keys(query))
            this.remote.searchParams.set(i, query[i]);

        this.meta = fetch(new URL("?page_size=1", this.remote))
            .then(r=>{
                if(r.ok) {
                    r.json();
                } else {
                    throw new Module.HttpError(r);
                }
            });
    }

    /**
     * Fetches everything from the API path specified, using a number of streams.
     *
     * @param {number=} maxStreams - number of simultaneous streams.
     * @param {number=} pageSize - size of pages to fetch.
     *
     * @return {(Array<Object>|Object)} An array of pages
     */
    async scrape(maxStreams = 5, pageSize = 100) {
        const meta = await this.meta;
        if ("count" in meta) { // Check number of pages from API metadata.
            let target = this.remote;
            target.searchParams.set("page_size", pageSize);

            const numP = Math.ceil((meta.count)/pageSize);
            let q = Array.from({length: numP}, (v, i) => i+1);
            let pages = [];
            let wait = 0;

            /**
             * Creates a stream that fetches pages from the shared queue,
             * then saves the result to the array pages.
             *
             * @param {!URL} target - the URL and path of the remote.
             * @param {number} page - the page number to fetch.
             * @param {number=} retries - maximum number of retries before error.
             * @return {number} zero on sucessful completion.
             */
            async function stream (target, page, retries=3) {
                if(wait) await sleep(5000*1.5**wait);

                target.searchParams.set("page", page);
                let result = await fetch(target);

                if(result.ok) {
                    pages[page-1] = result.json();
                    // When queue is empty, return 0.
                    return q.length?stream(target, q.shift()):0;
                } else if(result.status === 429 && retries) {
                    wait>4||(wait+=1/maxStreams); // Max wait = 5 or ~ 30 secs
                    console.warn("Too many requests! Backing off.");
                    return stream(target, page, retries-1);
                } else if(500<=result.status && retries) {
                    console.warn("Server error, retrying");
                    return stream(target, page, retries-1);
                } else {
                    throw new dvt.HttpError(result);
                }
            }

            await Promise.all(Array.from({length: maxStreams}, v => stream(target, q.shift())));

            console.info("Final wait level: " + wait);

            this.pages = pages;
            return this.pages;
        } else {
            return this.meta;
        }
    }
};

export default Module;


texts:
I'm learning C++ and thought I would try my hand at writing a basic program in modern C++. I'm always looking for ways to reduce my code to STL algorithms and simplifying areas that would require refactoring. I'm also trying to make my code as readable as possible.

Limitation

I can't modify the precision in std::to_string as far as I can see, which affects the rest of the program.

What I want

Looking for ways to simplify stuff to STL algorithms
Ensure everything is modern C++
Readability. What if I want to modify the code 3 weeks from now?
Anything else?

Code:

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>

auto fah_to_cel(double in)
{
    return (in - 32.) / 1.8;
}

int main()
{
    auto min = 0u;
    auto max = 100u;
    auto step = 5u;

    std::vector<double> temps;

    /* size_type is not necessarily the same
     * type as 0u
     */
    auto max_width = std::string::size_type(0);

    for (auto i = min; i < max; i += step)
    {
        auto width = std::to_string(i).size();
        max_width = std::max(width, max_width);
        temps.emplace_back(i);
    }

    auto header_width = sizeof("Fahrenheit") - 1;
    max_width = std::max(header_width, max_width);

    std::cout << "Fahrenheit"
              << std::string(5, ' ')
              << "Celsius"
              << "\n";

    std::cout << std::string(max_width, '-')
              << std::string(5, ' ')
              << std::string(max_width, '-')
              << "\n";

    for (auto& temp : temps)
    {
                  /* Fahrenheit column */
        std::cout << std::left  << std::setw(max_width)
                  << std::fixed << temp

                  /* Padding */
                  << std::string(5, ' ' )

                  /* Celsius column*/
                  << std::left  << std::setw(max_width)
                  << std::fixed << fah_to_cel(temp)
                  << "\n";
    }
}

Example output:

Fahrenheit     Celsius
----------     ----------
0.000000       -17.777778
5.000000       -15.000000
10.000000      -12.222222
15.000000      -9.444444
20.000000      -6.666667
25.000000      -3.888889
30.000000      -1.111111
35.000000      1.666667
40.000000      4.444444
45.000000      7.222222
50.000000      10.000000
55.000000      12.777778
60.000000      15.555556
65.000000      18.333333
70.000000      21.111111
75.000000      23.888889
80.000000      26.666667
85.000000      29.444444
90.000000      32.222222
95.000000      35.000000


texts: Find unused stored procedures/functions in SQL 2012

texts:
I was given the task of finding those unused procs/functions in our SQL 2012 database.

Initially my plan was to use the table sys.dm_exec_procedure_stats.  I could set up a job to check the table once/day and then summarize over the course of a month or a quarter.

Two problems with this: it wouldn't catch the functions and wouldn't catch stored procs with NOCOMPILE. So I decided to use extended events instead.
I didn't find the code to accomplish this exactly, so I'm adding it here in case it could save someone else some time.

CREATE EVENT SESSION [CaptureProcNames] ON SERVER
ADD EVENT sqlserver.sp_statement_starting

(
 SET collect_object_name=(1),
         collect_statement=(0)
 WHERE (
        ([object_type]=(8272) OR [object_type]=(20038))
        AND [sqlserver].[database_name]=N'MyDatabase'
        AND [sqlserver].[is_system]=(0))
)
ADD TARGET package0.event_file
(SET filename=N'C:\Program Files\Microsoft SQL Server\MSSQL11.KAIGSTAGING\MSSQL\Log\CaptureProcNames.xel',
max_file_size=(250),
max_rollover_files=(3)) WITH (MAX_MEMORY=4096 KB,
EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,
MAX_DISPATCH_LATENCY=30 SECONDS,
MAX_EVENT_SIZE=0 KB, MEMORY_PARTITION_MODE=NONE, TRACK_CAUSALITY=OFF, STARTUP_STATE=OFF)


texts:
This is the Flipping coins problem on CodeChef:

  There are \$N\$ coins kept on the table, numbered from \$0\$ to \$N - 1\$. Initially, each coin is kept tails up. You have to perform two types of operations:

  Flip all coins numbered between \$A\$ and \$B\$ inclusive. This is represented by the command "0 A B"
  Answer how many coins numbered between \$A\$ and \$B\$ inclusive are heads up. This is represented by the command "1 A B".

  Input:

  The first line contains two integers, \$N\$ and \$Q\$. Each of the next \$Q\$ lines are either of the form "0 A B" or "1 A B" as mentioned above.

  Output:

  Output 1 line for each of the queries of the form "1 A B" containing the required answer for the corresponding query.

Out of all the submissions in Python 3.5, none was able to solve it in the provided time limit (probably 0.3s, it is not specified exactly). How can I optimize my code?

n,q = map(int,input().split())
c = [0]*n
for i in range(q):
    j,k,l = list(map(int,input().split()))
    co = 0
    if j == 1:
        #do Something
        for m in range(k,l+1):
            if c[m] == 1:
                co += 1
        print(co)
    if j == 0:
        #do something
        for m in range(k,l+1):
            if c[m] == 1:
                c[m] = 0
            else:
                c[m] = 1


texts: .hasScroll function, checking if a scrollbar is visible in an element

texts:
I have constructed a function that checks whether an element has a scrollbar or not, and can also check individual axes.

I don't know if this works in all major browsers and am unsure about the performance.

Is there any way to improve upon the code, did I miss anything?
How would a javascript equivalent look like?

Note: I first asked this question on Stack Overflow, but someone suggested I should post it here instead.

Code | Example

$.fn.hasScroll = function(axis){
    var sX = this.css("overflow-x"),
        sY = this.css("overflow-y");

    if(typeof axis == "undefined"){
        //Check both x and y declarations
        if(
            (sX == "hidden" && sY == "hidden") ||
            (sX == "visible" && sY == "visible")
        ){
            return false;
        }

        if(sX == "scroll" || sY == "scroll"){
            return true;
        }
    }else{
        //Check individual axis declarations
        switch(axis){
            case "x":
                if(sX == "hidden" || sX == "visible") return false;
                if(sX == "scroll") return true;
            break;
            case "y":
                if(sY == "hidden" || sY == "visible") return false;
                if(sY == "scroll") return true;
            break;
        }
    }

    //Compare client and scroll dimensions to see if a scrollbar is needed
    var bVertical = this[0].clientHeight < this[0].scrollHeight,
        bHorizontal = this[0].clientWidth < this[0].scrollWidth;

    return bVertical || bHorizontal;
};


texts: Expressing computations on values as State

texts:
I was writing an application with a few Monads in a transformer stack. The top level application state resides in a TVar, and various components of the application operate on parts of it.

I wrote a helper function to extract those parts:

hoistStateWithLens :: S.MonadState outerState m =>
                      Simple Lens outerState innerState ->
                      S.State innerState a ->
                      m a
hoistStateWithLens acc op = do
    s <- S.get
    let sp = s ^. acc
    let (res, sp') = S.runState op sp
    S.put (s & acc .~ sp')
    return res

And I extract it from my main state as such:

runWebMState :: MonadTrans t => State appState a -> t (WebM appState) a
runWebMState x =
    let
        runWebMState_ :: State appState a -> WebM appState a
        runWebMState_ f = do
            appStateTVar <- ask
            liftIO . atomically $ do
                appState <- readTVar appStateTVar
                let (fResult, appState') = runState f appState
                writeTVar appStateTVar appState'
                return fResult
    in webM $ runWebMState_ x

Ensuring atomic access (multiple web handlers can run at once).

Using it in my application code gets pretty easy:

runRandom x = runWebMState $ hoistStateWithLens gen x

-- sample use of runRandom
get "/random" $ do
    x <- runRandom $ state . randomR (1 :: Int,100)
    text . pack . show $ x

I wanted to gather some feedback about the implementation and the idea itself. The whole project is OpenSource and available on GitHub.


texts: Finding the tallest and find the index number of the next taller guy in a circular queue

texts:
Input given is:

  Each test case contains two lines. The first line contains a single integer N (1 ≤ N ≤ 105), the number of persons playing the game. The second line contains N integers i(height) (1 ≤ hi ≤ 109) the height of the i-th person. They are numbered 1 to N starting from Druid.

Output given is:

  For each test case print N lines, in the i-th line print 2 numbers, the index of the first person taller than the i-th person on his left, and the index of the first person taller than the i-th person on his right. If no one is taller than the i-th person print -1 -1.

Input is:

3
5
172 170 168 171 169
3
172 169 172
1
172

The output obtained is:

-1 -1
 1 4
 2 4
 1 1
 4 1
-1 -1
 1 3
-1 -1
-1 -1

The code is:

t = input()

num =  []

def get_druid_index(arr,n):
     druid_max_index = arr.index(max(arr))

     if n == 1:
         num.append(-1)
         num.append(-1)

     for j in range(n):
          if j == druid_max_index:
              num.append(-1)
              num.append(-1)
          else:
              cur = arr[j]
              l = j
              r = j
              for k in range(n):

                   if arr[l] > cur:
                       num.append(l + 1)
                       break

                   if l == 0:
                       l = n

                   l = l - 1

               for k in range(n):
                   if r == n:
                       r = 0

                   if arr[r] > cur:
                       num.append(r + 1)
                       break

                   r = r + 1

for i in range(t):

   arr = []

   n = input()
   arr = raw_input()
   arr = arr.split()

   get_druid_index(arr,n)
count = 0

for i in range(len(num)/2):
    print num[count],num[count + 1]

    count = count + 2

I optimized the code as much as possible but I get TLE from the online judge. Please offer suggestions for improvements.


texts:
I have an entity called Travel which has list of costCenter. I have created a code for handling CRUD operation for cost centers

protected void assignCostCenter(CostCenterDTO costCenterDTO, Travel travel, Long detailsId) throws BusinessException {
    CostCenter costCenter = null;
    if (costCenterDTO.getCostCenters() != null) {
        Center center = commonDao.find(costCenterDTO.getCostCenters().getId());
        costCenter = costCenterDTOMapper.mapToDTO(costCenterDTO.getCostCenters(), travel, detailsId, center);
        if (costCenter != null && !travel.getCostCenters().contains(costCenter)) {
            travel.getCostCenters().add(costCenter);
        }
    } else {
        travel.setCostCenters(travel.getCostCenters().stream().filter(costCenter1 -> !(costCenter1.getDetailId().equals(detailsId))).collect(Collectors.toList()));
    }
}

And in the mapper

 public CostCenter mapToCostCenter(CostCenterDTO costCenterDTO, Travel travel, Long claimDetail, Center center) throws BusinessException {
        CostCenter costCenter = new CostCenter();
        CostCenter costCenterToUpdate = travel.getCostCenters()
                .stream()
                .filter(costCenter1 -> costCenter1.getDetailId().equals(claimDetail))
                .findFirst()
                .orElse(null);
        if (costCenterToUpdate == null) {
            costCenter.setCenter(center);
            costCenter.setTravel(travel);
            costCenter.setDetailId(claimDetail);
        } else {
            costCenterToUpdate.setCenter(center);
            return costCenterToUpdate;
        }
        return costCenter;
    }

The functionality is that if new CostCenter is assigned, I fetch Center from db which was assigned and pass to mapper. In mapper I call travel.getCostCenters to see if there is no costCenter already assigned with same detail id if there is I just update it, if there is no I create new and return, and add to list if doesn't exist. Also if CostCenterDTO comes as null then I remove from list costCenter by detailId. My question is how I could refactor it because it doesn't look tidy?


texts:
To get n-th member of a struct without non-empty bases and w/o non-public members C++ now have a pretty way:

#include <type_traits>
#include <utility>
#include <tuple>

struct filler { template< typename type > operator type (); };

template< typename aggregate, typename index_sequence = std::index_sequence<>, typename = void >
struct aggregate_arity
        : index_sequence
{

};

template< typename aggregate, std::size_t ...indices >
struct aggregate_arity< aggregate, std::index_sequence< indices... >, std::void_t< decltype(aggregate{(indices, std::declval< filler >())..., std::declval< filler >()}) > >
    : aggregate_arity< aggregate, std::index_sequence< indices..., sizeof...(indices) > >
{

};

template< std::size_t index, typename type >
constexpr
decltype(auto)
get(type & value) noexcept
{
    constexpr std::size_t arity = aggregate_arity< std::remove_reference_t< std::remove_cv_t< type > > >::size();
    if constexpr (arity == 1) {
        auto & [p1] = value;
        if constexpr (index == 0) {
            return (p1);
        } else {
            return;
        }
    } else if constexpr (arity == 2) {
        auto & [p1, p2] = value;
        if constexpr (index == 0) {
            return (p1);
        } else if constexpr (index == 1) {
            return (p2);
        } else {
            return;
        }
    } else if constexpr (arity == 3) {
        auto & [p1, p2, p3] = value;
        if constexpr (index == 0) {
            return (p1);
        } else if constexpr (index == 1) {
            return (p2);
        } else if constexpr (index == 2) {
            return (p3);
        } else {
            return;
        }
    } else /* extend it by yourself for higher arities */  {
        return;
    }
}

#include <cstdlib>
#include <cassert>

int
main()
{
    using S = struct { int i; char c; bool b; };
    S s{1, '2', true};
    decltype(auto) i = get< 0 >(s);
    decltype(auto) c = get< 1 >(s);
    decltype(auto) b = get< 2 >(s);
    static_assert(std::is_same< decltype(i), int & >{});
    static_assert(std::is_same< decltype(c), char & >{});
    static_assert(std::is_same< decltype(b), bool & >{});
    assert(i == 1);
    assert(c == '2');
    assert(b == true);
    s.i = 2;
    s.c = '3';
    s.b = false;
    assert(i == 2);
    assert(c == '3');
    assert(b == false);
    return EXIT_SUCCESS;
}

It is not as generic as one can want, but it is workable on clang from a current trunk.

It also currently not works for top level cv-qualified class (due to clang bug) and can't properly forward referenceness of the input (though, it can be implemented for non-const references), but latter is hardly desired by anybody at all (maybe there would be conversion of referenceness from xvalue to prvalue, whereas lvalueness should be still preserved).

What can I do it to improve the style and correcteness?

Live example.


texts:
Given a byte string S of length l, obtain the string D of length l-1 as D(i) = S(i) * S(i+1) (each element of D is the product of two consecutive elements of S).
here is my code.
bits 32

global start

extern exit
import exit msvcrt.dll

segment data use32 class=data
    s db 1, -3, 4, 7 ; declaring the string of bytes s
    l equ $ - s - 1 ; compute the length of the string l - 1
    d times l dw 0 ; reserve l bytes for the destination string and initialize it
segment code use32 class=code
    start:
        mov ecx, l

        mov esi, 0

        jecxz end_prog
        repeat_this:
            mov al, [s + esi] ; in al - the element on the esi position
            mov dh, [s + esi + 1] ; in dh - the element after the esi position
            imul dh ; multiplying consecutive terms
            mov [d + esi], ax; put the result in d
            inc esi ; incrementing esi to go to the next position
        loop repeat_this

        end_prog:

        push dword 0
        call [exit]

my question is did I make a mistake by declaring d times l dw 0 since I know that a byte * byte = word? Is everything else okay or should I pay attention to some details that I'm missing?


texts:
Below is my code for an attempted solution to cracking the coding interview exercise 1.8 written in python 3.5.  The problem statement is:

  Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.

I looked at the hints for this problem so I do know that my solution is not the most space efficient possible.  I believe the time complexity of the code below is \$O(M*N)\$ and the space complexity is \$O(M + N)\$.  I wrote small unit tests to test my code.  Looking for feedback on what needs to be improved, especially in terms of readability.

import unittest

def locate_zero_rows(matrix: list) -> list:
    """Given an NxM matrix find the rows that contain a zero."""
    zero_rows = [False for _ in range(len(matrix))]
    for row_num, row in enumerate(matrix):
        for col_num, element in enumerate(row):
            if element == 0:
                zero_rows[row_num] = True
    return zero_rows

def locate_zero_cols(matrix: list) -> list:
    """Given an NxM matrix find the columns that contain a zero."""
    zero_cols = [False for _ in range(len(matrix[0]))]
    for row_num, row in enumerate(matrix):
        for col_num, element in enumerate(row):
            if element == 0:
                zero_cols[col_num] = True
    return zero_cols

def zero_out(matrix: list) -> list:
    """Given an NxM matrix zero out all rows and columns that contain at least one zero."""
    zero_rows, zero_cols = locate_zero_rows(matrix), locate_zero_cols(matrix)

    for row_num, row in enumerate(matrix):
        for col_num, element in enumerate(row):
            if zero_rows[row_num] or zero_cols[col_num]:
                matrix[row_num][col_num] = 0
    return matrix

class MyTest(unittest.TestCase):
    def test_locate_zero_rows(self):
        matrix = [[5, 3, 2, 1],
                  [-3, 0, 5, 0],
                  [0, -1, 2, 6]]
        zero_rows = [False, True, True]
        self.assertSequenceEqual(locate_zero_rows(matrix), zero_rows)

    def test_locate_zero_cols(self):
        matrix = [[5, 3, 2, 1],
                  [-3, 0, 5, 0],
                  [0, -1, 2, 6]]
        zero_cols = [True, True, False, True]
        self.assertSequenceEqual(locate_zero_cols(matrix), zero_cols)

    def test_zero_out(self):
        matrix = [[5, 3, 2, 1],
                  [-3, 0, 5, 0],
                  [0, -1, 2, 6]]
        zeroed_out_matrix = [[0, 0, 2, 0],
                             [0, 0, 0, 0],
                             [0, 0, 0, 0]]
        self.assertSequenceEqual(zero_out(matrix), zeroed_out_matrix)

if __name__ == '__main__':
    unittest.main()


texts:
Is there any better way to do this?

import json

product_data = [x for x in open('product_strings.txt', 'r', encoding='utf-8').read().split(',')]
json_data = json.load(open('tedata.json', 'r', encoding='utf-8'))

for product_no in json_data:
    for product in product_data:
        if product.lower() in json_data[product_no]['name'].lower():
            print (product.lower(), json_data[product_no]['name'])
        elif product.lower() in json_data[product_no]['des'].lower():
            print (product.lower(), json_data[product_no]['name'])

tedata.json contains (6mb with ~1000 objects)

{
    "12345": {
        "owner": "BMW int",
        "doman": "20/01/2016",
        "des": "a beautiful BMW with improvements with respect to older version of bmw.",
        "dopur": "25/07/2016",
        "purchaser": "Mitsubishi, Japan",
        "name": "BMW-8"
    },
    "12346": {
        "owner": "audi",
        "doman": "20/01/2016",
        "des": "a beautiful skoda with improvements with respect to older version of skoda.",
        "dopur": "25/07/2016",
        "purchaser": "Mokoto, Japan",
        "name": "skoda-1"
    }
}

product_strings file contains (small with ~100 such string)

audi,bmw,jaguar

code for testing:

import json

tedata = """{
    "12345": {
        "owner": "BMW int",
        "doman": "20/01/2016",
        "des": "a beautiful BMW with improvements with respect to older version of bmw.",
        "dopur": "25/07/2016",
        "purchaser": "Mitsubishi, Japan",
        "name": "BMW-8"
    },
    "12346": {
        "owner": "audi",
        "doman": "20/01/2016",
        "des": "a beautiful skoda with improvements with respect to older version of skoda.",
        "dopur": "25/07/2016",
        "purchaser": "Mokoto, Japan",
        "name": "skoda-1"
    }
}"""

product_strings = "audi,bmw,jaguar"

product_data = [x for x in product_strings.split(',')]
json_data = json.loads(tedata)

for product_no in json_data:
    for product in product_data:
        if product.lower() in json_data[product_no]['name'].lower():
            print (product.lower(), json_data[product_no]['name'])
        elif product.lower() in json_data[product_no]['des'].lower():
            print (product.lower(), json_data[product_no]['name'])

##prints ===>bmw BMW-8


texts: Fast way to calculate Standing Wave modes in NumPy

texts:
I am trying to plot the standing wave modes in a 2D box over time. The equation for this is:

$$ A(x,y,t) = \sum\limits_{n,m} sin \left( \frac{n \pi x}{L_x} \right) sin \left( \frac{m \pi y}{L_y} \right) cos \left( w_{n,m}t + \phi_{n,m} \right) $$ where $$ w_{n,m} = \sqrt{ {\left( \frac{n \pi}{L_x}\right)}^2 + {\left( \frac{m \pi}{L_y}\right)}^2 }$$

The code I have used is given below:

Nx = 384
Ny = 384
Nt = 360

# function to calculate standing wave
def s_wave(ll, xx, yy, tt, pp, max_modes):
   tot_amp = 0
   Mm = 1000 # a constant relevant to my problem
   k = 0
   for m in range (1,max_modes):
       for n in range (1,max_modes):
           omega = ((m*np.pi/(ll*Mm))**2 + (n*np.pi/(ll*Mm))**2)**0.5
           amp   = np.sin(m*np.pi*xx/ll)*np.sin(n*np.pi*yy/ll)*np.cos(omega*tt-pp[k])
           tot_amp = tot_amp + amp
           k = k + 1
   return (tot_amp)

# building grid points in x and y direction
L = 6.144 # Length of the Box along each axis
T = 10 # delta_T
x = np.linspace(-L/2, L/2, Nx)
y = np.linspace(-L/2, L/2, Ny)
t = np.linspace(0, (Nt-1)*T, Nt)

modes = 60 #number of standing wave modes
phase = np.random.uniform(0,2*np.pi,modes*modes) # to introduce random phase in each mode

ustand = s_wave(L,x[None,None,:],y[None,:,None],t[:,None,None],phase,modes)

This approach works quantitatively fine with my problem. But the execution time is pretty slow. Is there any way to accelerate the execution time?

Thanks in advance.


texts:
I'm logging data from an embedded platform over UART. This gets saved to a log file and I want to process the saved log with Excel.

I have no idea whether what I did was even remotely a good solution. My VBA experience so far consists mainly of code only used once. However, since I'll have to use this for every measurement series I conduct it's probably a good idea to clean it up. Not in the least because I can't stand ugly code, I'm about to expand on it and colleagues may want to use it in the near future as well.

Example input:

00032
00016
00016
00016
00032
00064
00080
00096
00112
00128
00160
00192

The size of the input can be thousands of values. All leading zeroes get dropped as intended. Values can be negative.

Option Explicit

Public Sub Stats()
'
' Stats Macro
' Give stats to column A and draw chart with trendline.
'
' Keyboard Shortcut: Ctrl+Shift+M
'
    Columns("A:A").Select
    Selection.FormatConditions.AddColorScale ColorScaleType:=3
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
        xlConditionValueLowestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
        .Color = 7039480
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
        xlConditionValuePercentile
    Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
    With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
        .Color = 8711167
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
        xlConditionValueHighestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
        .Color = 8109667
        .TintAndShade = 0
    End With

    ActiveSheet.Shapes.AddChart2(227, xlLine).Select
    ActiveChart.SetSourceData Source:=Range("Sheet1!$A:$A")
    ActiveChart.FullSeriesCollection(1).Trendlines.Add Type:=xlMovingAvg, Period _
        :=2, Forward:=0, Backward:=0, DisplayEquation:=0, DisplayRSquared:=0, _
        Name:="2 per. Mov. Avg. (Series1)"
    ActiveChart.ClearToMatchStyle
    ActiveChart.ChartStyle = 233
    ActiveChart.FullSeriesCollection(1).Trendlines(1).Select
    With Selection.Format.Line
        .Visible = msoTrue
        .ForeColor.ObjectThemeColor = msoThemeColorAccent2
        .ForeColor.TintAndShade = 0
        .ForeColor.Brightness = -0.25
        .Transparency = 0
    End With

    Range("C1").Select
    ActiveCell.FormulaR1C1 = "Average:"
    Range("D1").Select
    ActiveCell.FormulaR1C1 = "=AVERAGE(C[-3])"
    Range("C2").Select
    ActiveCell.FormulaR1C1 = "Minimum:"
    Range("D2").Select
    ActiveCell.FormulaR1C1 = "=MIN(C[-3])"
    Range("C3").Select
    ActiveCell.FormulaR1C1 = "Maximum:"
    Range("D3").Select
    ActiveCell.FormulaR1C1 = "=MAX(C[-3])"
    Range("C4").Select
    ActiveCell.FormulaR1C1 = "Median:"
    Range("D4").Select
    ActiveCell.FormulaR1C1 = "=MEDIAN(C[-3])"
End Sub

Result looks like this:

I'm mainly worried about the lack of being generic. While ActiveCell and ActiveSheet and ActiveChart work wonders, I haven't figured out how to apply the same logic everywhere. There are still values like Sheet1 which should be set automatically for the current sheet/object/etc..


texts: Reducing verbosity of RomanNumeral class

texts:
I point to my problem in the comments of my code.

I have a class RomanNumeral:

public class RomanNumeral {

    private String romaNumera;
    private String romans = "IVXLCDM";

    public RomanNumeral(String rn) {
        //sets rn to romaNumera and checks if rn is a valid roman numeral
    }

    public boolean equals(RomanNumeral rn) {
        //overrides .equals
    }

     public String toString() {
            //overrides toString();
    }

             public int getDecimalValue() {
        float[] valueOfNumeral = new float[romaNumera.length()];
        int result = 0;
        float calculatedRomanDecimal=.5f;
        for(int i = 0; i<romaNumera.length(); i++) {

            /* My attempt at shortening the code
            for(int j = 0; j<romans.length(); j++) {

                if ( romans.charAt(j)==( romaNumera.charAt(i) ) && (j)%2==0 ) {valueOfNumeral[i] = calculatedRomanDecimal*2f;}
                if ( romans.charAt(j)==( romaNumera.charAt(i) ) && (j)%2==1 ) {valueOfNumeral[i] = calculatedRomanDecimal*5f;}
            */
        //What I am trying to do above and what I did bellow was check which               Roman numeral was which, and assign a float value to the corresponding index in a float array. Say that I have a Roman numeral MCM. MCM is romaNumera of type string, and I compare each character in romaNumera to each character in romans. Since romaNumera.charAt(0)==romans.charAt(6), I assign valueOfNumeral[0] the value of 1000
                //The stuff bellow works, but I feel like there is a more efficient way

                if (romans.charAt(0)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 1;}
                if (romans.charAt(1)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 5;}
                if (romans.charAt(2)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 10;}
                if (romans.charAt(3)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 50;}
                if (romans.charAt(4)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 100;}
                if (romans.charAt(5)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 500;}
                if (romans.charAt(6)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 1000;}

        }

        result = Math.round(valueOfNumeral[romaNumera.length()-1]);
        for (int j = valueOfNumeral.length-2; j>=0; j--){
            if (valueOfNumeral[j]<valueOfNumeral[j+1])
                result -= Math.round(valueOfNumeral[j]);
            else result += Math.round(valueOfNumeral[j]);
        }

        return result;
    }

} // class RomanNumerals

This compiles and does what I want it to do, however, I am trying to find a way to shorten the program so it doesn't require so many if statements.


texts: Finding the minimum difference in a list of numbers

texts:
I have written following code to find the minimum difference from a list of numbers.

Because I am using a loop once and LINQ again to find the minimum, the algorithm is O(N2).

Can you please tell me if I am using the framework in the most optimal way (speed and memory utilisation) to achieve this task:

using (StreamReader sr = new StreamReader("IN.in"))
using (StreamWriter sw = new StreamWriter("OUT.out"))
{
    int T = int.Parse(sr.ReadLine());
    for (int i = 1; i <= T; i++)
    {
        int N = int.Parse(sr.ReadLine());
        List<int> intList = sr.ReadLine().Split(' ').Select(e => int.Parse(e)).ToList();
        intList.Sort();

        List<int> diff = new List<int>();
        int leastDiff = int.MaxValue;
        for (int k = 0; k < intList.Count - 1; k++)
        {
            int iDiff = intList[k + 1] - intList[k];
            diff.Add(iDiff);
            leastDiff = Math.Min(leastDiff, iDiff);
        }
        sw.WriteLine(leastDiff);
    }
}

Benchmark

For 3 test case of 5 integers in each list where as for loop implementation takes 55±5 ms. Mr.Mindor LINQ implementation timing varies from 60±50 ms. Memory usage in both implementation is almost 8.3MB


texts:
I've built a class for an e-commerce Item, and the ShoppingCart class for checkout functions.

The thing I'm most concerned about is my use of pointers.  I think I've used them properly in this situation, but I could be wrong.

Item.hpp

#ifndef Item_hpp
#define Item_hpp

#include <iostream>
using namespace std;

class Item {

private:
    string name;
    double price;
    int quantity;

public:
    void setName(string);
    void setPrice(double);
    void setQuantity(int);
    string getName();
    double getPrice();
    int getQuantity();

    // Constructors
    Item();

    Item(string, double, int);

};

#endif

Item.cpp

#include "Item.hpp"
#include <iostream>
using namespace std;

Item::Item() {
    name = "";
    price = 0.0;
    quantity = 0;
}

Item::Item(string itemName, double itemPrice, int itemQuantity) {
    setName(itemName);
    setPrice(itemPrice);
    setQuantity(itemQuantity);
}

void Item::setName(string itemName) {
    name = itemName;
}

void Item::setPrice(double itemPrice) {
    price = itemPrice;
}

void Item::setQuantity(int itemQuantity) {
    quantity = itemQuantity;
}

string Item::getName() {
    return name;
}

double Item::getPrice() {
    return price;
}

int Item::getQuantity() {
    return quantity;
}

ShoppingCart.hpp

#ifndef ShoppingCart_hpp
#define ShoppingCart_hpp

#include "Item.hpp"
#include <iostream>
using namespace std;

class ShoppingCart {

private:
    Item* itemArray[100];
    int arrayEnd;

public:
    void addItem(Item *);
    double totalPrice();

    // Constructors
    ShoppingCart();

};
#endif

ShoppingCart.cpp

#include "ShoppingCart.hpp"
#include "Item.hpp"
#include <iostream>
using namespace std;

ShoppingCart::ShoppingCart() {
    for (int i=0; i<100; i++) {
        itemArray[i] = {NULL};
    }
    arrayEnd = 0;
}

void ShoppingCart::addItem(Item *currentItem) {
    itemArray[arrayEnd] = currentItem;
    arrayEnd++;
}

double ShoppingCart::totalPrice() {
    double totalPrice;

    for (int i=0; i<100; i++) {
        if (itemArray[i] != NULL) {
            totalPrice += itemArray[i]->getPrice() * itemArray[i]->getQuantity();
        } else {
            break;
        }
    }

    return totalPrice;
}


texts: Adding action id to a history repository

texts:
In my system I have a history repository.
My history class is big and with a lot of information regarding operations.
My warehouse needs, for some actions to know which histories are caused by the same action.

My first idea was to create an overloaded version of each method requiring to write histories and make all the clients using that services create and supply a guid if they want to specify an action.

As my system has a lot of services that some use other services and a lot of clients that may need to specify an action that solution sounds bad. Complicated, error prone and would pollute code that is not interested in knowing anything about this.

My solution:
I created a ActionIdContext class that my clients can use to specify a group action and then my HistoryBuilder uses a static property to get the current ActionId if any. This way no services or overloads have to be created or changed.

Do you like this design or maybe you have another idea?

public class ActionIdContext : IDisposable
{
    private static Guid? actionId;
    private readonly bool isActionIdSet;

    public ActionIdContext()
    {
        if (actionId == null)
        {
            actionId = Guid.NewGuid();
            isActionIdSet = true;
        }
    }

    public static Guid? ActionId
    {
        get { return actionId; }
        set { actionId = value; }
    }

    public void Dispose()
    {
        if (isActionIdSet)
        {
            actionId = null;
        }
    }
}

public class HistoryBuilder
{
    private string text;

    public HistoryBuilder SetText(string value)
    {
        this.text = value;
        return this;
    }

    public History Build()
    {
        return new History()
        {
            Text = text,
            ActionId = ActionIdContext.ActionId
        };
    }
}

public class Client
{
    private readonly ISomeService someService;

    public Client(ISomeService someService)
    {
        this.someService = someService;
    }

    public void DoSomeAction()
    {
        someService.DoSomething("Flying in the sky");
    }

    public void DoSomeGroupAction()
    {
        using (new ActionIdContext())
        {
            someService.DoSomething("Driving in the corner");
            someService.DoSomething("Reading Hulk!");
            someService.DoSomething("Doing math");
        }
    }
}


texts:
Summary

I have a normal class which has a normal property but that property has access to an async backing field.

I'm not sure if this is the best/acceptable way to access the asyc method for this backing field.

Details

I've got a C# library that helps testing the .NET HttpClient class.

This class has a property public HttpContent HttpContent which is access two private backing fields which some code uses later on.

One of these private backing fields is populated via an async method. This, being a property, isn't async.

When the value of this property is set, I extract the actual string content from it by calling the method _httpContent.ReadAsStringAsync() and also remember a reference to this instance via a class-global variable.

The actual code in question is this

private string _httpContentSerialized;

....

_httpContentSerialized = _httpContent == null
    ? "*"
    : Task.Run(_httpContent.ReadAsStringAsync).Result;

As such, I'm not sure if the code I have (which seems to work, mind you) is the best way to do this and I'm hoping someone can review this (as opposed to asking on SO for a 'how to do this' answer).

Extra Info to consider:

Being a library I have no idea how/where my library will be consumed/used:

A console app?
An ASP.NET app?

With this in mind, I'm not sure if the code I have written is acceptable and won't cause deadlocks for a .NET application.

Other suggestions have been to use _httpContent.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();

Here's some more of the code:

public class HttpMessageOption
{
    private HttpContent _httpContent;
    private string _httpContentSerialized;

    public HttpContent HttpContent
    {
        get { return _httpContent; }
        set
        {
            _httpContent = value;
            _httpContentSerialized = _httpContent == null
                ? "*"
                : Task.Run(_httpContent.ReadAsStringAsync).Result;
        }
    }
}


texts:
Print sums of all subsets of a given set

Problem summary : Print all subset sums of a given set of integers

My approach is to store previous results and use them to calculate new (similar idea as DP).

SubsetSum.cpp

#include<iostream>
#include<vector>
//using namespace std;

bool isPowerOf2 (long long x)
{
  /* First x in the below expression is for the case when x is 0 */
    return x && (!(x&(x-1)));
}

std::vector<long long> subsetSums(std::vector<int> set)
{
    long long total = 1<<set.size();    //total number of subsets = size of power set = 2^n
    std::vector<long long> sums(total, 0);
    sums[1] = set[0];
    //std::cout << sums[0] << std::endl;
    //std::cout << sums[1] << std::endl;
    int effectiveBits = 1, prevPowOf2 = 1;
    for (long long i = 2; i < total; ++i)
    {
        if (isPowerOf2(i))
        {
            ++effectiveBits;
            prevPowOf2 *= 2;
        }
        //std::cout << "e = " << effectiveBits << "\tp = " << prevPowOf2 << std::endl;

        sums[i] = set[effectiveBits-1] + sums[i-prevPowOf2];
        //std::cout << sums[i] << "\n";
    }

    return sums;
}

// Driver code
int main()
{
    std::vector<int> set = {5, 4, 3};

    std::vector<long long> sumsOfAllSubsets = subsetSums(set);
    for (auto sum : sumsOfAllSubsets)
        std::cout << sum << "\n";
    return 0;
}

You can find the code on Github Gist and compilation result at OnlineGdb.

Along with code, please also comment on the algorithm itself.
Is it advisable to store previous result in practice (since it takes 2^n space)?
Also, is there any scope of improving time or space without trading-off the other?


texts:
I'm new to python, and after doing a few tutorials, some about scraping, I been trying some simple scrapping on my own. Using beautifulsoup I manage to get data from webpages where everything has labels, but without them I'm doing a poor job.

I'm trying to get the dollar exchange rate from:
http://www.bancochile.cl/cgi-bin/cgi_mone?pagina=inversiones/mon_tasa/cgi_mone

The value I'm after is highlighted in yellow

After a lot of trial and error, I manage to get the dollar exchange rate, but I think there has to be a better way.

import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.bancochile.cl/cgi-bin /cgi_mone?pagina=inversiones/mon_tasa/cgi_mone")
soup = BeautifulSoup(page.content, 'html.parser')

tables = soup.find_all("table")
dollar = tables[4].find_all("td")

print(dollar[5].string)

Is there a better, or more correct way to do this? Also, I'm not sure if the problem is in the way I coded, or in not being able to better understand the html structure, to navigate to the information in a more efficient way.


texts:
Just out of curiosity, I have this code lying around a personal project in which I will generate lots of dummy customer data.
Here's the code:
faker = Faker()
# Faker.seed(random.randint(0, sys.maxsize))

async def get_random_customer_login(count: int, user: CustomerLogin_PydanticIn) -> list:
    data = []

    for i in range(count):
        plain_email = user.plain_email
        user_ip = user.user_ip
        user_id = user.user_id
        client_id = user.client_id
        result = user.result
        fail_cause = user.fail_cause
        process = user.process
        user_agent = user.user_agent
        device_token = user.device_token
        event_timedate = user.event_timedate

        if plain_email is None:
            plain_email = await get_random_email()

        if user_ip is None:
            user_ip = await get_random_ip_address()

        if user_id is None:
            user_id = uuid.uuid4()

        if client_id is None:
            client_id = await get_random_client_id()

        if result is None:
            result = await get_random_result()

            if 'AUTHENTICATION_SUCCESS' not in result:
                fail_cause = await get_random_fail_cause()
                if fail_cause is None:
                    fail_cause = await get_random_fail_cause()

        if process is None:
            process = await get_random_ub_process()

        if user_agent is None:
            user_agent = await get_random_user_agent()

        if device_token is None:
            device_token = uuid.uuid4()

        if event_timedate is None:
            event_timedate = await get_random_utc_timestamp()

        customer_login = CustomerLogin_PydanticIn(
            event_timedate=event_timedate,
            user_id=user_id,
            device_token=device_token,
            user_ip=user_ip,
            user_agent=user_agent,
            client_id=client_id,
            process=process,
            result=result,
            fail_cause=fail_cause,
            plain_email=plain_email)
        data.append(customer_login)
    return data

async def get_random_email() -> str:
    return faker.ascii_company_email()

async def get_random_ip_address() -> str:
    return faker.ipv4_public()

async def get_random_ub_process() -> str:
    return faker.random_element(elements=PROCESS_LIST)

async def get_random_client_id() -> str:
    return faker.random_element(elements=CLIENT_ID_LIST)

async def get_random_result() -> str:
    return faker.random_element(elements=RESULT_LIST)

async def get_random_fail_cause() -> str:
    return faker.random_element(elements=FAILURE_CAUSE_LIST)

async def get_random_user_agent() -> str:
    return faker.user_agent()

async def get_random_utc_timestamp() -> datetime.datetime:
    return pytz.utc.localize(faker.date_time_this_century())

Basically, this function takes in a count of dummy data to be created, and the CustomerLogin pydantic object. The catch is the function will assign some randomly generated value of fields in CustomerLogin that are not provided.
Anyway, this code works. However, I think there's a lot of room to optimize and should I set faker seed?


texts: Copy a directory from source to destination

texts:
I wrote a program that copies a directory from a source to a destination, similar to the cp utility.

For this, I used the essential functions:

open(), write(), mkdir(), readdir().

This is the source code (ignore the main() function, this is not the final form):

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int isDirectory(char*);
int copyFile(char*, char*);
int copyDirectory(char*, char*);

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

  copyDirectory(*(argv + 1), *(argv + 2));

  return 0;
}

int isDirectory(char *path) {
   struct stat statbuf;

   if (stat(path, &statbuf) == -1) {
      return -1;
   }
   else {
      return S_ISDIR(statbuf.st_mode);
   }
}

int copyFile(char *source, char *destination) {
  if((source == NULL) || (destination == NULL)) {
    return -1;
  }

  struct stat statbuf;
  int fdr, fdw, rv;
  char buff[256];

  stat(source, &statbuf);
  if(!S_ISREG(statbuf.st_mode)) {
    return 1;
  }

  fdr = open(source, O_RDONLY);
  fdw = open(destination, O_CREAT|O_WRONLY, S_IREAD|S_IWRITE);

  while((rv = read(fdr, &buff, 128))) {
    write(fdw, &buff, rv);
  }

  return 0;
}

int copyDirectory(char *source, char *destination) {
  if((source == NULL) || (destination == NULL)) {
    return -1;
  }

  struct dirent *entry;
  DIR *dr;
  char sourcePatch[512], destinationPatch[512];

  strcpy(sourcePatch, source);
  strcpy(destinationPatch, destination);
  strcat(destinationPatch, "/");
  strcat(sourcePatch, "/");

  if(!isDirectory(source)) {
    return -1;
  }

  if(opendir(destination) == NULL) {
    mkdir(destination, 0700);
  }

  dr = opendir(source);
  while((entry = readdir(dr))) {
    strcat(sourcePatch, entry->d_name);
    strcat(destinationPatch, entry->d_name); //printf("%s\n", sourcePatch);

    if(isDirectory(sourcePatch) && strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
      copyDirectory(sourcePatch, destinationPatch);
    }
    else {
      copyFile(sourcePatch, destinationPatch);
    }

    *sourcePatch = '\0'; *destinationPatch = '\0';
    strcpy(sourcePatch, source);
    strcpy(destinationPatch, destination);
    strcat(destinationPatch, "/");
    strcat(sourcePatch, "/");
  }

  return 0;
}

Is there a better way for doing this?

Comparing my program, to the GNU cp program, I get this results:

[marius@arch labs]$ gcc -Wall cp.c -g -O3 -o cp
[marius@arch labs]$ time ./cp ~/Desktop/management ~/Desktop/testtest

real    0m0.139s
user    0m0.003s
sys     0m0.133s
[marius@arch labs]$ time cp -r ~/Desktop/management ~/Desktop/testtest2

real    0m0.018s
user    0m0.000s
sys     0m0.017s

And what about this code, can I make some improvements?


texts: C++ custom exception handling using std::error_category and std::system_error

texts:
I want to make my own custom exception handling and I am curious if I am going the right path, maybe some of you could suggest to me how I could improve it? Or maybe I have went the wrong direction? (Also it would be amazing to know how I could make this piece of code more of a modern C++.)
Here is a simple namespace with classes, which inherits from std::error_category and std::system_error.
#include <string>
#include <system_error>
#include <iostream>

namespace CustomException {

    class ErrorC : public std::error_category {
        using Base = std::error_category;
    public:
        char const *name() const noexcept
        override { return "App error"; }

        std::error_condition default_error_condition(int const code) const noexcept
        override {
            (void) code;
            return {};
        }

        bool equivalent(int const code, std::error_condition const &condition) const noexcept
        override {
            (void) code;
            (void) condition;
            return false;
        }

        bool equivalent(std::error_code const &code, int const condition) const noexcept
        override { return Base::equivalent(code, condition); }

        std::string message(int const condition) const
        override { return "An application error occurred, code = " + std::to_string(condition); }

        constexpr ErrorC() : Base{} {}
    };

    auto app_error_category()
    -> ErrorC const & {
        static ErrorC the_instance;
        return the_instance;
    }

    enum class BreakErrorCode {
        FAILED_INIT_BREAKS = 1,
        FAILED_TO_LINK_BREAKS = 2,
    };

    class BreakError : public std::system_error {
        using Base = std::system_error;
    public:
        BreakErrorCode appErrorCode() const {
            return static_cast<BreakErrorCode>(code().value());
        }

        explicit BreakError(const BreakErrorCode code)
                : Base{(int) code, app_error_category()} {
        }

        BreakError(const BreakErrorCode code, const std::string &description)
                : Base{(int) code, app_error_category(), description} {
        }
    };

    enum class EngineErrorCode {
        FAILED_INIT_ENGINE = 101,
        MOTHER_BOARD_FAILED_LINKING = 102,
    };

    class EngineError : public std::system_error {
        using Base = std::system_error;
    public:
        EngineErrorCode appErrorCode() const {
            return static_cast<EngineErrorCode>(code().value());
        }

        EngineError(const EngineErrorCode code)
                : Base{(int) code, app_error_category()} {
        }

        EngineError(const EngineErrorCode code, const std::string &description)
                : Base{(int) code, app_error_category(), description} {
        }
    };

    enum class ControlErrorCode {
        CONTROL_GIMBAL_FAILED = 301,
        OBTAIN_CONTROL_AUTHORITY_FAILED = 302,
    };

}

Main.cpp, which invokes methods throwing exceptions from previously declared namespace.
using namespace CustomException;

void initEngine() {
    throw EngineError(EngineErrorCode::FAILED_INIT_ENGINE, "Failed init engine");
}

void initBreaks() {
    throw BreakError(BreakErrorCode::FAILED_INIT_BREAKS, "Failed init breaks");
}

int main() {
    try {
        initEngine();
        initBreaks();
    }
    catch (const BreakError &error) {
        std::cout << error.what() << std::endl;
    }
    catch (const EngineError &error) {
        std::cout << error.what() << std::endl;
    }
    catch (...) {
        std::cout << "Caught something unexpected error" << std::endl;
    }
    return 0;
}

I would appreciate very much any kind of comments / help.


texts:
My goal was to create class, that can run external method in non blocking manner.
Second requirement was to be able to abort method run if it is needed (i.e. running user script).
I decided to do that with Thread instead of Task, because only Thread can be truly aborted.
Because Thread have big creation overhead, it is initialized and started in advance and resumed if work is needed.

What do you think about my implementation ?

Example usage:

//generic type param is used as external method argument (instead of object)
AbortableStepWorker<int> worker = new AbortableStepWorker<int>(someMethodWithIntArgument);
worker.Start();
worker.DoWork(someArgument);
while(!worker.WaitForWorkDone(someTimeout))
    if(cancelWasRequested)
    {
        worker.Stop(lastChanceTimeout);
        return false;
    }

//if we've managed to get here, then work was done
//run result:
var result = !worker.Stopped;

and class implementation:

public class AbortableStepWorker<T> : IDisposable
    {
        public AbortableStepWorker(Func<T, bool> externalWork)
        {
            if (externalWork == null) throw new ArgumentNullException("workMethod");
            this.externalWork = externalWork;

            ThreadInstance = new Thread(Worker) { Priority = ThreadPriority.BelowNormal };
        }

        private readonly Func<T, bool> externalWork;
        private T externalWorkParam;
        private void Worker()
        {
            try
            {
                while (true)
                {
                    resumeEvent.WaitOne(Timeout.Infinite);

                    if (stopRequested)
                        return;

                    if (!externalWork(externalWorkParam))
                        return;

                    workDoneEvent.Set();
                }
            }
            catch (ThreadAbortException) { }
            finally { workDoneEvent.Set(); }
        }

        private bool stopRequested = false;
        private AutoResetEvent resumeEvent = new AutoResetEvent(false);
        private ManualResetEvent workDoneEvent = new ManualResetEvent(false);

        public Thread ThreadInstance { get; private set; }

        public void Start()
        {
            ThreadInstance.Start();
        }

        /// <summary>
        /// Allows inner thread to do externalWork call.
        /// </summary>
        public void DoWork(T param)
        {
            externalWorkParam = param;
            workDoneEvent.Reset();
            resumeEvent.Set();
        }

        /// <summary>
        /// Waits for DoWork to finish.
        /// </summary>
        /// <param name="millisecondsTimeout">Timeout.</param>
        /// <returns>True if work is not still running.</returns>
        public bool WaitForWorkDone(int millisecondsTimeout)
        {
            return workDoneEvent.WaitOne(millisecondsTimeout);
        }

        /// <summary>
        /// Waits specified time for worker method to end. If time elapsed, aborts thread.
        /// </summary>
        /// <param name="millisecondsTimeout">Timeout before thread abort.</param>
        public void Stop(int millisecondsTimeout = 0)
        {
            if (Stopped)
                return;

            bool wasWorking = !workDoneEvent.WaitOne(0);
            stopRequested = true;
            resumeEvent.Set();

            if (!ThreadInstance.Join(wasWorking ? millisecondsTimeout : Timeout.Infinite))
                ThreadInstance.Abort();
        }

        public bool Stopped
        {
            get
            {
                return ThreadInstance.Join(0);
            }
        }

        #region IDisposable
        public void Dispose()
        {
            if (ThreadInstance.ThreadState != ThreadState.Unstarted)
            {
                Stop();
                ThreadInstance.Join();
            }
            resumeEvent.Dispose();
            workDoneEvent.Dispose();
        }
        #endregion //IDisposable
    }


texts:
I'm trying to refactor the working code below which intends to handle bill cancellation, but doesn't seem "linear" enough.
open FSharpPlus
open FSharpPlus.Data

type BillCancellationReason = | A | B
type OrderBillingCommand = | A | B
type OrderBillingEvent = | A | B
type CommandError = | A | B

type BillCancellationRequest =
    { BillSequence: int32
      Reason: BillCancellationReason
      Comment: string }

type BillCancellationsRequestPart =
    { OrderId: int32
      BillSequence: int32
      Reason: BillCancellationReason
      Comment: string }

type BillCancellationsRequest = BillCancellationsRequestPart list

module Validation =
    // Validation<'Failure list, 'Success> list -> Validation<'Failure list, 'Success list>
    let cumulativeFoldList (validations: Validation<'Failure list, 'Success> list):
        Validation<'Failure list, 'Success list> =
        traverse id validations

// BillCancellationsRequestPart -> Validation<CommandError list, (int32 * OrderBillingCommand)>
let toCommand (requestPart: BillCancellationsRequestPart) =
    Unchecked.defaultof<Validation<CommandError list, (int32 * OrderBillingCommand)>>

// (int32 * OrderBillingCommand) list -> Async<Result<OrderBillingEvent list, CommandError list>>
let processValidCommands (commands: (int32 * OrderBillingCommand) list) =
    Unchecked.defaultof<Async<Result<OrderBillingEvent list, CommandError list>>>

// BillCancellationsRequest -> Async<Result<OrderBillingEvent list,CommandError list>>
let cancelBills (request: BillCancellationsRequest) =
    async {
        match request |> List.map toCommand |> Validation.cumulativeFoldList with
        | Success commands -> return! processValidCommands commands
        | Failure failure -> return Error failure
    }

In particular this last bit:
// BillCancellationsRequest -> Async<Result<OrderBillingEvent list,CommandError list>>
let cancelBills (request: BillCancellationsRequest) =
    async {
        match request |> List.map toCommand |> Validation.cumulativeFoldList with
        | Success commands -> return! processValidCommands commands
        | Failure failure -> return Error failure
    }

I tried to come up with a new module but I found myself rolling a lot more code:

module Result =
    // ('T -> 'U) -> ('V -> 'W) -> Result<'T, 'V> -> Result<'U, 'W>
    let bimap okMapping errorMapping result =
        result
        |> Result.map okMapping
        |> Result.mapError errorMapping

    // Result<Async<'T>, 'U> -> Async<Result<'T, 'U>>
    let awaitOnOk result =
        async {
            match result with
            | Ok ok ->
                let! awaitedOk = ok
                return Ok awaitedOk
            | Error error ->
                return Error error
        }

// BillCancellationsRequest -> Async<Result<OrderBillingEvent list,CommandError list>>
let cancelBills (request: BillCancellationsRequest) =
    request
    |> List.map toCommand
    |> Validation.cumulativeFoldList
    |> Validation.toResult
    |> Result.map processValidCommands
    |> Result.awaitOnOk
    |> Async.map Result.flatten

I'm wondering if there is like a better and more concise approach to achieve that?
Note: Unchecked.defaultof<...> has been used just for the sake of making the code above to compile.


texts: Download, unzip and parse xml into pandas dataframe

texts:
I have a python script that downloads, unzip and parses an XML file published by a Canadian institution. Only some very specific tags are extracted and then all put into a pandas dataframe for later processing.

Everything works well. I just wonder if there is room for improvement here, specially in the parsing part. I am not sure if the nested for I use are a good idea or there is a better and cleaner way to parse.

import requests
import zipfile
import os
import glob
from lxml import etree
from io import StringIO, BytesIO
import pandas as pd
import xml.etree.ElementTree as ET

def download_file(url,filename):
    r = requests.get(url, allow_redirects=True)
    open(filename, 'wb').write(r.content)

def unzip_and_delete(filename):
    zip_file = zipfile.ZipFile(filename,'r')
    zip_file.extractall()
    zip_file.close()
    os.remove(filename)

def parse_xml_fields(file, base_tag, tag_list,final_list):
    root = etree.parse(file)
    nodes = root.findall("//{}".format(base_tag))
    for node in nodes:
        item = {}
        for tag in tag_list:
            if node.find(".//{}".format(tag)) is not None:
                item[tag] = node.find(".//{}".format(tag)).text.strip()
        final_list.append(item)

# My variables
field_list = ["MsbRegistrationNumber","StatusDescriptionEnglish","Surname","GivenName","MiddleName","Name","StreetAddress"]
entities_list = []

download_file('http://www10.fintrac-canafe.gc.ca/msb-esm/public/msb-search/zipdownload-eng/', 'fintrac.zip')

unzip_and_delete('fintrac.zip')

parse_xml_fields("MsbRegistryPublicDataFile.xml", "MsbInformation", field_list, entities_list)

df = pd.DataFrame(entities_list, columns=field_list)

df.to_excel("Canada_MSB_List.xlsx")


texts:
I needed a method to test whether a given file is in use. Is the code below up to the task?

Public Function IsFileInUse(path As String) As Boolean
    If IO.File.Exists(path) Then
        Try
            Using fs = IO.File.OpenWrite(path)
                'If stream can write to the file, it suggests the file is not in use.
                Return Not fs.CanWrite
            End Using
        Catch ex As Exception
            'An exception was raised when trying to create a write stream
            'This suggests the file is in use.
            Return True
        End Try
    Else
        'File does not exists, therefore it is not in use:
        'a file could be written anew to the provided path.
        Return False
    End If
End Function


texts:
I have implemented a primitive ArrayList class in C++ as part of an attempt to learn about data structures and their optimizations. It currently has:

Constructor/destructor
Overloaded [] operator
bool insert()
bool remove()
short LinearSearch()
short BinarySearch()

insert and remove return a bool indicating success or failure. insert can accept a negative number to insert from the end towards the front (-2 is the 2nd to last element); by default, insert is called with index = 1. The search functions return a short indicating the index, or -1 if it is not found.

It uses templates to allow for multiple types of data stored, but I am currently only concerned with number and boolean data types to be stored. If you have any tips or optimizations regarding the current functions, or operators/other functions that I should consider, please tell me. Thank you for your help.

Code:

#include <cstdlib> // for calloc/malloc

namespace structures {
    template<typename T> class ArrayList {
        private:
            T* pointer;
        public:
            ArrayList(unsigned short len = 10);
            ~ArrayList();
            T& operator[](unsigned short index);
            const T& operator[](unsigned short index) const;
            unsigned short length;
            bool insert(const T& element, short index = -1);
            bool remove(unsigned short index);
            short LinearSearch(const T& element) const;
            short BinarySearch(const T& element) const;
    };

    template<typename T> ArrayList<T>::ArrayList(unsigned short len) {
        length = 0;
        pointer = (T*)calloc(len, sizeof(T));
    }

    template<typename T> ArrayList<T>::~ArrayList() {
        free(pointer);
    }

    template<typename T> T& ArrayList<T>::operator[](const unsigned short index) {
        if (index > length) throw;
        return pointer[index];
    }

    template<typename T> const T& ArrayList<T>::operator[] (const unsigned short index) const {
        if (index > length || index < 0) throw;
        return pointer[index];
    }

    template<typename T> bool ArrayList<T>::insert(const T& element, short index) {
        if (index > (short)length) return false;
        if (index < 0) index = length + index + 1;
        if (length == sizeof(*pointer)/sizeof(T)) {
            pointer = (T*)realloc(pointer, 2 * sizeof(*pointer)/sizeof(T));
        }
        if (index == length || index == -1) pointer[index] = element;
        else {
            for (short i = length; i > index; --i) {
                pointer[i] = pointer[i-1];
            }
            pointer[index] = element;
        }
        ++length;
        return true;
    }

    template<typename T> short ArrayList<T>::LinearSearch(const T& element) const {
        for (short i = 0; i < length; ++i) {
            if (pointer[i] == element) return i;
        }
        return -1;
    }

    template<typename T> short ArrayList<T>::BinarySearch(const T& element) const{
        short left = 0;
        short right = length - 1;
        short middle = (length - 1) / 2;
        while (true) {
            if (left > right) return -1;
            if (element == pointer[middle]) return middle;
            if (element > pointer[middle]) left = middle + 1;
            else right = middle - 1;
            middle = (left + right) / 2;
        }
    }

    template<typename T> bool ArrayList<T>::remove(unsigned short index) {
        if (index > length || index < 0) return false;
        for (; index < length; ++index) {
            pointer[index] = pointer[index + 1];
        }
        --length;
        return true;
    };
}


texts: Capitalize the first character of all words (even when following a '-')

texts:
I got it working, all variations are displayed Sint-Anna as should be, but I wonder, is there a simpler way to this, since it looks very cluttered?

String.prototype.capitalize = function(){
    var sa = this.replace(/-/g,' ');
    var saa = sa.toLowerCase();
    var sb = saa.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
    var sc = sb.replace(/\s+/g, '-');
    return sc;
};

console.log('sint-anna'.capitalize());
console.log('sint anna'.capitalize());
console.log('sint-Anna'.capitalize());
console.log('Sint Anna'.capitalize());
console.log('SiNt anna'.capitalize());
console.log('SINT ANNA'.capitalize());

Console:

Sint-Anna
Sint-Anna
Sint-Anna
Sint-Anna
Sint-Anna
Sint-Anna

There are no ways that there is a wrong input like Si ntAn na resulting in Si-Ntan-Na.


texts: Stack implementation using arrays in Java

texts:
Could someone please review my code and let me know if there is any scope for optimization for better performance.

package com.gmail.practice;

import java.util.Arrays;

public class Stacks {

private int top;
int size;
int[] stack;

public Stacks(int arraysize)
{
    size = arraysize;
    stack = new int[size];
    top = -1;
}

public void push(int value)
{
    if(top == size-1)
    {
        System.out.println("the value cant be pushed: Stack underflow");
    }
    else{
        top = top+1;
        stack[top] = value;
    }
}

public void pop()
{
    if(top > size-1)
    {
        System.out.println("stack is overflow");
    }else{
        top = top-1;
        System.out.println("current top value is " + " " +stack[top]);
        System.out.println("the popped value is" + " " + stack[top+1]);
    }

}

public void display()
{
    for(int i=0;i<size-1;i++)
        System.out.println(stack[i]);
}

public static void main(String[] args)
{
    Stacks s = new Stacks(5);
    s.push(10);
    s.push(15);
    s.push(19);
    s.push(3);
    s.pop();
    s.push(4);
    s.display();
    s.pop();
    s.pop();
    s.display();
}
}


texts:
The code below is converting: data from one format to another

# input sample
{
  productText: [
    {
      "language": "en",
      "version": "1",
      "sequence": 1,
      "text": "blah",
      "textType": "ROMANCE"
    }
  ]
}

# output sample
{
  productText: [
    {
      sequence: 1,
      textType: "ROMANCE"
      text: [
        {
          text: "blah",
          language: "en",
          version: "1",
        }
      ]
    }
  ]
}

The source:

deserialize: (profileJSON)->
  return profileJSON unless profileJSON.productText?
  profileJSON.productText = _(profileJSON.productText).reduce(
    (acc, el)->
      current  = _(acc).findWhere(
        _(el).pick('sequence', 'textType')
      )
      unless current?
        current = _(el).pick('sequence', 'textType')
        current.text = []
        acc.push(current)
      current.text.push(
        _(el).pick('version', 'text', 'language')
      )
      return acc
    []
  )
  return profileJSON

My colleague said that I overuse underscore. Is he right? Is it a good piece of code?


texts: Translating array pointer access from C++ to Delphi

texts:
I'd like to know if I translated a piece of code correctly from C++ to Delphi. It looks like it is working, but I have a feeling that I'm reading and writing into memory that I'm not supposed to using Delphi.

Given C++ code:

struct tile_map
{
    int32 CountX;
    int32 CountY;

    uint32 *Tiles;
};

inline uint32
GetTileValueUnchecked(tile_map *TileMap, int32 TileX, int32 TileY)
{
    uint32 TileMapValue = TileMap->Tiles[TileY*TileMap->CountX + TileX];
    return(TileMapValue);
}

uint32 Tiles00[9][17] =
    {
        {1, 1, 1, 1,  1, 1, 1, 1,  0, 1, 1, 1,  1, 1, 1, 1, 1},
        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},
        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},
        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},
        {0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},
        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},
        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},
        {1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1},
        {1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1, 1},
    };
// More tile map declarations ...
// uint32 Tiles01[9][17] = ...
// uint32 Tiles10[9][17] = ...
// uint32 Tiles11[9][17] = ...

    tile_map TileMaps[2][2];
    TileMaps[0][0].CountX = 17;
    TileMaps[0][0].CountY = 9;
    TileMaps[0][0].Tiles = (uint32 *)Tiles00;

    TileMaps[0][1] = TileMaps[0][0];
    TileMaps[0][1].Tiles = (uint32 *)Tiles01;

    TileMaps[1][0] = TileMaps[0][0];
    TileMaps[1][0].Tiles = (uint32 *)Tiles10;

    TileMaps[1][1] = TileMaps[0][0];
    TileMaps[1][1].Tiles = (uint32 *)Tiles11;

// Usage
    int32 PlayerTileX = 2;
    int32 PlayerTileY = 2;
    uint32 TileMapValue = GetTileValueUnchecked(&TileMap[1][1], PlayerTileX, PlayerTileY);

Delphi translation:

program Project1;

{$APPTYPE CONSOLE}

type
    Puint32 = ^uint32;

    tile_map = record
        CountX : int32;
        CountY : int32;

        Tiles : Puint32;
    end;
    Ptile_map = ^tile_map;

{$POINTERMATH ON}
function GetTileValueUnchecked(TileMap : Ptile_map; TileX, TileY : int32) : uint32; inline;
begin
    result := TileMap^.Tiles[TileY * TileMap^.CountX + TileX];
end;

const //in the future these will be read from file, so const for now
    Tiles00:  array [0..8, 0..16] of uint32 =
    (
        (1, 1, 1, 1,  1, 1, 1, 1,  0, 1, 1, 1,  1, 1, 1, 1, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1, 1)
    );
    // More tile map declarations ...
    //Tiles01:  array [0..8, 0..16] of uint32 = ...
    //Tiles10:  array [0..8, 0..16] of uint32 = ...
    //Tiles11:  array [0..8, 0..16] of uint32 = ...
var
    TileMaps : array [0..1, 0..1] of  tile_map;
    PlayerTileX, PlayerTileY : int32;
    TileMapValue : uint32;
begin

    TileMaps[0][0].CountX := 17;
    TileMaps[0][0].CountY := 9;
    TileMaps[0][0].Tiles := Addr(Tiles00);

    TileMaps[0][1] := TileMaps[0][0];
    TileMaps[0][1].Tiles := Addr(Tiles01);

    TileMaps[1][0] := TileMaps[0][0];
    TileMaps[1][0].Tiles := Addr(Tiles10);

    TileMaps[1][1] := TileMaps[0][0];
    TileMaps[1][1].Tiles := Addr(Tiles11);

    // Usage
    PlayerTileX := 2;
    PlayerTileY := 2;
    TileMapValue = GetTileValueUnchecked(@TileMaps[1][1], PlayerTileX, PlayerTileY);
end.


texts:
Presenting you an implementation of the "shear and transpose" method of rotating a bitmap image. It works.. but it works slow, which is fully understandable. It is understandable due to the evident lack of optimization. Notwithstanding it doesn't interact with the VGA or any library for that matter.

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

/* bmp offsets */
#define OFFSET_OF_ID        (0x0)
#define OFFSET_OF_SIZE      (0x2)
#define OFFSET_OF_PIXELS    (0xA)
#define OFFSET_OF_NDIB      (0xE)
#define OFFSET_OF_WIDTH     (0x12)
#define OFFSET_OF_HEIGHT    (0x16)
#define OFFSET_OF_BPP       (0x1C)
#define OFFSET_OF_NRAW      (0x22)

/* bmp is especially dedicated for windows. defining windows-specific types: */
typedef unsigned char byte, *buffer;
typedef unsigned short word;
typedef unsigned long dword;
typedef unsigned long long ddword;
typedef unsigned char pixel[3];

/* bitmapS[nBitmap][offset] */
buffer *bitmapS;

/* Helper function */
ddword bmp_find_xy (dword width, dword xp, dword yp);

buffer
bmp_rotate
(dword nBitmap, float angle)
{
    const dword src_width  = *( (dword*)&bitmapS[nBitmap][OFFSET_OF_WIDTH]);
    const dword src_height = *( (dword*)&bitmapS[nBitmap][OFFSET_OF_HEIGHT]);
    const dword src_nraw   = *( (dword*)&bitmapS[nBitmap][OFFSET_OF_NRAW]);
    const dword src_pixels = *( (dword*)&bitmapS[nBitmap][OFFSET_OF_PIXELS]);

    buffer dest = malloc( src_pixels + src_nraw );

    float midX, midY;
    float deltaX, deltaY;
    dword rotX, rotY;
    dword i, j;

    midX = src_width / 2.0f;
    midY = src_height / 2.0f;

    memcpy(dest, bitmapS[nBitmap], src_pixels);

    for(i = 0; i < src_width; i++)
    for(j = 0; j < src_height; j++)
    {
        deltaX = i - midX;
        deltaY = j - midY;

        rotX = (dword)(midX + deltaX * sin(angle) + deltaY * cos(angle));
        rotY = (dword)(midY + deltaX * cos(angle) - deltaY * sin(angle));

        if(rotX >= 0 && rotX < src_width && rotY >= 0 && rotY < src_height)
        {
            ddword dest_offset = bmp_find_xy(src_width, i, j);
            ddword src_offset = bmp_find_xy(src_width, rotX, rotY);

            deltaX = i + midX;
            deltaY = j + midY;

            memcpy(&dest[dest_offset], &bitmapS[nBitmap][src_offset], sizeof(pixel);
        }
    }

    return dest;
}

/* Definition of helper function */
ddword
bmp_find_xy
(dword width, dword xp, dword yp)
{
    dword w = width;
    const dword channels = sizeof(pixel);
    const dword bpp = 8;
    const dword single = (channels * bpp) / 7;
    const dword offset = sizeof(BMP) + sizeof(DIB);
    dword rowsize = w * single;

    dword pixAddress;

    if (rowsize % 4 != 0) rowsize += 4 - (rowsize % 4);
    pixAddress = offset + yp * rowsize + xp * single;

    return pixAddress;
}


texts: Chaining HTTP requests becoming unreadable

texts:
I'm dealing with some very frustrating API's that requires a bit of filtering/processing data in order to get the results I need.

I need to make 2 API calls, one of which returns a list of asset ID's, the second of which populates that list with metadata. I've managed to successfully chain the requests and return the desired response, although I am

not certain if this is the correct way to do it, along with appropriate error handling
I can imagine it would be quite hard to understand what's going on from an outside perspective

How could I refactor/improve the following?

angular.module('api', [])

.service('api', ['$http', '$q', 'recommendationsService', 'alertsService', function($http, $q, recommendationsService, alertsService){

var service = {};

service.getRecommendations = function(configKey, assetId){

    //reset recommendations and q
    recommendationsService.setRecommendations(null);
    var abort = $q.defer();

    alertsService.setAlert("Fetching Recommendations...");
    var startTimer = new Date();

    return $http.get("/movies/" + configKey + "/" + assetId, { timeout: 10000 || abort })
    .then(function(movieRecs){
        var recommendationsServiceTime = (new Date() - startTimer)/1000;

        //if there's an error, abort
        if(movieRecs.data.errorMessage !== null){
                abort.resolve();
                return false;
        }

        var movieRecommendations = movieRecs.data.recommendation;

        var assetString = "";

        //item ID's are returned as asset:12345678; need to substr and append to assetString
        //for next query
        for(var i = 0; i < movieRecommendations.length; i++){
            var itemId = movieRecommendations[i].itemId;
            movieRecommendations[i].assetId = itemId.substr(itemId.length-8, itemId.length);
            assetString += movieRecommendations[i].assetId + ",";
        }

        //fetch metadata for given ID's
        alertsService.setAlert("Fetching Metadata...");
        startTimer = new Date();
        return $http.get("/id/" + assetString, { timeout: 10000 || abort })
        .then(function(contentMetadata) {
            var contentServiceTime = (new Date() - startTimer)/1000;

            for(var i = 0; i < movieRecommendations.length; i++){

                //if no metadata is found, remove asset from results
                if(!contentMetadata.data[movieRecommendations[i].assetId]){
                    movieRecommendations.splice(i,1);
                    continue;
                }

                movieRecommendations[i].meta = contentMetadata.data[movieRecommendations[i].assetId];

                //if no image exists, replace with a placeholder URL
                if(movieRecommendations[i].meta.imageUrl.length === 0){
                    movieRecommendations[i].meta.imageUrl = "/images/placeholder.png";
                }

            }

            alertsService.setAlert("Movie API: " + recommendationsServiceTime + "s ; Content API: " + contentServiceTime + "s");
            recommendationsService.setRecommendations(movieRecommendations);

        });

    })
    .catch(function(error) {
        //request error handling
        var errorMessage = (error.data) ? error.data.message : error.statusText;
        alertsService.setAlert(errorMessage);

    });

}

    return service;

}]);


texts:
This is the following Python code that I have coded for an algorithmic problem online.  For each line of input, the goal is to find the greatest number of repeating blocks into which the string can be split.  For example, if the input is abcabcabcabc, then the output should be 4, because the string is equal to 4 repetitions of abc.

The online compiler says "Time Limit Exceeded". Where in the following code can I optimize to make it much more efficient in terms of time?

inputString = raw_input()
while (inputString !='*'):
   scanned_string = ""
   matched_characters = ""
   frequency = 0
   if (len(inputString) == 1):
     print frequency
   for current_symbol in inputString:
     if not scanned_string:
        scanned_string = scanned_string + current_symbol
     if scanned_string:
        matched_characters = matched_characters + current_symbol
        if (scanned_string.startswith(matched_characters)):
            if (len(scanned_string) == len(matched_characters)):
                frequency = frequency + 1
                matched_characters = ""
        else:
            scanned_string = scanned_string+matched_characters
            matched_characters = ""
            frequency = 1
   print frequency
   inputString = raw_input()


texts:
Is this code an adequate implementation of the producer/consumer pattern?

In computer science, the producer/consumer pattern is a classic example of multithreaded synchronisation. The problem describes some threads called consumers and some threads called producers sharing a common fixed-size queue.

In the above code, the queue is called _myQueue and it's size is 1000.

Each producer job is to generate some item, put it in the queue by calling AddItem(), and start again.
The consumers job is to remove items from the queue by calling RemoveItem()

The problem is to make sure no producer tries to add items to the queue when it's full (i.e. containing 1000 items) and no consumer tries to remove items from the queue when it's empty.

Also, we'd like to avoid situation where consumers or producers end up waiting for no reason (deadlocks).

private int _count = 1000;
private Queue<string> _myQueue = new Queue<string>();
private static object _door = new object();

public void AddItem(string someItem)
{
    lock (_door)
    {
        while (_myQueue.Count == _count)
        {
            Monitor.Wait(_door);
        }

        _myQueue.Enqueue(someItem);
        Monitor.Pulse(_door);
    }
}

public string RemoveItem()
{
    string item = null;
    lock (_door)
    {
        while (_myQueue.Count == 0)
        {
            Monitor.Wait(_door);
        }

        item = _myQueue.Dequeue();
        Monitor.Pulse(_door);
     }

    return item;
}


texts: Method to return a collection of objects, filtered by a string

texts:
I have a Vehicle object which has a few properties such as Make, Model, Price, etc.

I also have a VehicleCollection object which derives from List<Vehicle which has a few custom methods, one of which is the following...

class VehicleCollection : List<Vehicle>
{
    public VehicleCollection GetVehicles(string _searchTerm = "")
    {
        // return the entire collection if no search term is provided
        if (_searchTerm.Length == 0)
            return this;

        var matchingVehicles = new VehicleCollection();
        foreach(var vehicle in this) // loop through all vehicles
        {
            PropertyInfo[] propInfos = vehicle.GetType().GetProperties(); // all properties of the current vehicle
            for (int i = 0; i < propInfos.Length; i++)
            {
                var propVal = propInfos[i].GetValue(vehicle); // the value of the current property of the current vehicle

                // check aganst value of a strings or the values within a string array
                // ignores case
                if (propVal is string propertyValueStr && propertyValueStr.IndexOf(_searchTerm, StringComparison.CurrentCultureIgnoreCase) >= 0
                    || propVal is string[] propValueArr && propValueArr.Any(x => x.IndexOf(_searchTerm, StringComparison.CurrentCultureIgnoreCase) >= 0))
                {
                    matchingVehicles.Add(vehicle);
                }
            }
        }

        return matchingVehicles;
    }
}

This returns a collection of vehicles, of which each vehicle must have a property whose value contains the supplied _searchTerm parameter.

Is this the best way to do this? Can this be achieved using LINQ at all? Can this be done without reflection?

Edit:
At the request of a comment, here is the Vehicle Class, with a few unnecessary methods omitted.

public class Vehicle
{
    public string ID { get; private set; }
    public string Make { get; private set; }
    public string Model { get; private set; }
    internal decimal Value { get; private set; }
    public string Price { get { return string.Format("{0:C}", Value); } }
    public VehicleColourEnum Colour { get; private set; }
    internal StatusEnum Status { get; private set; }
    public string State
    {
        get
        {
            switch (Status)
            {
                case StatusEnum.ComingSoon:
                    return "Coming Soon";
                case StatusEnum.HasDeposit:
                    return "Has Deposit";
                case StatusEnum.InStock:
                    return "In Stock";
                case StatusEnum.Sold:
                    return "Sold";
                case StatusEnum.Unknown:
                default:
                    return "Unknown";
            }
        }
    }

    public Vehicle(string _make, string _model, decimal _value, VehicleColourEnum _colour = VehicleColourEnum.None, StatusEnum _status = StatusEnum.Unknown)
    {
        Make = _make;
        Model = _model;
        Value = _value;
        Colour = _colour;
        Status = _status;
        ID = Guid.NewGuid().ToString("N");
    }
}


texts: Thoughts on organizing code for multiple mysql queries in php scripts

texts:
I have a web application where I connect with a MySQL database using PDO and in some scripts there are a lot of queries one after the other which don't necessarily concern the same tables. i.e I will execute a SELECT statement in one, and then depending on some values I will UPDATE another and finally go and DELETE from another one.

The thing is I only recently learned PHP and MySQL and because I wasn't sure and wanted to be careful and to find easily any problems (and a little because I am a little ocd and anal about silly things like uniformity and coding style) in every query I used the following format

try {
    $statement = "
        UPDATE/SELECT   ...
        FROM/SET    ...
        WHERE   ...";
    $query = $dbcnx->prepare($statement);
    $flag = $query->execute();
}
catch (PDOException $e) {
    $errorMsg = "...";
    error_log($errorMsg,3,'../../xxx.log');
    $response = ...;
    $dbcnx->null;
    return $response;
}
$result = $query->fetch/fetchAll/fetcColumn...

so I could find where any problem would occur (try/catch) and to be safe against injections and invalid characters (prepare) (I had some personal checks but I am pretty sure that a function specifically made for would be better).

When I had one or two queries it was fine but after the code grew it became a little too much code for little action/substance (like 16 lines for one query...)

So I would like some advise.
How do I make my code more manageable?
Is there some fundamental error in my logic on structure (the way I wrote it)?
Is there some rule for using try/catch? Is it more for developing and debugging and afterwards you can remove some blocks of it?
Is prepare enough for rudimentary security on queries?

I was thinking of making a function of just this block of code and calling it with the statement as a parameter. So I would just 'type' the query in the main body and then call the function where it would be prepared, executed and then return the result. Of course then I would always use fetchAll and would return an associative array but I think as long the datasets are small the memory usage would be fine (in any case in nowadays systems it should take A LOT to notice a difference, I think)...

EDIT: I was told about abstraction layer, which I admit I am a little fuzzy about. Basically it is a class which is instantiated every time the script/function runs and wrap the functions used repeatedly (along with the checking I do) inside it?


texts: Better approach on handling unexpected string upon converting it to the enum value

texts:
I have Grade enum and there is a static method to convert a string value to the particular enum value.

public enum Grade {
    None("N"),
    NotAccepted("-"),
    Accepted("+"),
    Uncertain("?");

    private final String gradeSymbol;

    Grade(String gradeSymbol) {
        this.gradeSymbol = gradeSymbol;
    }

    public String getGradeSymbol() {
        return gradeSymbol;
    }

    public static Grade fromGradeSymbol(final String gradeSymbol) {
        switch (gradeSymbol) {
            case "N":
                return None;

            case "-":
                return NotAccepted;

            case "+":
                return Accepted;

            case "?":
                return Uncertain;

            default:
                throw new IllegalArgumentException("Unexpected grade symbol: " + gradeSymbol);
        }
    }

    @Override
    public String toString() {
        return this.gradeSymbol;
    }
}

My question is, what is better way to handle unexpected grade symbol in the static fromGradeSymbol() method.

Another option I consider is the approach using Optional and returning Optional.empty() instead of throwing IllegalArgumentException.

Like this:

public static Optional<Grade> fromGradeSymbol(final String gradeSymbol) {
    switch (gradeSymbol) {
        case "N":
            return Optional.of(None);

        case "-":
            return Optional.of(NotAccepted);

        case "+":
            return Optional.of(Accepted);

        case "?":
            return Optional.of(Uncertain);

        default:
            return Optional.empty();
    }
}

My thoughts:

Throwing exception looks more logical, because it is being thrown in not expected case, when wrong value has been passed. But throwing exception makes it necessary to catch this exception anywhere where I convert string to the enum.

Use of Optional does not involve exceptions and makes cleaner code, without try-catch construct. But it somehow hides the unexpected input.

Sure, I can assume that every time when Optional does not contain a value we have an unexpected input. But it feels like code smell.

What do you think?


texts: Rotate an image (2D array) by 90 degrees recursively with low memory usage

texts:
I'm looking for comments on coding style, passing arguments, ...etc.

#include <iostream>

using namespace std;

void printImage(int** img, int N){

    //check if image pointer is NULL
    if(img == NULL){
        return;
    }

    //check if any of the columns of the image are null (since its essentially an array of pointers)
    for(int i=0; i<N ; i++){
        if(img[i] == NULL){
            return;
        }
    }

    for(int i=0; i<N ; i++){
        for(int j=0; j<N ; j++){
            cout<<img[i][j]<<",";
        }
        cout<<endl;
    }
}

// ROTATE IMAGE BY 90 DEGREES RECURSIVELY
void do_rotateImageInplace(int** img, int N, int row, int col){

    //base condition --> return: do this by check if we need to go deeper into the "peels of the onion :)"
    if(row > N-row-1 || col < 0 || N==1)
    {
        return;
    }

    // Tmp usage --> to store row or column being rotated
    int* tmp = new int[N-row];

    //backup row
    for(int i=row; i<N-row ; i++){
        tmp[i]=img[i][col];
    }

    //copy row into col
    for(int i=N-row-1; i>=row ; i--){
        img[i][col] = img[row][i];
    }

    //swap tmp with end row
    for(int i=N-row-1 ; i>=row ; i-- ){
        int tmpVal = img[col][i];
        img[col][i] = tmp[N-i-1];
        tmp[N-i-1] = tmpVal;
    }

    // Swap end row into first col
    for(int i=N-(row)-2 ; i>=row ; i--){
        int tmpVal = img[i][row];
        img[i][row] = tmp[N-i-1];
        tmp[N-i-1]=tmpVal;
    }

    // Swap first column backup into first row
    for(int i=row+1; i<N-(row)-1 ; i++){
        img[row][i] = tmp[i];
    }

    delete[] tmp;

    do_rotateImageInplace(img, N, row+1, col-1);
}

void rotateImageInplace(int** img, int N){

    // Check if image pointer is NULL
    if(img == NULL){
        return;
    }

    // Check if any of the columns of the image are null (since its essentially an array of pointers)
    for(int i=0; i<N ; i++){
        if(img[i] == NULL){
            return;
        }
    }

    // If image is less than 2 in size
    if(N<2){
        return;
    }

    do_rotateImageInplace(img, N, 0, N-1);
}

int main(){

    //TEST CASES:
    int N = 5;
    int** img = new int*[N];
    int val = 0;
    for(int i=0; i<N ; i++){
        img[i] = new int[N] {val++,val++,val++,val++,val++};
    }

    cout<<"******* original image ******"<<endl;
    printImage(img, N);

    rotateImageInplace(img, N);

    cout<<"******* rotated image ******"<<endl;
    printImage(img, N);

    for(int i=0; i<N ; i++){
        delete img[i];
    }
    delete[] img;

}