texts:
I've written a rudimentary parser for INI files:

{-# LANGUAGE OverloadedStrings   #-}

import qualified Data.Map           as M
import           Data.Maybe         (fromMaybe)
import qualified Data.Text          as T

type Ini = M.Map T.Text Section

data Section =
  Section
    { name       :: T.Text
    , properties :: M.Map T.Text T.Text
    }
  deriving (Show)

main :: IO ()
main = parseIni iniFilePath >>= \ini -> putStrLn $ "Parsed INI: " ++ show ini
  where
    iniFilePath = "/home/me/test.ini"

parseIni :: FilePath -> IO Ini
parseIni iniFilePath = parseToIni . T.pack <$> readFile iniFilePath

parseToIni :: T.Text -> Ini
parseToIni stringToParse =
  -- We return the parsed Ini, not the helper values
  firstOfTriple $
  foldr
    (\line (ini, currentSectionMaybe, lineIndex) ->
        -- We're at a new section start or the end of the file → add the previous section
        -- to the parsed Ini value and create a new section
      if isSectionHeader line || lineIndex >= length lines - 1
        then let updatedIni = addSection ini currentSectionMaybe
              in (updatedIni, Just $ Section (getSectionName line) M.empty, 1 + lineIndex)
        else (ini, updateSection currentSectionMaybe line, 1 + lineIndex))
    (M.empty, Nothing, 0) $
  -- Since foldr is right associative we would process the lines starting with the last one, that's
  -- why we reverse the list of lines
  reverse lines
  where
    lines :: [T.Text]
    lines = T.splitOn "\n" stringToParse

firstOfTriple :: (a, b, c) -> a
firstOfTriple (x, _, _) = x

parseProperty :: T.Text -> Maybe (T.Text, T.Text)
parseProperty line =
  case T.splitOn "=" line of
    [name, value] -> Just (T.strip name, T.strip value)
    _             -> Nothing

updateSection :: Maybe Section -> T.Text -> Maybe Section
updateSection sectionMaybe line = fmap updateSection' sectionMaybe
  where
    updateSection' :: Section -> Section
    updateSection' section =
      -- Add the property to the section if the property can be parsed.
      -- Otherwise, leave the section as it were
      maybe
        section
        (\(propName, value) -> Section (name section) (M.insert propName value (properties section)))
        (parseProperty line)

getSectionName :: T.Text -> T.Text
getSectionName line = fromMaybe line headerWithoutBracketsMaybe
  where
    headerWithoutBracketsMaybe = T.stripPrefix "[" line >>= T.stripSuffix "]"

isSectionHeader :: T.Text -> Bool
isSectionHeader line = T.isPrefixOf "[" strippedLine && T.isSuffixOf "]" strippedLine
  where
    strippedLine = T.strip line

addSection :: Ini -> Maybe Section -> Ini
addSection ini sectionMaybe = maybe ini (\section -> M.insert (name section) section ini) sectionMaybe

I'd love to get feedback on how to simplify the code and/or make it more readable.

Things I'm aware of and ok with at the moment:

The parser doesn't support comments
addSection could be eta-reduced
I don't use a parsing library like Parsec
I don't use lenses


texts:
Here is my code to retrieve a class from a different solution (both solutions are in the same folder) using an XML file:

var xml = XElement.Load("settings.xml");
var query = xml.Elements();
     foreach (var XMLProtocol in query)
     {
         string NameSpace = XMLProtocol.Element("NameSpace").Value;
         string ClassName = XMLProtocol.Element("ClassName").Value;
         string FrequencyType = XMLProtocol.Element("FrequencyType").Value;
         string FrequencyValue = XMLProtocol.Element("FrequencyValue").Value;
         string path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
         System.Reflection.Assembly assembly = Assembly.LoadFrom(path + "../../" + NameSpace + "\\bin\\Debug\\" + NameSpace + ".dll");
         System.Type type = assembly.GetType(NameSpace + '.' + ClassName);
         Protocol protocol = new Protocol((IProtocol)Activator.CreateInstance(type), Convert.ToInt64(int.Parse(FrequencyValue) * GetFrequencyTypeMultiplier(FrequencyType)));
         this.Add(protocol);
     }
Execute();

This is the XML:

<Protocols>
  <Protocol>
    <NameSpace>ClassTest</NameSpace>
    <ClassName>Class1</ClassName>
    <FrequencyType>Minute</FrequencyType>
    <FrequencyValue>20</FrequencyValue>
  </Protocol>
</Protocols>

Is there a way to retrieve the assembly without having to "hardcode" the path to the DLL? What is the best practice for that scenario?


texts:
I'm writing a utility method which pipes given ResponseSpec's body and gives to the caller a change to read it.

static <R> Mono<R> pipeBodyAndApply(
        final WebClient.ResponseSpec spec,
        final ExecutorService executor,
        final Function<? super ReadableByteChannel, ? extends R> function) {
    return using(
            Pipe::open,
            p -> {
                final Future<Disposable> future = executor.submit(
                        () -> write(spec.bodyToFlux(DataBuffer.class), p.sink())
                                .log()
                                .doFinally(s -> {
                                    try {
                                        p.sink().close();
                                        log.debug("p.sink closed");
                                    } catch (final IOException ioe) {
                                        throw new RuntimeException(ioe);
                                    }
                                })
                                .subscribe(DataBufferUtils.releaseConsumer())
                );
                return just(function.apply(p.source()))
                        .log()
                        .doFinally(s -> {
                            try {
                                final Disposable disposable = future.get();
                                assert disposable.isDisposed();
                            } catch (InterruptedException | ExecutionException e) {                                 e.printStackTrace();
                            }
                        });
            },
            p -> {
                try {
                    p.source().close();
                    log.debug("p.source closed");
                } catch (final IOException ioe) {
                    throw new RuntimeException(ioe);
                }
            }
    );
}

Now I'm wondering am I doing it right.

Is this method written right for the purpose?
Is there any mis-usages regarding Mono or Flux?


texts: Providing a consistent interface for inRange function over modded values

texts:
I want to write a function named inRange which will have below interface

inRange(long a, long b, boolean inclusiveStart, boolean inclusiveEnd)

This function calculates if this.value is in between a & b. However there are two important points to note:

Two boolean values (inclusiveStart & inclusiveEnd) specify if a (or b) should be included in the range.
All 3 values viz. a, b and this.value are modded values i.e they define a circular range.

I have tried writing this function but here is my concern,

How to provide a consistent interface so that client does not have to worry about circular range. Lets say, a == b then should the function consider complete range or should it just consider a single value for the range. Or when a = 0 & b = MOD - 1 then what should be the function behavior for different combinations of boolean values.

Below is my code:

private boolean inRangeBothInclusive(long start, long end) {
    if (start == end)
    return this.value == start;
    else if (start < end) {
    return start <= this.value &&
        this.value <= end;
    } else {
    return !(end <= this.value &&
         this.value <= start);
    }
}

public boolean inRange(long start, long end, boolean startInclusive,
               boolean endInclusive) {
    /* Ranges can have bigger start and smaller end value due to mod */

    if (!startInclusive) {
    start = (start + 1) % MOD;
    }
    if (!endInclusive) {
    end = (end - 1) % MOD;
    if (end < 0)
        end += MOD;
    }
    return inRangeBothInclusive(start, end);
}


texts: Exercism: determine if a word or phrase is an isogram

texts:
The task:

Determine if a word or phrase is an isogram.
An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.

Examples of isograms:

lumberjacks
background
downstream
six-year-old

The word isograms, however, is not an isogram, because the s repeats.
Even though I'm aware that questions about isograms have already been posted, in this variation of the problem spaces and hyphens are allowed to appear multiple times so that you can not use a solution such as len(string) == len(set(string))
What bothers me about my solution is hardcoding bounds of ascii character ranges and using collections library for such a small problem. I'm wondering if there is a better way to do it.
Here is my code:
from collections import Counter

ASCII_LOWER_BOUND = 97
ASCII_UPPER_BOUND = 123

def is_isogram(string):
    char_counts = Counter(string.lower())
    return all(
        char_counts[char] == 1
        for char in char_counts
        if ord(char) in range(ASCII_LOWER_BOUND, ASCII_UPPER_BOUND + 1)
        )

And a test suite provided by exercism:
import unittest

from isogram import is_isogram

# Tests adapted from `problem-specifications//canonical-data.json` @ v1.7.0

class IsogramTest(unittest.TestCase):
    def test_empty_string(self):
        self.assertIs(is_isogram(""), True)

    def test_isogram_with_only_lower_case_characters(self):
        self.assertIs(is_isogram("isogram"), True)

    def test_word_with_one_duplicated_character(self):
        self.assertIs(is_isogram("eleven"), False)

    def test_word_with_one_duplicated_character_from_the_end_of_the_alphabet(self):
        self.assertIs(is_isogram("zzyzx"), False)

    def test_longest_reported_english_isogram(self):
        self.assertIs(is_isogram("subdermatoglyphic"), True)

    def test_word_with_duplicated_character_in_mixed_case(self):
        self.assertIs(is_isogram("Alphabet"), False)

    def test_word_with_duplicated_character_in_mixed_case_lowercase_first(self):
        self.assertIs(is_isogram("alphAbet"), False)

    def test_hypothetical_isogrammic_word_with_hyphen(self):
        self.assertIs(is_isogram("thumbscrew-japingly"), True)

    def test_hypothetical_word_with_duplicated_character_following_hyphen(self):
        self.assertIs(is_isogram("thumbscrew-jappingly"), False)

    def test_isogram_with_duplicated_hyphen(self):
        self.assertIs(is_isogram("six-year-old"), True)

    def test_made_up_name_that_is_an_isogram(self):
        self.assertIs(is_isogram("Emily Jung Schwartzkopf"), True)

    def test_duplicated_character_in_the_middle(self):
        self.assertIs(is_isogram("accentor"), False)

    def test_same_first_and_last_characters(self):
        self.assertIs(is_isogram("angola"), False)

if __name__ == "__main__":
    unittest.main()
```


texts:
I am a Python beginner learning Python 3. I have written two small functions that parse the lsblk output and return Linux physical and logical disks. Here is the first function:

from subprocess import run, PIPE

def physical_drives():
    """
    Gets all physical drive names.

    Gets all physical drive names on a Linux system,
    parsing the lsblk utility output.

    Parameters
    ----------

    Returns
    -------
    list
        A list of strings representing drive names.

    """

    command = ['lsblk -d -o name -n']
    output = run(command, shell=True, stdout=PIPE)

    output_string = output.stdout.decode('utf-8')
    output_string = output_string.strip()

    results = output_string.split('\n')
    return results

def main():
    print(physical_drives())

if __name__ == '__main__':
    main()

The second function:

from subprocess import run, PIPE

def partitions(disk):
    """
    Gets all partitions for a given physical disk.

    Gets all partitions present on a physical disk
    on a Linux system.
    The function parses the lsblk utility output.

    Parameters
    ----------
    disk : string
        A string containing a disk name such as 'sda'

    Returns
    -------
    list
        A list of strings representing partitions.

    """

    command = ['lsblk -o name -n -s -l']
    output = run(command, shell=True, stdout=PIPE)

    output_string = output.stdout.decode('utf-8')
    output_string = output_string.strip()

    results = list()
    results.extend(output_string.split('\n'))
    results = [x for x in results if x != disk and disk in x]

    return results

def main():

    from disks import physical_drives

    for drive in physical_drives():

        print(drive)
        parts = partitions(drive)

        for partition in parts:
            print('\t' + partition)

if __name__ == '__main__':
    main()

The functions are in two different files in the same directory. I would appreciate a quick review on anything that is not idiomatic/pythonic code. I also have one specific question. I have coded the functions in Ninja-Ide with lint and PEP8 suggestions turned on. In both files the IDE suggests that my print() statements:

print('\t' + partition)
print(physical_drives())

should be written with doubled parentheses:

print(('\t' + partition))
print((physical_drives()))

For Python 3 support, I have checked the print() documentation, but have been unable to find a reference for including function calls and string concatenation in double parentheses when calling print().


texts: Display the last N lines of a text file with line numbers in reverse order

texts:
Do you think the way I'm doing it is fine? Is this the most typical way to do it? Share your thoughts please.

# Display the last three lines of a text file with line numbers in reverse order
# Can come quite in handy when reading log file entries
cat -n [FILE] | tac | head --lines=3

Test:

# Let's create a text file to test our command against
cat > test.txt

# Copy and paste these lines into the terminal window and press Ctrl+D to let
# the shell know that we're done entering our stuff
house
car
boy
cat
lake
sea
laptop
rain

# Run the command
cat -n test.txt | tac | head --lines=3

# Brief description:
# cat -n test.txt | - Pipe the output with line numbers to the tac command
# tac |             - Reverse the order and pipe along to the head command
# head --lines=3    - Display only the first three lines

# Output:
     8  rain
     7  laptop
     6  sea

# The number next to the first line in our output (8  rain) should be equal to
# the number of lines in the entire file. We can check that using the word count
# utility:
wc -l test.txt

# Output (It's 8 too. Looks like the test passes):
8 test.txt


texts: Further optimization of file transfer over FIFO on linux?

texts:
For learning purposes I'm writing a very simple mqueue based file transfer server. Below is a thread function that takes care of an incoming request:

static void * handle_client_request(const char *request_string) {
    char request_pathname[_part_delim_alloc_size],
         request_fifo_name[_part_delim_alloc_size];

    bool parse_ret = parse_mqueue_request_string(request_string, (char *[]) {request_pathname, request_fifo_name});
    if(!parse_ret) {
        fprintf(stderr, PROGNAME ": error parsing mqueue request string: %s\n", request_string);
        free(request_string);
        return NULL;
    }

    fprintf(stdout, PROGNAME ": received new request: (%s, %s) -- handling\n", request_pathname, request_fifo_name);

    // open requested file for reading
    int file_fd = open(request_pathname, O_RDONLY);
    if(file_fd == -1) {
        perror(PROGNAME ": error opening requsted file");
        free(request_string);
        return NULL;
    }

    // construct full FIFO path
    char full_fifo_path[strlen(FIFO_STORAGE_PATH) + strlen(request_fifo_name) + 1];
    strcpy(full_fifo_path, FIFO_STORAGE_PATH);
    strncat(full_fifo_path, request_fifo_name, 11);

    // open FIFO for writing only -- this may block until client also opens the FIFO
    int fifo_fd = open(full_fifo_path, O_WRONLY);
    if(fifo_fd == -1) {
        perror(PROGNAME ": failed opening FIFO for writing");
        close(file_fd);
        free(request_string);
        return NULL;
    }

    void *buf = malloc(DEFAULT_BUFSIZE); // 128 KiB, 2^17 bytes
    if(!buf) {
        perror(PROGNAME ": failed allocating buffer");
        close(file_fd);
        close(fifo_fd);
        free(request_string);
        return NULL;
    }

    size_t bread;
    while((bread = read(file_fd, buf, DEFAULT_BUFSIZE)) > 0) {
        // read call complete, "bread" bytes are now in "buf"
        ssize_t bwritten = write(fifo_fd, buf, bread);

        if(bwritten == -1) {
            // failed writing the batch of bytes received
            fprintf(stderr, PROGNAME ": failed writing to FIFO - request aborted (%s): %s\n", full_fifo_path, strerror(errno));
            free(buf);
            free(request_string);
            close(file_fd);
            close(fifo_fd);
            return NULL;
        }

        /* fprintf(stdout, PROGNAME ": read %lu bytes of data and wrote %ld bytes of data\n", bread, bwritten); */
    }

    fprintf(stdout, PROGNAME ": done processing request (%s, %s) last bread: %lu\n", request_pathname, request_fifo_name, bread);

    close(file_fd);
    close(fifo_fd);
    free(buf);

    return NULL;
}

Its purpose is to transfer a local file (that the client requests) over a FIFO that the client connects to.

The size of the buffer for read(2) and write(2) I've decided on is 128KiB. Increasing it doesn't seem to have an positive effect on performance.

I am wondering - are there any trivial (or not so trivial) optimizations I could apply to this function to gain an ever so slight increase in performance?


texts:
This Problem is from https://www.codechef.com/problems/PRINCESS .

The Problem in brief - i am given a string of length N. I have to check among all the the substrings that whether a substring exist or not which is palindrome and having length greater than 1. If such a substring exists then print YES else print NO.

Input
The first line contains a single integer T, the number of test cases. Each test case is described by a single line containing a string.

Constraints

1 ≤ T ≤ 10

1 ≤ N ≤ 100000

Subtasks

Subtask #1 (20 points), Time limit : 1 sec
1 ≤ T<=10, N<=1000

Subtask #2 (80 points), Time limit : 1 sec
1 ≤ T<=10, N<=100000

How Do I optimize the code? I am getting subtask #1 right , with this code.

int main()
{
    int T;
    string s,sub;
    int n,counter;
    int i,j,k;
    scanf("%d",&T);
    for(i=0;i<T;i++)
    {
        cin>>s;
        n = s.length();
        counter=0;

        for(j=0;j<n-1;j++)
        {
          if(counter==1)
                    break;
                for(k=2;k+j<=n;k++)
                {
                   sub=s.substr(j,k);
                    if( equal(sub.begin(), sub.begin() + sub.size()/2, sub.rbegin()) )
                    {
                        counter++;
                        break;
                    }
                }
        }
        if(counter==0)
                printf("NO\n");
        else
                 printf("YES\n");
    }
    return 0;
}


texts:
I need to shorten code, remove duplicate elements, and generally make a more valid code.

My code works, but I think it is 'hardcoded'. How would an experienced programmer reduce this code?

At the top of the code are variables
In the calculation center
And at the bottom of the event clicked on the mouse

 let logicSummFunc = () => {
        let
            up = $('.passengers__count_up'),
            dn = $('.passengers__count_down'),
            val = $('.passengers__count_val'),
            mainVal = $('.js__passengers'),

            summFunc = {
                0: 0,
                1: 0,
                2: 0,
                total: 0,

                _totalSumm: function(flag) {
                    this.total = this[0] + this[1] + this[2];
                    mainVal.val(this.total);
                },
                _plus: function(flag) {
                    this._numberPlus(flag);
                    val.eq(flag).val(this[flag]);
                },
                _minus: function(flag) {
                    this._numberMinus(flag);
                        val.eq(flag).val(this[flag]);
                },
                _numberPlus: function(flag) {
                    this[flag]++;
                    this._totalSumm();
                },
                _numberMinus: function(flag) {
                    this[flag]--;
                    this._totalSumm();
                }
            };

        // foo

        for (var i = 0; i < $('.passengers__line').length; i++) {
            $('.passengers__line')[i];
            foo(i, i);
        }

        function foo(eqNumb, n) {
            up.eq(eqNumb).on('click', function(e) {
                e.preventDefault();
                summFunc._plus(eqNumb, n);
            });

            dn.eq(eqNumb).on('click', function(e) {
                e.preventDefault();
                summFunc._minus(eqNumb, n);
            });
        }

    };
    logicSummFunc();
};


texts:
I tried to make a dynamic tree in python. It is simple and i have gotten it to work so far. I created a function in main that generates some example data for the tree and then the main goal was to create a member function that uses recursion to print all the data (display_data()). The only issue with this that i have is the recursion depth problem, as well as the speed. Essentially the recursion and loop pattern builds up quite a bit on the overall run time. Also note this is a side project, I need to understand dynamic trees for a tic-tac-toe AI I am attempting(failing) to write.

tree.py

class Tree():
    """Implement a dynamic tree

                   1
                 / | \
                /  |   \
              2    3     4
             / \       / | \
            5   6     7  8  9
           /  / | \
          10 11 12 13
    """

    def __init__(self):
        self.children = []
        self.data = []

    def create_children(self, amount):
        for i in range(amount):
            self.children.append(Tree())

    def create_data(self, data):
        for datum in data:
            self.data.append(datum)

    def display_data(self):
        print(self.data, end = ' ')
        for child in self.children:
            child.display_data()

main.py

from tree import Tree

def example_data(root):
    """
        ['Child', 1] ['nChild', 1] ['nChild', 2]
        ['Child', 2] ['nChild', 1] ['nChild', 2]
        ['Child', 3] ['nChild', 1] ['nChild', 2]

    """
    root.create_data(["Root"])
    root.create_children(3)

    counter = 1
    for child in root.children:
        child.create_data(["Child", counter])
        child.create_children(2)
        counter += 1

        ncounter = 1
        for nchild in child.children:
            nchild.create_data(["nChild", ncounter])
            ncounter += 1

    return root

if __name__ == "__main__":
    root = example_data(Tree())
    root.display_data()


texts: Object instantiation with multiple parameters

texts:
I'm trying to create a little block presenter for Laravel which displays blocks of content in certain positions. I have 2 classes, BlockFactory and Block. The BlockFactory contains all the blocks and creates them whereas the Block class is exactly just that: a simple block.

As can be seen in the code below, when I'm creating a new Block from within the BlockFactory, I have to pass all these parameters to the create method. Which then get passed onto the instantiation of the Block class and finally passed onto the constructor.

This seems very unwieldy to me. Any ideas for a smarter way of doing this?

Also: not sure if it's smart to create a new Block object inside create method. I was trying to think in terms of dependency injection but I couldn't figure it out.

// create and save new block
Block::create('name', 'content', 'position', 0, [])->add();

// BlockFactory, bound to the Block facade (bad naming i know)
class BlockFactory
{

    protected $blocks = [];
    protected $currentBlock;

    public function create($title, $content, $position, $order = 0, $parameters = [])
    {
        $this->currentBlock = new Block($title, $content, $position, $order, $parameters); // this part is bugging me somehow...
        return $this;
    }

    public function add()
    {
        $this->blocks[] = $this->currentBlock;
    }

    public function render()
    {
        return $this->blocks;
    }

}

// The actual block class
class Block
{

    protected $title;
    protected $content;
    protected $position;
    protected $order;
    protected $parameters;

    public function __construct($name, $content, $position, $order = 0, $parameters = [])
    {
        $this->title = $name;
        $this->content = $content;
        $this->position = $position;
        $this->order = $order;
        $this->parameters = $parameters;
    }
}


texts: Unit testing where you depend on implementation of another method

texts:
I am implementing a gap buffer and am trying to write a test for the insert method, the test currently looks something like this:

gapBuffer.insert('a')
assertEquals(gapBuffer.getText(), "a")
gapBuffer.insert('c')
assertEquals(gapBuffer.getText(), "ac")
gapBuffer.insert('d')
assertEquals(gapBuffer.getText(), "acd")
gapBuffer.moveCursorTo(1)
gapBuffer.insert('d')
assertEquals(gapBuffer.getText(), "abcd")

Now the problem is that this method is not just testing the insert method because it depends on the correctness of the getText() and moveCursorTo() methods

Note: the getText() and moveCursorTo() methods are not trivial but do have tests of their own


texts: Python - Making A Valid Date Checker - using Regular Expressions

texts:
Date Detection:
Write a regular expression that can detect dates in the DD/MM/YYYY format.
Assume that the days range from 01 to 31, the months range from 01
to 12, and the years range from 1000 to 2999. Note that if the day or month
is a single digit, it’ll have a leading zero.
Then store these strings into variables named month, day, and
year, and write additional code that can detect if it is a valid date.
April,
June, September, and November have 30 days, February has 28 days, and
the rest of the months have 31 days. February has 29 days in leap years.
Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, unless the year is also evenly divisible by 400. Note how this calculation makes it impossible to make a reasonably sized regular expression
that can detect a valid date.
import re
def check_date(day, month, year):
    # April, June, September, November = 30 days/ February = 28 days, unless leapyear so 29/ rest has 31 days
    month_dict = {4: 30, 6: 30, 9: 30, 11: 30, 2: 28}
    day_bound = month_dict.get(month, 31)

    # month is february
    if day_bound == 28:
        # checks if the year is a leap year
        if year % 4 == 0:
            if year % 100 == 0:
                if year % 400 == 0:
                    day_bound = 29
            else:
                day_bound = 29

    # if the day is in the range of possible days
    if day <= day_bound:
        return True
    return False

# DD/MM/YYYY
string = "31/02/2020"
date_regex = re.compile(r"([0-2]\d|3[01])/(0\d|1[0-2])/([12]\d{3})")
match = date_regex.search(string)
valid = False
if match:
    day = int(match.group(1))
    month = int(match.group(2))
    year = int(match.group(3))
    valid = check_date(day, month, year)

if valid:
    print(f'Day: {day}, Month: {month}, Year: {year}')
else:
    print('Invalid Date!')


texts: Extract code that makes class shared_ptr construct-able only

texts:
I've tried using CRTP, but the forces the class to befriend CRTP Base.

template <typename T>
class SharedConstructable
    : public std::enable_shared_from_this<T>
{
    typedef std::shared_ptr<T> ptr_type;

public:

    struct Ptr
        : ptr_type
    {
        template<typename... Args>
        Ptr(Args&&... args)
            : ptr_type(new T(args...))
        {
        }
    };
};

class SharedOnly
    : SharedConstructable<SharedOnly>
{
private:
    friend class SharedConstructable<SharedOnly>;
    SharedOnly(int) {}
}

Usage:

SharedOnly x(5); // Error Constructor is private
SharedOnly::Ptr(5); // Correct usage;

Is there a cleaner/better way of doing this (without the friendship)?


texts: Trie implementation for left to right wildcard search

texts:
I was working on a task to implement auto suggest from an array of couple of thousands of strings.

Of course, the first and the easiest implementable was to go through each element and do a[i].startWith(query). Technically the time complexity of this algorithm then would be \$O(n+(q*m))\$. Here, n equals the number of elements in the array, q equals the number of total matches and m equals the number of characters in the query (I am not sure how accurate I am here).

Regardless, I have created a following Trie which at every node keeps track of every child that has a word ending there.

For example, if the query is "can" then with only three traversal the tree will return cancel, cancer, can and cancellation because the node 'n' will have connections to all the sub trees that has a word ending!

I would really like to hear some comments on this.

package utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author Sapan
 */
public class Trie {

    private Map<Character, Trie> children;
    private String word = null;
    private Set<Trie> connections;
    static int count = 0;

    public Trie() {
        this.children = new HashMap<>();
        connections = new HashSet<>();
    }
    /*
     * Builds a Trie with given query
     */

    public void add(String word) {
        if (word == null || "".equals(word.trim())) {
            throw new IllegalArgumentException("Query can not be empty or null");
        }
        Trie t = this;
        for (Character c : word.toCharArray()) { //for every character in query do the following....
            //add character to the current instance and get the child instance right after adding the current char
            if (!t.children.containsKey(c)) {
                t.children.put(c, new Trie());
            }
            t = t.children.get(c);
        }
        t.word = word;
    }

    public Set search(String word) {
        count = 0;
        Trie current = this;
        Set<Trie> matches = new HashSet();
        for (Character c : word.toCharArray()) {
            ++count;
            current = current.children.get(c);
            if (current == null){
                return matches;
            }
        }
        //System.out.println(current);
        if (current == null) {
            return matches;
        }

        matches = current.connections;

        return matches;
    }
    public Set build() {
        //matches = new HashSet<>();
        ++count;
        for (Character c : this.children.keySet()) {
            this.connections.addAll(this.children.get(c).build());
        }
         if (this.word != null && this.word.length() > 0) {
             this.connections.add(this);
        }
         if (this.children.keySet().isEmpty()) {// we are at the leaf node
            this.connections.add(this);
        }
        return this.connections;
    }

    public static void main(String[] args) {
        Trie t = new Trie();
        t.add("can");
        t.add("kangaroo");
        t.add("roo");
        t.add("rash");
        t.add("ram");
        t.add("rat");
        t.add("kansas");
        t.add("banana");
        t.add("ban");
        t.add("cancel");
        t.add("cancer");
        t.add("add");
        t.add("addition");
        t.add("sub");
        t.add("subtraction");
        t.add("ape");
        t.add("apple");
       // t.build();
        t.build();
        System.out.println(t);
        System.out.println(t.count+"----");
        //System.out.println(t);
       // List<Trie> l = t.search("ap");

        //System.out.println(l);
       // for (char c = 'a'; c <= 'z'; c++) {
           Set<Trie> l = t.search("ca");
           System.out.println(t.count);
            System.out.println("words starting from ca ");
            for (Trie trie : l) {
                System.out.println(trie.word);
            }
    }
}


texts: Inserting a user sign-up record using mysqli

texts:
My Code:
Connectivity(php)

<?php

$conn=mysqli_connect("localhost","root","","webchat_data");
//if($conn)
//{
//  echo "hi";
//}
if(!$conn){
    die("CONNECTION FAILED" .mysqli_connect_error());
}

?>

Signup

<?php
include 'connectivity.php';
$uname=($_POST['uname']);
$email=($_POST['Email']);
$pass=($_POST['Password']);

$sql = "INSERT INTO `sign-up`(USERNAME,EMAIL_ID,PASSWORD) VALUES('$uname','$email','$pass')";
//$result=$conn->query($sql);
$result = mysqli_query($conn, $sql);
//$query=mysqli_query($conn,$sql);

header("Location:index.php");

?>

Someone told me that my query is good for a learner, but not for real world applications. Please make some recommendations to make this code more suitable for real world scenarios.


texts:
I have this rather ghastly if statement and I'm sure there is a way to condense it, but I don't really know how.  I was told a case statement would work but I've never used a case statement and I'm not sure.

public void add(int p, Course c)
{
    if (p == 1){
    if (course1.isFree() == true) {
        course1 = c;
        System.out.println("Course " + c + "added to period " + p +".\n");
    } else {
        System.out.println("Unable to add class to a nonfree period.");
    }
    } else if (p == 2){
        if (course2.isFree() == true) {
        course2 = c;
        System.out.println("Course " + c + "added to period " + p +".\n");
    } else {
        System.out.println("Unable to add class to a nonfree period.");
    }
    } else if (p == 3){
        if (course3.isFree() == true) {
        course3 = c;
        System.out.println("Course " + c + "added to period " + p +".\n");
    } else {
        System.out.println("Unable to add class to a nonfree period.");
    }
    } else if (p == 4){
        if (course4.isFree() == true) {
        course4 = c;
        System.out.println("Course " + c + "added to period " + p +".\n");
    } else {
        System.out.println("Unable to add class to a nonfree period.");
    }
    } else if (p == 5){
        if (course5.isFree() == true) {
        course5 = c;
        System.out.println("Course " + c + "added to period " + p +".\n");
    } else {
        System.out.println("Unable to add class to a nonfree period.");
    }
    } else if (p == 6){
        if (course6.isFree() == true) {
        course6 = c;
        System.out.println("Course " + c + "added to period " + p +".\n");
    } else {
        System.out.println("Unable to add class to a nonfree period.");
    }
    } else if (p == 7){
        if (course7.isFree() == true) {
        course7 = c;
        System.out.println("Course " + c + "added to period " + p +".\n");
    } else {
        System.out.println("Unable to add class to a nonfree period.");
    }
    } else if (p == 8){
        if (course8.isFree() == true) {
        course8 = c;
        System.out.println("Course " + c + "added to period " + p +".\n");
    } else {
        System.out.println("Unable to add class to a nonfree period.");
    }
    }

    totalcredits();
}


texts:
The chart data is stored in a nested dictionary struct @line_charts, and I need to convert the prices to target currency with the function exchange_datasets_currency. It should finally return the @chart in the end of method.

Is there any way to improve my pattern?

def sample_a
    @line_charts = [get_line_chart(@from, @to, "flight_date", "price", tixs)]
    exchange_datasets_currency(@line_charts.first[:datasets], @flights.first)
    @line_charts
end

def sample_b
    @line_chart = _build_line_chart(@from, @to, union_keys, datasets)
    exchange_datasets_currency(@line_chart[:datasets], @flight)
    @line_chart
end

  def exchange_datasets_currency(datasets, flight)
    datasets.each do |item|
      item[:data] = item[:data].collect do |price|
        if price.nil?
          nil
        else
          country = LocationUtils.instance.get_country(flight.from)
          from_currency = LocationUtils.instance.get_currency(country)
          Money.new(price,from_currency).exchange_to("TWD").cents
        end
      end
    end
  end


texts: C++ implementation of quicksort with iterators (unstable sorting)

texts:
Please review the following quicksort implementation.
qsort below is intentionally unstable, as partition reoders equal elements.

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

using namespace std;

// Ensures pivot is at position end.
template<typename Iter, typename T>
Iter part_pivot(Iter begin, Iter end, T pivot) {
  while (begin != end) {
    if (*begin < pivot)
      ++begin;
    else if (*--end < pivot)
      iter_swap(begin, end);
  }
  return begin;
}

template<typename Iter>
Iter part(Iter begin, Iter end) {
  typename iterator_traits<Iter>::value_type pivot = *begin;
  Iter mid = part_pivot(begin, end, pivot);
  // Ensure pivot is at position mid.
  iter_swap(--end, mid);
  return mid;
}

template<class Iter>
void quicksort(Iter begin, Iter end) {
  if (std::distance(begin, end) < 2)
    return;
  Iter mid = part(begin, end, *begin);
  quicksort(begin, mid);
  quicksort(++mid, end);
}

template<class T>
void quicksort(vector<T>& v) {
  quicksort(v.begin(), v.end());
}

template <class T>
void print(const vector<T>& v) {
  for (const T& t : v)
    cout << t << " ";
  cout << endl;
}

int main() {
  vector<int> v = {1,4,8,34,2,3,45,6,87,4,3};
  print(v);
  quicksort(v);
  print(v);
}


texts: Convert hex to base64 (Cryptopals challenge 1)

texts:
I've been spending some time learning Rust and I came across the Cryptopals Challenges.
This is my implementation of challenge 1

  Convert hex to base64 The string:

49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d

  Should produce:

SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t

  So go ahead and make that happen. You'll need to use this code for the
  rest of the exercises.

  Cryptopals Rule: Always operate on raw bytes, never on encoded strings. Only use hex and base64 for pretty-printing.

I did go ahead and pull in a crate for handling base64 encoding. It didn't seem important to implement that myself.

mod basics {
    extern crate base64;
    use self::base64::encode;

    pub fn hex_to_base64(hex: &str) -> String {
        encode(&hex_to_bytes(hex))
    }

    pub fn hex_to_bytes(hex: &str) -> Vec<u8> {
        hex.chars()
            .collect::<Vec<_>>() //convert to slice-able
            .chunks(2)           //each char is one nibble
            .map(|byte| byte.iter().collect::<String>())
            .map(|byte| u8::from_str_radix(&byte[..], 16).unwrap())
            .collect()
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn can_convert_hex_to_base64() {
            let hex_as_string =
                "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
            let base64_as_string =
                "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";

            assert_eq!(hex_to_base64(hex_as_string), base64_as_string);
        }

        #[test]
        fn ff_byte_hex_string_to_byte_vector() {
            let hex = "FF";
            assert_eq!(vec![0xFF], hex_to_bytes(hex));
        }

        #[test]
        fn single_byte_hex_string_to_byte_vector() {
            let hex = "2A";
            assert_eq!(vec![0x2A], hex_to_bytes(hex));
        }

        #[test]
        fn multibyte_hex_string_to_byte_vector() {
            let hex = "2ABE";
            assert_eq!(vec![0x2A, 0xBE], hex_to_bytes(hex));
        }
    }
}


texts:
Type Driven Development with Idris demonstrates how Idris can be used to build a Finite State Machine for a vending machine.

Please critique my implementation. I'm new to dependent types, so I'm not sure if dependent types would enhance this implementation. In other words, if path-dependent types would significantly improve this FSM, then I'm not sure how.

module VendingMachine

-- Pounds is a form of currency/money
Pounds : Type
Pounds = Nat

-- the Machine dispenses/vends chocolate candy bars
Choc : Type
Choc = Nat

data Machine = Mach Pounds Choc

fill : Machine -> Nat -> Machine
fill (Mach ps bars) ns = Mach ps (bars + ns)

init : Machine
init = Mach 0 0

insertCoin : Machine -> Machine
insertCoin (Mach ps bars) = (Mach (ps + 1) bars)

vend : Machine -> Machine
vend (Mach Z bars)          = Mach Z bars
vend (Mach (S ps) (S bars)) = Mach ps bars

getChange : Machine -> Machine
getChange (Mach Z bars) = Mach Z bars
getChange (Mach n bars) = Mach 0 bars


texts:
I applied a class to  in order to display the arrow. In that class, I am using the background image, size and position to display the arrow. Is this the right way to do it?

.b-dropDownSelector__selectArrow {
      background-image: url('/images/glyph-wedge-down.svg');
      background-size: rem(16px) rem(9px);
      background-repeat: no-repeat;
      background-position-x: calc(100% - 16px);
      background-position-y: center;
    }


texts: Construct an 2D array of contiguous elements comparing master and incident arrays

texts:
Requirement:

Based on mainArray which contains the master list of items, and compArray which has items of interest; construct a 2 dimensional third array that contains the array of contiguous elements.

The purpose of this requirement is for plotting poly-line on map wherever an incident occurred in contiguous manner, plotted using the finalArray of locations.

Example:

const mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const compArray = [1, 2, 3, 6, 7, 11, 12, 13, 15];

// produces finalArray
[[ 1, 2, 3 ],[ 6, 7 ],[ 11, 12, 13 ],[ 15 ]]

My current solution:

console.clear();

const mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const compArray = [1, 2, 3, 6, 7, 11, 12, 13, 15];
let compArrayIndex = 0;
let finalArray = [];
let currentArray = null;

for (let i = 0; i < mainArray.length; i++) {
  const e = mainArray[i];

  if (e === compArray[compArrayIndex]) {
    if (!currentArray) {
      currentArray = [];
    }
    currentArray.push(e);
    compArrayIndex++;
  } else {
    if (currentArray) {
      finalArray.push([...currentArray]);
      currentArray = null;
    }
  }
}

if (currentArray) {
  finalArray.push([...currentArray]);
  currentArray = null;
}

console.log(mainArray);
console.log(compArray);
console.log('finl arr:');
for (let i = 0; i < finalArray.length; i++) {
  const e = finalArray[i];
  console.log(e);
}


texts:
I was trying to solve this questions:

Given an input string, find all combination of unique substrings, which are anagrams of each other and distinct from each other. The substrings must follow 2 <= length(substring) < len(original string).

Example 1:

String: “vadapav”
substrings: va, vad, vada, vadap, vadapa, ad, ada, adap, adapa, adapav, da, dap, dapa, dapav, ap, apa, apav, pa, pav, av
Output: (va, av), (ad, da), (ap, pa)

How can it be optimised in terms of algorithmic and code complexity?

# Code goes below
from collections import defaultdict
import itertools
def anagram_substring(str):
    substr_list = []
    ans = []
    is_present = defaultdict(list)
    for i in xrange(len(str)):
            for j in xrange(i+2, len(str)+1):
                substr_list.append(str[i:j])

        substr_list = list(set(substr_list))
    for substr in substr_list:
        if is_present[''.join(sorted(substr))]:
                    for anagram_str in is_present[''.join(sorted(substr))]:
            ans.append([anagram_str,substr])
        is_present[''.join(sorted(substr))].append(substr)
    return ans

str = raw_input().strip()
print anagram_substring(str)


texts: Double-Ended Queue - Have I over-engineered it again?

texts:
I'm working on an implementation of the Double-Ended Queue as a Doubly-Linked List (for personal enrichment), and I was wondering if anyone minded taking a look at my Constructor/Destructor and Empty functions to see if I'm on the right track.  It should be self-explanatory enough on it's own (I hope).

    DeQueue::DeQueue() {
        // set up the sentinels
        head = new QueueItem();
        tail = new QueueItem();

        head->next = tail;
        tail->last = head;

        head->data = NULL;
        tail->data = NULL;
        tail->next = head->last = NULL;
    }

   DeQueue::~DeQueue() {
    QueueItem* current = head;
    QueueItem* next;
    current = current->next;
    for (;current != tail; current = current->next){
        delete current->last;
    }
    delete current;
    }

    bool DeQueue::Empty() {
        return tail->last == head;
    }

The idea is that the two head and tail sentinels will always remain at the ends, so the easiest way to check if it is empty is to determine if head points to tail or vice versa.  Also, in my destructor, I start at the tail and delete everything from there back, sentinels included.  Any suggestions?

EDIT:  The destructor now moves forward one node, deletes what's behind it, then moves on.  Sound like a better approach?


texts:
I intentionally avoided Python tools which would make this even more trivial.  I would like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.

def unique_char(s):
  ''' Find first non-repeated char in a string '''
  myDict = {}
  first = len(s)
  for c in s:
    if c in myDict.keys():
      myDict[c] += 1
    else:
      myDict[c] = 1
  if 1 in myDict.values():
    for k,v in myDict.items():
      if v == 1:
        if s.index(k) < first:
          first = s.index(k)
    return s[first]
  return(False)


texts: Graceful way to iterate through two arrays and build a master array?

texts:
params[:controller_id].each do |cid|
  params[:zone_number].each do |pzn|
    zone_ids << Zone.find_by_controller_id_and_number(cid,pzn).id
  end
end

I have multiple controllers and multiples zone_numbers, and I would like to build a single array of zone_ids by iterating through controller and then zone per controller.

The code I wrote works - but there has to be a more eloquent way!


texts: check condition with userdefaults value exist or not

texts:
I am check first time userDefaults will not save value return 0 else get value from userDefaults

I am checking if userDefaults will not save the value, and If it doesn't, return 0. If it does, then I get the value from userDefaults.

func scaleMeter() {
    let numberPicker = NumberPicker(delegate: self, maxNumber: 100)
    numberPicker.tintColor = .white
    numberPicker.heading = “Select Scale”

    let ageCount = UserDefaults.value(forKey: defaultsKeys.age)
    guard countValue != nil else {
        numberPicker.defaultSelectedNumber = 0
        self.tabBarController?.present(numberPicker, animated: true,  completion: nil)
        return
    }

    numberPicker.defaultSelectedNumber = Int(ageCount as! String)!
    self.tabBarController?.present(numberPicker, animated: true,  completion: nil)

}

Is this a correct approach, having self.tabBarController?.present both inside and outside the guard?


texts:
I made a simple django migration that adds two field to our Invoices model : first_payment and first_paying_month.

first_payment is obvious : is this the user's first payment, first_paying_month answers to the question: Was this payment made in the same month as the first payment, I'd love a more obvious name for this field.

The values for these fields used to be computed dynamically but now we need them all the time for performance reasons.

The schema part of the migration in handled by Django so there's not much to show. But I'd like inputs on this script, I'm mostly looking for performance optimizations but I'm really open to any feedback :)

from django.db.models import Count

from wallet.models import Invoice
from account.models import User

def set_first_payment_flags(): # We don't use a RunPython for out-of-scope reasons
    users_by_invoice_count = User.objects.annotate(Count("invoice"))
    users_with_one_invoice = users_by_invoice_count.filter(
        invoice__count=1
    ).values_list("id", flat=True)

    users_with_many_invoice = users_by_invoice_count.filter(
        invoice__count__gt=1
    )

    Invoice.objects.filter(user__id__in=users_with_one_invoice).update(
        first_payment=True, first_paying_month=True
    )

    invoices_to_save = []

    for user in users_with_many_invoices:
        # This part has a lot of queries and I'd like to reduce them but I could'nt find anything.
        # I don't see how to reference the first field of a relation in an F expression.
        first_invoice = user.invoice_set.order_by("date_created").first()
        first_invoice.first_payment = True
        invoices_to_save.append(first_invoice)
        user.invoice_set.filter(
            date_created__month=first_invoice.date_created.month
        ).update(first_paying_month=True)

    Invoice.objects.bulk_update(invoices_to_save, fields=["first_payment"])


texts: Applying TrimSideSpaces() method to multiple string properties

texts:
I am looking for generic ideas and guidelines of how to improve the style of my coding and make it more readable and robust.

public class TemplatePart : ITemplatePart
{
    #region Fields

    private readonly List<ITemplatePart> _options = new List<ITemplatePart>();
    private readonly List<ITemplatePart> _cables = new List<ITemplatePart>();

    #endregion // Fields

    #region Constructor

    #endregion // Constructor

    #region Creator

    public static TemplatePart CreateTemplatePart(string partName, string basePart)
    {
        return new TemplatePart
        {
            PartName = partName,
            BasePart = basePart
        };
    }

    public static TemplatePart CreateTemplatePart(DataTable table, DataRow row, int rowIndex)
    {
        return new TemplatePart
        {
            // as you can see, TrimSideSpaces() get's applied for every single content
            // being read from the sheet for each property.
            Key = rowIndex,
            PartName = TrimSideSpaces(row.Field<string>(Strings.TemplateSpreadSheet_Column_PartName)),
            BasePart = TrimSideSpaces(row.Field<string>(Strings.TemplateSpreadSheet_Column_BasePart)),
            Category = TrimSideSpaces(ExtractVendor(table.TableName))

        };
    }

    private static string TrimSideSpaces(string p)
    {
        var rgx = new Regex(@"\S.*\S");
        return rgx.Match(p).Value;
    }

    #endregion // Creator

    #region Public Properties

    public int Key { get; set; }
    public string PartName { get; set; }
    public string BasePart { get; set; }
    // This captures the tab the item is in.
    public string Category { get; set; }
    public double? PriceDom { get; set; }
    public double? PriceInt { get; set; }
    public IEnumerable<ITemplatePart> Options { get { return this._options; } }
    public IEnumerable<ITemplatePart> Cables { get { return this._cables; } }

    #endregion // Public Properties

    #region Private Helpers
    ....
    #endregion // Private Helpers
}

I have a similar concrete class with about 20 properties and I am thinking it might not be a good choice to apply methods on each property such as TrimSideSpaces() in this example.

I apologize if this is not a whole code which could compile.


texts: Controling Document and Window events via array

texts:
I have recently taken on a task to rewrite some very old javascript / jquery and many of the issues are dozens of JS files with onready, onload, onscroll events everywhere and in no logical order! It truly looks like dozens of different developers over many years just sticking whatever code in whatever file.

Moving forward in my re-writes I will get away from this, but I have so many different JavaScript files that for right now the task of cleaning them up and unifying a common functions, $.fn's , prototypes and plugins structure will take me months to organize.

So, knowing I have a long road ahead of me here is what I implemented so incremental deployments would still be possible and to help me organize the code into logical groups for the eventual mass cleanup ahead. The code below is very stable and surprisingly fast, but am I headed in a strange direction?

Define an object I can organize the events into.

myObj = {
    doc: {
        ready:[],
        custom: []
    },
    win: {
        load: [],
        scroll: [],
        resize: [],
        resizestop: [],
    }
}

Push all the code into the logical array that organizes the events.

//for dom ready events
myObj.doc.ready.push(function(){
    alert("document ready")
})

//for window load events
myObj.win.load.push(function(){
    alert("window loaded")
})

//for custom events
myObj.doc.custom.push({
    name:"myCustomName",
    func: function(){
        alert("custom event")
    }
})

Loop through the arrays of the object and execute the stored function.

$(document).on({
    ready:function(){for(var i = 0; i < myObj.doc.ready.length; i++){ myObj.doc.ready[i]() }}
});

$(window).on({
    load:function(){for(var i = 0; i < myObj.win.load.length; i++){ myObj.win.load[i]() }},
    scroll:function(){for(var i = 0; i < myObj.win.scroll.length; i++){ myObj.win.scroll[i]() }},
    resize:function(){for(var i = 0; i < myObj.win.resize.length; i++){ myObj.win.resize[i]() }},
    resizestop:function(){for(var i = 0; i < myObj.win.resizestop.length; i++){ myObj.win.resizestop[i]() }}
})

//bind custom document events
for(var i = 0; i < myObj.doc.custom.length; i++){
    var c = myObj.doc.custom[i];
    $(document).on(c.name, c.func);
}


texts: How to correctly use lock when adding/renewing cached data in asp.net cache?

texts:
This is sort of a follow up question on https://stackoverflow.com/questions/754661/httpruntime-cache-best-practices/11431198 where a reply from frankadelic contains this quote and code sample from http://msdn.microsoft.com/en-us/magazine/cc500561.aspx:

  The problem is that if you've got a query that takes 30 seconds and you're executing the page every second, in the time it takes to populate the cache item, 29 other requests will come in, all of which will attempt to populate the cache item with their own queries to the database. To solve this problem, you can add a thread lock to stop the other page executions from requesting the data from the database.

// check for cached results
object cachedResults = ctx.Cache["PersonList"];
ArrayList results = new ArrayList();

if  (cachedResults == null)
{
  // lock this section of the code
  // while we populate the list
  lock(lockObject)
  {
    // only populate if list was not populated by
    // another thread while this thread was waiting
    if (cachedResults == null)
    {
      ...
    }
  }
}

In my opinion this code sample would have benefitted from showing the actual cache assign/get logic as well. My assumption also is that the cachedResults reference in the sample above should be a static reference, otherwise different threads wont access the same instance.

Is this correct and would the following be a correct implementation of a property where you want to lazy-load data through the cache?

private static object _someDataCacheLock = new object();
private static object _cachedResults;
public List<object> SomeData
{
    get
    {
        HttpContext ctx = HttpContext.Current;
        _cachedResults = ctx.Cache["SomeData"] as List<object>;

        if (_cachedResults == null)
        {
            // lock this section of the code
            // while we populate the list
            lock (_someDataCacheLock)
            {
                // only populate if list was not populated by
                // another thread while this thread was waiting
                if (_cachedResults== null)
                {
                    _cachedResults= GetSomeData(); //db access inside GetSomeData()

                    ctx.Cache.Insert("SomeData",
                            _cachedResults,
                            null, DateTime.Now.AddMinutes(10),
                            TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                }
            }
        }

        return _cachedResults;
    }
}

Ok, so I'm going ahead with this code instead, where I've added one row that in my opinion must have been missing from the MSDN sample... Any feedback on this?

private static object _someDataCacheLock = new object();
public List<object> SomeData
{
    get
    {
        HttpContext ctx = HttpContext.Current;
        List<object> cachedResults = ctx.Cache["SomeData"] as List<object>;

        if (cachedResults == null)
        {
            // lock this section of the code
            // while we populate the list
            lock (_someDataCacheLock)
            {
                //This row was missing in the MSDN sample, I believe...
                cachedResults = ctx.Cache["SomeData"] as List<object>;

                // only populate if list was not populated by
                // another thread while this thread was waiting
                if (cachedResults == null)
                {
                    cachedResults = GetSomeData(); //db access inside GetSomeData()

                    ctx.Cache.Insert("SomeData",
                            cachedResults,
                            null, DateTime.Now.AddMinutes(10),
                            TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                }
            }
        }

        return cachedResults;
    }
}


texts: Averages and standard deviations for a Knn application

texts:
I'm working on a small command line application in c# where data is read from a CSV file along with a query and KNN is calculated for the query based on the data.

My problem isn't the algorithm at all, I understand it. Im having difficulty working with my code though. I think it's down to bad planning.

Here's my object for holding a "row" of data. the data is based on weather data and if something was played that day or not.

class dataRow
{
    public double sun {get; set;}
    public double temp {get; set;}
    public double humidity {get; set;}
    public double wind {get; set;}
    public bool play {get; set;}

    public override string ToString()
    {
        return string.Format("\n\tSun: {0}\n\tTemp: {1}\n\tHumidity: {2}\n\tWind: {3}\n\tPlay: {4}", sun, temp, humidity, wind, play);
    }

    public double[] toArray()
    {
        return new double[] { sun, temp, humidity, wind };
    }
}

I'm trying to Znormalize the data and the query before I work out euclidean distance between points but I'm stuck in a rut of annoying nested loops and I have a hunch there's a better way to code what I'm doing

class KNN
{
    public int numK;
    List<dataRow> dataSet;
    dataRow QueryRow;
    dataRow stdDev;
    dataRow avg;

    public KNN(String[] input)
    {
        numK = Int32.Parse(input[0]);
        dataSet = dataImport.import(input[1]);
        //inputRow = dataImport.import(input[2])[0];
        avg = getAverage(toDoubleList(dataSet));
    }

    public List<double[]> toDoubleList(List<dataRow> input)
    {
        var doubleList = new List<double[]>();

        for(int i =0; i<input.Count; i++)
        {
            doubleList[i] = input[i].toArray();
        }

        return doubleList;
    }

    public dataRow getAverage(List<double[]> input)
    {
        var avgTotals = new double[4];
        var avgRow = new dataRow();

        for (int y = 0; y < 3; y++)
        {
            double avg = 0;

            for (int x = 0; x < input.Count; x++)
            {
                avg += input[x][y];
            }

            avgTotals[y] = avg / input.Count;
        }

        avgRow.sun = avgTotals[0];
        avgRow.temp = avgTotals[1];
        avgRow.sun = avgTotals[2];
        avgRow.wind = avgTotals[3];

        return avgRow;
    }

    public dataRow getStdDev(List<double[]> input)
    {
        var stdDevTotals = new double[4];
        var stdDevRow = new dataRow();

        for (int y = 0; y < 3; y++)
        {
            double stdDev = 0;

            for (int x = 0; x < input.Count; x++)
            {
                stdDev += Math.Pow(input[x][y] - this.avg.toArray()[y], 2);
            }

            stdDev = Math.Sqrt(stdDev/input.Count);
            stdDevTotals[y] = stdDev / input.Count;
        }

        stdDevRow.sun = stdDevTotals[0];
        stdDevRow.temp = stdDevTotals[1];
        stdDevRow.sun = stdDevTotals[2];
        stdDevRow.wind = stdDevTotals[3];

        return stdDevRow;
    }
}

Any advice or ideas? (All harsh criticism welcome!)


texts:
Please look the code below

#include<stdio.h>
void quicksort(int *,int ,int);
int partition1(int *,int ,int);
void swap1(int *,int *);

int main()
{

int low = 0;
int length;
int i;
int a[100];
int high;

printf("Enter  the length of array\n");
scanf("%d",&length);

high=length-1;

printf("Enter the array elememts\n");

for(i=0;i<=high;i++)
{
 scanf("%d",&a[i]);
}

quicksort(a,low,high);

printf("The sorted array\n");

for(i=low;i<=high;i++)
{
  printf("%d--",a[i]);
}

 printf("\n");
 return 0;
}

void quicksort(int a[],int low,int high)
{
   int p;

  if(low<high)
  {
     p=partition1(a,low,high);
     quicksort(a,low,p-1);
     quicksort(a,p+1,high);
  }
}

 int partition1(int a[],int low,int high)
{
   int pivot=a[high];
   int i=low-1;
   int j=low;

   for(j=low;j<high;j++)
  {
      if(a[j]<a[high])
      {
         i++;
         swap1(&a[i],&a[j]);
      }
  }
        swap1(&a[i+1],&a[high]);
        return i+1;
}

  void swap1(int* a,int* b)
 {
   int  temp;
   temp=*a;
   *a=*b;
   *b=temp;
 }

This is the working program of quick sort.Can anyone tell me the way to make this program much better?

  please do the necessary changes  required.


texts: N-tier application with BAL and DAL methods

texts:
I was just asking this question over here. I'm on a project in which I'm failing to see the point of how a previous developer made decisions. I HAVE taken over this project and wish to make changes.

Same exact method names in DAL and BAL
Static is EVERYWHERE
What should I do with new methods to follow best practices?

Example of existing code:

Calling appliction (could be console app or web app etc. agnostic ):

DataSet DS = CreditMgr.GetCreditRqstInfo(ddlGEO.Text);

BAL

public class CreditMgr
{
   public static DataSet GetCreditRqstInfo(String GeoID)
    {
        try
        {
            DataSet DS = new DataSet();
            DS = CreditIntfDB.GetCreditRqstInfo(GeoID);
            return DS;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

DAL

public class CreditIntfDB
{
     public static DataSet GetCreditRqstInfo(String GeoID)
    {
        try
        {
            Database DB = new SqlDatabase(Common.ConnectionString);
            String SQLCommand = Common.SPGetRqstInfo;
            DbCommand DBCommand = DB.GetStoredProcCommand(SQLCommand);
            DBCommand.CommandTimeout = Common.CommandTimeOut;
            DB.AddInParameter(DBCommand, "@a_geo_id", DbType.String, GeoID);
            DataSet DS = new DataSet();
            DB.LoadDataSet(DBCommand, DS, new String[] { "CreditRqstInfo" });

            return DS;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Yes, the whole point is to have layers of separation, but when the same method names are being used, and static, and each are simply doing the same exact thing with passing in string and returning a DataSet has "code smell" to me.

Any suggestions on better ways?


texts:
I haven't been programming for a while, I wanted to do a simple project to warm myself up and get back into the game; I made this simple tool that finds the probabilities of coin toss combinations. Enter a number to get all combinations with that many flips, or enter a string to search for that combination, i.e. H**H would find all combinations starting and ending with heads.

module Every
  def every(&block)
    arys = map do |ary|
      base_ary = eval ary.inspect.split(':')[1] rescue nil
      base_ary.nil? ? ary : base_ary
    end
    longest = arys.max_by(&:count).count

    arys.map!.with_index do |ary, i|
      cyc = ary * ( longest / ary.count + 1 )
      self[i].is_a?(Enumerator) ? cyc[0...longest] : ary
    end
    arys.transpose.each &block
  end
end

class Array
  # I didn't have to use this module, but I had written it in the past
  # and this seemed like a good place to use it
  include Every
end

class CoinToss
  attr_accessor :outcomes, :reference, :iterations, :combins, :occrs

  def initialize(outcomes = ["H", "T"], reference = gets.chomp.upcase)
    @outcomes = outcomes.each &:to_s
    if (Integer reference rescue false)
      @iterations = reference.to_i
      @reference = "*" * @iterations
    else
      set = @outcomes.join("*")
      raise ArgumentError, "Invalid Characters" unless reference =~ /\A[#{set}]+\z/
      @reference = reference
      @iterations = @reference.length
    end

    @combins = @outcomes.repeated_permutation(@iterations).to_a
    @occrs = 0

    ref = [@reference.chars]
    # every loop ref is repeated but combins is iterated
    [ref.cycle, @combins].every do |r, c|
      # replaces `*` in ref with regex string for characters from `outcomes`
      @template = r.join.gsub "*", "[#{@outcomes.join}]"
      @occrs += 1 unless !(c.join =~ /#{@template}/) # +1 if it matches the template
    end
  end

  def get_combins(match_marker = "~")
    @combins.each do |c|
      # m is blank if combin doesn't match the template
      m = !(c.join =~ /#{@template}/) ? "" : match_marker
      line = Array c.join
      # skips marker when reference contains only `*`
      line << m unless @reference.chars.all? { |r| r == "*" }
      puts line.join(" ")
    end
  end

  def get_probability(rationalize = true, match_word = "out of")
    puts Rational(occrs, combins.length) if rationalize
    puts [@occrs, match_word, @combins.length].join(" ") unless rationalize
  end
end

tosses = CoinToss.new
tosses.get_combins
tosses.get_probability(rationalize = false)
tosses.get_probability(rationalize = true)

Thanks for any advice.


texts: Project Euler #5 - Lowest common multiple of 1 through 20

texts:
This is my code.  All comments welcome.  Last time run it only took 335 milliseconds:

static bool CheckMultiples(int val)
{
    for (int i = 1; i <= 20; i++)
    {
        if (val % i != 0)
            return false;
    }

    return true;
}

static void Main(string[] args)
{
    Stopwatch s = new Stopwatch();
    s.Start();

    int Num = 20;
    while (!CheckMultiples(Num))
    {
        Num += 20;
    }

    s.Stop();

    Console.WriteLine("The smallest number divisible by all numbers 1-20 is {0}.", Num);
    Console.WriteLine("The time took is {0} milliseconds.", s.ElapsedMilliseconds);
}


texts: Creating chat commands properly with Socket.IO

texts:
I am developing a chat program (mountreus-chat and GitHub) in Node.js using Socket.io and my code looks awful. I'm starting to use commands and now it's even worse.

Here's a code snippet (you can find every detail on the Github repo):

io.on('connection', function(socket){
      if(socketConnections().length <= 1024){
        socket.username = socket.handshake.query.username;
        socket.toString = function(){return this.name};
        socket.join(socket.handshake.query.room);
        socket.on('postName', function(username){
                socket.username = username;
                });
        var socketsConnected = socketConnections(socket.handshake.query.room, "/");
        io.emit('connections', socketsConnected.length + 1);
        socket.on('chat message', function(msg){
            var markedMessage =  markdown.renderInline(msg.message);
            var messageDate = moment(msg.date).format("LT, D/M");
            var firstWord = markedMessage.substr(0, markedMessage.indexOf(" "));
            if(msg.message !== "/help"){
            if(firstWord === "/broadcast"){
            var finalMessage = markedMessage.substr(markedMessage.indexOf(" ") + 1);
             var messageToBeSent = '
 BROADCAST: ' + finalMessage + '

' + messageDate + '
';
            }else if(firstWord === "/bot-say"){
                var finalMessage = markedMessage.substr(markedMessage.indexOf(" ") + 1);
                var messageToBeSent = '
 Chat bot: ' + finalMessage + '

' + messageDate + '
';
            }else{
            var messageToBeSent = '
' + escapeHTML(msg.username) + ': ' + markedMessage + '

' + messageDate + '
';
            }
            if(messageToBeSent.length <= 8192){
                  if(!verifyEmptyness(msg.message)){
                    io.to(socket.handshake.query.room).emit('chat message', messageToBeSent);
                  }else{
                  socket.emit('chat message', 'PM: Sorry, you cannot send empty messages.');
                  }
                }else{
                  socket.emit('chat message', 'PM: Oops! You cannot send messages longer than 8192 characters. Sorry!');
                }
            }else{
                socket.emit('chat message', 'Montreus Chat - v1.3.3
Available commands:
/help - Display help commands
/bot-say &lt;message&gt; - Give something for the bot to say!
/broadcast &lt;message&gt; - Broadcast a message');
            }
        });
      socket.on('users', function(){
                var socketsConnected = socketConnections(socket.handshake.query.room, "/");
                io.to(socket.handshake.query.room).emit('connections', socketsConnected.length + 1);
                });
      socket.on('disconnect', function(){
                var socketsConnected = socketConnections(socket.handshake.query.room, "/");
                io.to(socket.handshake.query.room).emit('connections', socketsConnected.length + 1);
                });
      }else{
      socket.emit('chat message', 'PM: Sorry, we cannot allow more than 1024 connections in the server');
      socket.emit('chat message', 'PM: Disconnecting! Try again later.');
      socket.emit('connections', 'You are not connected.');
      socket.disconnect();
      }
      });


texts:
I was doing a programming challenge and the object was to validate an email address, I wrote a simple little email validator and would like some input on how I can make it more efficient.

How it works, it has two validations, one with a regex, and one validating the length (most email addresses are over 12 characters, so that's what I went with).
The regex checks for an @ and a . symbol. This is all inside of its own validation class.

Source:

import re

class Validator(object):

    def __init__(self, email):
        self.email = email

    def check_for_symbol(self):
        if re.search("[@.]", self.email) is None:
            return False
        else:
            return True

    def check_length(self):
        if len(self.email) >= 12:
            return True
        else:
            return False

def email_to_verify():
    return raw_input('Enter your email address: ')

def check_email(email):
    validator = Validator(email)
    symbol = validator.check_for_symbol()
    if symbol is False:
        print "Your email address is not valid. Failed symbols.."

    length = validator.check_length()
    if length is False:
        print "Your email is not valid. Failed length"

    if length and symbol is True:
        print "Email is a valid email address."

if __name__ == '__main__':
    e = email_to_verify()
    check_email(e)

Is there a way to make this more efficient?

Examples of usage:

C:\challenges>python email_val.py
Enter your email address: test
Your email is not valid. Failed symbols check.
Your email is not valid. Failed length check.

C:\challenges>python email_val.py
Enter your email address: te@t.t
Your email is not valid. Failed length check.

C:\challenges>python email_val.py
Enter your email address: gmail@gmail.gmail
Email is a valid email address.


texts: Crypto createCipheriv and createDecipheriv for authentication

texts:
I'm not an expert in authentication, so I want to make sure I have done everything right.

I am using crypto.createCipheriv and crypto.createDecipheriv for authentication.

I will store the key in the database, and the initialization vector, IV, and encrypted data in cookies. When requested the server will try to decrypt encrypted data from cookies using the IV from the cookies and the key from the database. If the decryption is successful the request can proceed.

If the database is compromised, the hacker will not be able to use the database keys, because they will need the code to generate the IV and the data cookies.

The database key is the same for multiple sessions, only the IV and data are different.

Initial login conformation will be handled using external service, so I can focus on interacting with the cookies.

Are there problems with my solution?

import crypto from 'crypto'

function encrypt(dataToEncrypt /*random data*/) {
    let dbKey = crypto.randomBytes(32) //db
    let userKey = crypto.randomBytes(16) //cookie

    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(dbKey), userKey)
    let encryptedData = cipher.update(JSON.stringify(dataToEncrypt))
    encryptedData = Buffer.concat([encryptedData, cipher.final()])

    return { userKey: userKey.toString('hex'), dbKey: dbKey.toString('hex'), encryptedData: encryptedData.toString('hex') }
}

function decrypt(userProvidedKey, dbKey, dataToDecrypt) {
    let userKeyBuffer = Buffer.from(userProvidedKey, 'hex')
    let dbKeyBuffer = Buffer.from(dbKey, 'hex')

    let decryptedData = Buffer.from(dataToDecrypt, 'hex')
    let decipher = crypto.createDecipheriv('aes-256-cbc', dbKeyBuffer, userKeyBuffer)
    decryptedData = decipher.update(decryptedData)
    decryptedData = Buffer.concat([decryptedData, decipher.final()])

    return decryptedData.toString()
}


texts:
Here is a simple script that I am using to ping 50 sites at a time and check if they are up or not. If not, save the down time with error in MongoDB.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from urllib.request import urlopen, Request
from threading import Thread
from time import sleep, time
import datetime
import queue
import pymongo

''' A Simple script to  ping multiple sites at a time
and capture the down sites
'''
__author__ = "Aamir khan"
__version__ = 1.1

_MAX_CONNECTIONS = 50
counter = 0
downsites = []
now = datetime.datetime.utcnow  # time stamp

# DO NOT ON BOTH AT THE SAME TIME
_DEBUG = False
_MONITOR = True

def getcollection(db='websites', colname='website_urls'):
    return pymongo.MongoClient().get_database(db).get_collection(colname)

# to save downsites in db
ds = getcollection(colname="downsites")

# fetch urls from db
if _DEBUG:
    print("Fetching Urls")
    urls = getcollection().find()
    print("%d Urls Fetched" % urls.count())
    print("pulling urls to the queue")
    q = queue.Queue(urls.count())
    for url in urls:
        url = url['url']
        q.put(url)
    print("pulled urls to the queue")
    print("The size of the Queue is %d" % q.qsize())
else:
    urls = getcollection().find()
    q = queue.Queue(urls.count())
    for url in urls:
        url = url['url']
        q.put(url)

del urls

def inc_counter():
    global counter
    # lock.acquire()
    counter += 1
    # lock.release()

def monitor():
    total = q.qsize()
    if total > 0:
        while counter < total:
            print("%d Request sent" % counter)
            sleep(1)
        print("Total {}/{} Request Sent".format(counter, total))
        assert counter == total

def ping(uri):
    req = Request(uri, headers={
        "User-Agent": ("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0)"
                       " Gecko/20100101 Firefox/51.0")
    })
    req.get_method = lambda: 'HEAD'

    try:
        with urlopen(req) as r:
            res = r.getcode(), uri, now()
    except Exception as e:
        res = str(e), uri, now()
    finally:
        if _DEBUG:
            err, uri, last_check = res
            print("Requesting = ", uri, "Request Method = ", req.get_method(),
                  "\nstatus = ", err, "time", last_check)
            print("-----" * 10)
        if _MONITOR:
            inc_counter()
            sleep(1)
        sleep(0.5)  # sleep a while to release the workload from cpu
    return res

def process(url):
    err, uri, last_check = ping(url)
    if err != 200:
        ds.insert_one({"Error": err.strip('<>'),
                       "url": uri, "last_checked": last_check})

def worker():
    while True:
        url = q.get()
        if url is None:
            break
        process(url)
        q.task_done()

if __name__ == '__main__':
    workers = []

    if _MONITOR:
        Thread(target=monitor).start()  # start monitoring reqest/sec
        start_time = time()

    for i in range(_MAX_CONNECTIONS):
        t = Thread(target=worker)
        t.start()
        workers.append(t)

    # block until all tasks are done
    q.join()

    # poision kill
    for i in range(_MAX_CONNECTIONS):
        q.put(None)

    # wait for all the threads to join
    for w in workers:
        w.join()

    if _MONITOR:
        print("Time taken %f (sec)" % (time() - start_time))

Questions:

Can I make use of better threading techniques?
Can I eliminate the duplication of code while _DEBUG is on line 35 to 54?
I would love/prefer to see a functional version of this program.
How can I improve the performance? (my target is to ping 1000000 sites under an hour)


texts: Count the number of combinations with gap-restriction for every pair of values

texts:
A lottery draw consists of choosing 6 different values from 1 to 50.

I want to calculate the number of combinations with gaps of at least 3 between every pair of values.

I have used the following Python 2.7 script:

def func(array,length,min,max,gap):
    if len(array) == length:
        # print array
        return 1
    count = 0
    for n in range(min,max+1):
        count += func(array+[n],length,n+gap,max,gap)
    return count;

print func([],6,1,50,3)

Questions:

Are there any coding improvements that I can apply?
Is there a different method with which we can do it more efficiently?
Although more suitable for math.stackexchange.com, is there a straightforward formula?


texts: Calculating series of rows to use to play a melody on 5-row Bayan Accordion

texts:
This was my first attempt at writing a program in LISP. Can anyone give any guides as to how it could be improved? The multiple loops in best-pattern seem awkward (I'd normally do that in just one loop but there doesn't seem to be a way of doing that with LOOP, although I'm told there's an iterate extension that can do it), as does the way of calculating alternatives..

(defparameter *rows* (list (list :c :ds :fs :a) (list :cs :e :g :as) (list :d :f :gs :b)))

(defun row-for-note (note)
    (position-if (lambda (row) (find note row)) *rows*)
)

(defun rows-for-notelist (notelist)
    (mapcar #'row-for-note notelist)
)

(defun possible-alternates (rowlist)
    (let ((alternatives '(())))   ;; Lots of irritating silly parentheses
        (when (> (length rowlist) 1)
           (setq alternatives (possible-alternates (cdr rowlist)))
        )
        (case (car rowlist)
            ((0) (mapcar (lambda (x) (append '(0) x)) alternatives))
            ((1) (append (mapcar (lambda (x) (append '(1) x)) alternatives)
                         (mapcar (lambda (x) (append '(-2) x)) alternatives)))
            ((2) (append (mapcar (lambda (x) (append '(2) x)) alternatives)
                         (mapcar (lambda (x) (append '(-1) x)) alternatives)))
        )
    )
)

(defun count-jumps (rowlist)
    (loop for (a b) on rowlist while b counting (> (abs (- a b)) 1))
)

(defun best-pattern (notelist)
    (let ((minval (loop for x in (possible-alternates (rows-for-notelist notelist)) minimize (count-jumps x))))
    (loop for x in (possible-alternates (rows-for-notelist notelist)) when (= (count-jumps x) minval) collect x))
)

(If you're wondering what the program does, it tries to calculate the "most efficient" series of rows to use to play a melody on 5-row Bayan Accordion.)


texts:
I'm currently learning programming for the first time and I've created the following implementation of quick sort in C#. I basically read a very basic overview of how quick sort works recursively and implemented it without looking at any concrete examples of its implementation so that I could learn the most from it.

Could you let me know what you think and where it could be optimized?

class Program
{
    static void Main(string[] args)
    {
        var input = new int[] {  10, 3, 20, 5, 200 };
        QuickSort(0, 0, input.Length-1, input);
        Console.WriteLine("Sorted output: :");
        new List<int>(input).ForEach(x => Console.Write(x + ","));
        Console.ReadLine();
    }

    /// <summary>
    /// sample input: 5 7 3 9 2
    /// same output: 2 3 5 7 9
    /// </summary>
    /// <param name="numbers"></param>
    public static void QuickSort(int pivotIndex, int startIndex, int endIndex, int[] numbers)
    {
        if (startIndex == endIndex) return;

        int pivotNumber = numbers[pivotIndex];

        var lowerThanPivot = new List<int>();
        var higherThanPivot = new List<int>();

        for(int i = startIndex; i <= endIndex; i++)
        {
            if(i != pivotIndex)
            {
                if( numbers[i] <= pivotNumber )
                    lowerThanPivot.Add(numbers[i]);
                else
                    higherThanPivot.Add(numbers[i]);
            }
        }

        // now lets put the pivot number in the correct place
        numbers[startIndex + lowerThanPivot.Count] = pivotNumber;

        // reinsert the numbers lower than pivot in the right place
        int z = startIndex;
        lowerThanPivot.ForEach(x => numbers[z++] = x);

        z++; // *** skip over the new pivot index ***

        // reinsert the numbers higher than pivot in the right place
        higherThanPivot.ForEach(x => numbers[z++] = x);

        // recursively call to sort each remaining elements

        int newLeftPivot = startIndex;
        int newEndLeftIndex = newLeftPivot + lowerThanPivot.Count - 1 ;

        int newRightPivot = lowerThanPivot.Count + 1;
        int newEndRightIndex = newRightPivot + higherThanPivot.Count - 1;

        if(lowerThanPivot.Count> 0)
            QuickSort(newLeftPivot, newLeftPivot, newEndLeftIndex, numbers);

        if(higherThanPivot.Count > 0)
            QuickSort(newRightPivot, newRightPivot, newEndRightIndex, numbers);

    }
}


texts:
I need help moving my solve code in my calculator into its own separate class.

import java.awt.*;
import java.applet.*;

public class Calculator extends Applet
{

private Label calculatorL; //Sets the label
private boolean firstDigit = true; //Sets Boolean firstDigit to be true
private float savedValue = 0.0f;//Sets saved value to 0
private String operator = "="; //Sets Default operator

public void init ()
{

    setLayout (new BorderLayout()); //Sets the layout

    add ("North", calculatorL = new Label ("0", Label.RIGHT));

    Panel calculatorPanel = new Panel(); //Adding a panel for the buttons
    calculatorPanel.setLayout (new GridLayout (4, 4));
    calculatorPanel.setBackground(Color.CYAN);
    calculatorPanel.setForeground(Color.BLUE);

    addButtons (calculatorPanel, "123-");
    addButtons (calculatorPanel, "456*");
    addButtons (calculatorPanel, "789/");
    addButtons (calculatorPanel, ".0=+");

    add("Center", calculatorPanel);

}

public boolean action (Event event, Object inputobject)
{
    if (event.target instanceof Button)
    {
        String inputstring = (String)inputobject;
        if ("0123456789.".indexOf (inputstring) != -1)
        {
            if (firstDigit)
            {
                firstDigit = false;
                calculatorL.setText (inputstring);
            }
            else
            {
                calculatorL.setText(calculatorL.getText() + inputstring);
            }
        }
        else
        {
            if(!firstDigit)
            {
                solve(calculatorL.getText());
                firstDigit = true;
            }
            operator = inputstring;
        }

        return true;

        }
        return false;

    }

    public void solve (String valueToBeComputed)
    {
        float sValue = new Float (valueToBeComputed).floatValue();
        char c = operator.charAt (0);
        switch (c)
        {
            case '=': savedValue = sValue;
                break;

            case '+': savedValue += sValue;
                break;

            case '-': savedValue -= sValue;
                break;

            case '*': savedValue *= sValue;
                break;

            case '/': savedValue /= sValue;
                break;
        }

        calculatorL.setText (Float.toString(savedValue));
    }

    public void addButtons (Panel panel, String labels)
    {
        int count = labels.length();

        for (int i = 0; i<count; i ++)
        {
            panel.add (new Button (labels.substring(i,i+1)));
        }
    }
    }


texts: Copy-to-clipboard function from a React.js component

texts:
I have a React component with a copyToClipboard method, which all works fine, but feels extremely verbose and quite hacky (namely, having to create a new select element, hide it, focus/select/copy it and then delete it). From what I've read, there are a couple of different ways to achieve copy-to-clipboard functionality, but it seems as though this sort of approach is relatively common, and one or two of the other ways doesn't have great browser support yet.

This method gets called when a click event is triggered on a child component, which passes the value to be copied as a single argument.

Is there a nicer/better way to go about doing this?

copyToClipboard = (value: string) => {
  const copyTextarea = document.createElement('textarea');
  copyTextarea.value = value;
  copyTextarea.style.position = 'fixed';
  copyTextarea.style.opacity = '0';
  copyTextarea.style.pointerEvents = 'none';
  document.body.appendChild(copyTextarea);
  copyTextarea.focus();
  copyTextarea.setSelectionRange(0, value.length);

  try {
    document.execCommand('copy');

    this.showToastNotification(`Successfully copied ${value} to clipboard!`);
  } catch (err) {
    throw new Error(err);
  } finally {
    copyTextarea.remove();
  }
};


texts: Sort all the characters according to their brightness

texts:
I wrote a little fractal noise generator the other day, and to test it I wanted to display the dark values with a darker character and the bright values with bright characters (I use a dark background with light foreground). So I wrote a simple java program to do this, and here it is:

package com.loovjo.brightSort;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class Main {

    private static final int IMG_SIZE = 128;

    public static void main(String[] args) {
        ArrayList<Character> order = new ArrayList<Character>();

        HashMap<Character, Float> brightness = new HashMap<Character, Float>();

        long timer = System.currentTimeMillis();

        int max = 0xFF;

        for (char c = 0; c < max; c++) {
            Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
            if (!(!Character.isISOControl(c)) && c != KeyEvent.CHAR_UNDEFINED && block != null
                && block != Character.UnicodeBlock.SPECIALS)
                // We don't want any unprintables in out gradient.
                continue;

            brightness.put(c, getBrightness(c));
            if (System.currentTimeMillis() - timer > 100) {
                timer = System.currentTimeMillis();
                System.out.println(((float) c / max) * 100 + "% done.");
            }
        }

        // Sort brightness into order

        while (!brightness.isEmpty()) {
            char min = '\0';
            float val = Float.MAX_VALUE;
            for (Entry<Character, Float> e : brightness.entrySet()) {
                if (e.getValue() < val) {
                    val = e.getValue();
                    min = e.getKey();
                }
            }
            brightness.remove(min);
            order.add(min);
        }
        for (int i = 0; i < 10; i++)
            System.out.println(order.stream().map(c -> "" + c).collect(Collectors.joining()));

     }

    private static float getBrightness(char c) {
        BufferedImage img = new BufferedImage(IMG_SIZE, IMG_SIZE, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.setFont(new Font("Monaco", Font.PLAIN, (int) (img.getHeight() * 0.5)));
        // img.getHeight() * 0.5 because else some of the characters will be
        // rendered off-screen, giving them wierd values

        g.drawString(c + "", 0, g.getFont().getSize());
        g.dispose();

        int totalBrightness = 0;
        for (int x = 0; x < img.getWidth(); x++) {
            for (int y = 0; y < img.getHeight(); y++) {
                totalBrightness += img.getRGB(x, y) & 0xFF;
            }
        }

        return totalBrightness / (float) (img.getWidth() * img.getHeight());
    }

}

For those of you who can't run this program, here's a screenshot of the output:


texts:
I have the following class for 2D points:

class Point {
private:
    double _x, _y;

public:
    Point(double x, double y) : _x(x), _y(y);

    double x() const { return _x; }
    double y() const { return _y; }
};

I wanted to add a few comparison functions that compared objects of this class in different ways.

One of them is just a simple function:

/// Returns whether A has a smaller y-coordinate than B
/// (and smaller x-coordinate in case of equality).
bool yComp(const Point &A, const Point &B) {
    if (A.y() != B.y()) return A.y() < B.y();
    return A.x() < B.x();
}

The other is a struct with operator() defined on it:

struct angleComp {
    Point origin;
    angleComp(const Point &P);
    bool operator()(const Point &A, const Point &B);
};

// Constructs a new angle comparison with P as origin
angleComp::angleComp(const Point &P) : origin(P) {}

// Compares according to the angles that the lines joining each point
// to a given origin form with the x-axis.
bool angleComp::operator()(const Point &A, const Point &B) {
    GeometricVector u = A - origin, v = B - origin;
    return u.x()*u.x()*u.sqrNorm() < v.x()*v.x()*v.sqrNorm();
}

Do I put the comparisons inside the class definition? The first function could be made a static method, but the problem is I can't put angleComp inside the class (as a static member) since one of its fields is of type Point itself, which would be an incomplete type (inside the class declaration). And I would prefer these comparison functions to be grouped together (instead of one being a static member, and the other being a top-level thing).

So, an alternative would be to put both outside the class, but to retain some grouping, putting all of them in a namespace:

namespace PointComp {
    bool yComp(const Point &A, const Point &B);

    struct angleComp {
        Point origin;
        angleComp(const Point &P);
        bool operator()(const Point &A, const Point &B);
    };
}


texts:
I just built an audio player in Angular 2 using a player component and a player service. It's all working fine, I just feel like there is a much better way to do this.

Should the audio object be in the service or the component? I'm skeptical because I'm using three different observables and I don't think that is the best way to do it.

player.component.ts:

export class PlayerComponent implements OnInit, OnDestroy {

  // General variables
  private song: Song;
  private currentTime: string;
  private fullTime: string;
  private isPlaying: boolean;
  // Subscription variables
  private songSubscription: any;
  private currentTimeSubscription: any;
  private fullTimeSubscription: any;

  constructor(private _playerService: PlayerService) {
  }

  ngOnInit() {
    this.songSubscription = this._playerService.song.subscribe(data => this.song = data);
    this.currentTimeSubscription = this._playerService.currentTime.subscribe(data => this.currentTime = data);
    this.fullTimeSubscription = this._playerService.fullTime.subscribe(data => this.fullTime = data);
    console.log("Player subscription initialized");
  }

  toggleAudio() {
    this.isPlaying = this._playerService.toggleAudio();
  }

  ngOnDestroy() {
    this.songSubscription.unsubscribe();
    this.currentTimeSubscription.unsubscribe();
    this.fullTimeSubscription.unsubscribe();
    console.log("Player subscription destroyed");
  }

}

player.service.ts:

export class PlayerService {

  private audio: any;
  public song: Subject<Song> = new Subject<Song>();
  public currentTime: Subject<string> = new Subject<string>();
  public fullTime: Subject<string> = new Subject<string>();

  constructor(private _utilityService: UtilityService) {
    this.audio = new Audio();
  }

  setPlayer(song: Song) {
    this.song.next(song);
    this.audio.src = song.audio;
    this.audio.oncanplaythrough = () => {
      this.audio.play();
      this.fullTime.next(
        this._utilityService.getFormatedTime(this.audio.duration)
      );
    };
    this.audio.ontimeupdate = () => {
      this.currentTime.next(
        this._utilityService.getFormatedTime(this.audio.currentTime)
      );
    };
  }

  toggleAudio() {
    if (this.audio.paused) {
      this.audio.play();
    } else {
      this.audio.pause();
    }

    return this.audio.paused;
  }

}

player.component.html:

    {{currentTime}}

    {{song.title}} by {{song.artist}}

    {{fullTime}}

It's a pretty primitive player right now. I want to make sure I'm implementing it correctly before I add more features.


texts:
The problem is from yesterday's contest from Codeforces.

I have observed that, from the left side (i.e. MSB), for every digit, if we replace the given number with the output of f when after passing the digit - we get a bigger number we will get the desired output. I'm a beginner in programming and have written code with Python 3, which is showing TLE after submission (though it is correct and gives correct output for the sample test cases). I think a better algorithm is needed.

Variables st (start index), flag, cntr (length of contiguous subsegment ) are taken for the condition the part where we will replace the digits needs to be contiguous subsegment:

n = int(input())
s = input()
f = list(map(int,input().split()))
result = []
st = -1
flag = 1
cntr = 0
for i in range(len(s)):
    x=f[int(s[i])-1]
    if(x>int(s[i])):
        result.append(str(x))
        if(flag==1):
            st = i
            flag = 0
        if(flag==0):
            cntr+=1
    else:
        result.append(s[i])
        if(st!=-1 and (i-st-1)!=cntr):
            break
for j in range(i+1,len(s)):
    result.append(s[j])
#print(result)
r = int(''.join(result))
print(r)

Can anyone make any improvement in my code? I know there is a tutorial on that website, but I want to learn how to develop code which I have written already.


texts: Minimize array and output the remainder with respect to 1 second time limit

texts:
This is my code:

n = int(raw_input())
seq = raw_input().split()
def minimize_list(lst):
    new_lst = []
    k = len(lst)
    for i in range(k-1):
        new_lst.append(lst[i+1]-lst[i])
    return new_lst
for i in range(len(seq)):
    seq[i] = int(seq[i])
final_list = []
for num in seq:
    final_list.append(num)
while len(final_list) != 1:
    final_list = minimize_list(final_list)
print (final_list[0])%(1000000000+7)

It takes a number and a sequence of numbers. (The first number is the number of numbers in the sequence). It then calculates a shorter sequence with the difference of adjacent numbers until there is just 1 number. Unfortunately, The time complexity is not good enough. I have to make it better to meet the time limit which is 1 second.

Any idea?

Note: I cannot see the input. I can just pass my code to a server which has 10 examples and runs my code on them. The server then tells me that this code has exceeded the time limit for some examples.

Update: I want to print (final_list[0])%(1000000000+7)


texts: Generate a Jekyll blog post template using shell

texts:
I'm creating my first Bash script newpost.sh, which generates a Markdown file containing the metadata for a new blog post. This blog post will be hosted in a Jekyll engine, like GitHub pages. The idea is to facilitate:

The generation of date
The conversion from the post title to URL
Compatible in both mac OS and Linux

So user can really focus on writing blog, instead of handling different metadata.

#!/bin/bash
#
#    This script creates a new blog post with metadata in ./_posts
#    folder. Date will be generated according to the current time in
#    the system. Usage:
#
#        ./newpost.sh "My Blog Post Title"
#

title=$1

if [ -z "$title" ]; then
    echo "usage: newpost.sh \"My New Blog\""
    exit 1
fi

bloghome=$(cd "$(dirname "$0")"; pwd)
url=$(echo "$title" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')
filename="$(date +"%Y-%m-%d")-$url.md"
filepath=$bloghome/_posts/$filename

if [ -f filepath ]; then
    echo "$filepath already exists."
    exit 1
fi

touch $filepath

echo "---" >> $filepath
echo "layout:      post" >> $filepath
echo "title:       \"$title\"" >> $filepath
echo "date:        \"$(date +"%Y-%m-%d %H:%M:%S %z")\"" >> $filepath
echo "categories:  [weekly]" >> $filepath
echo "---" >> $filepath

echo "Blog created: $filepath"

Any feedback is welcome!


texts:
I want to ask the user about whether he wants to continue playing or not. For this I have used,

char choice;
do
{
     System.out.println("Would you like to continue?(y/n)");
     choice=sc.nextLine().charAt(0);
     if (choice!='y' && choice!='n')
     {
           System.out.println("Invalid Entry");
     }
}while (choice!='y' && choice!='n');

This is working fine and I didn't face any issues, but is that the right way?


texts: Slice a list or NumPy array into consecutive tuples

texts:
My function needs two params(a,b) and if...break, which seems redundant. Can it be made prettier?

def slice_list(lst,num):
    """
    Given a list or Numpy array，
    get consecutive tuples based on specific window.
    """
    rst = []
    for i,_ in enumerate(lst):
        a = i
        b = i + num
        if len(lst[a:b])<num:
            break
        rst.append(tuple(lst[a:b]))
    return rst

Example:

>>> lst = np.array([10, 11, 12, 13, 26, 28])
>>> slice_list(lst,4)
[(10, 11, 12, 13), (11, 12, 13, 26), (12, 13, 26, 28)]