texts: Extension method for getting custom Principal Claim

texts:
I'm writing extension methods to shorten the code required to get custom Claims from an IPrincipal. I have two general forms for the bodies of these methods.

Form 1

public static long? GetFirmId(this IPrincipal principal)
{
    return ((ClaimsPrincipal) principal)?.FindFirst(nameof(User.FirmId)) == null
        ? default(long?)
        : long.TryParse(((ClaimsPrincipal) principal).FindFirst(nameof(User.FirmId)).Value, out var firmId)
            ? firmId
            : default(long?);
}

Form 2

public static long? GetFirmId(this IPrincipal principal)
{
    if (principal == null)
    {
        return default(long?);
    }

    var claim = ((ClaimsPrincipal) principal).FindFirst(nameof(User.FirmId));

    if (claim == null)
    {
        return default(long?);
    }

    if (long.TryParse(claim.Value, out var firmId))
    {
        return firmId;
    }

    return default(long?);
}

Please note that safely casting IPrincipal to ClaimsPrincipal is not necessary as IPrincipal in an ASP.NET Identity application is guaranteed to be a ClaimsPrincipal. I personally like form 1 better due to the brevity. The only thing I'm not super fond of is having to repeat ((ClaimsPrincipal) principal).FindFirst(nameof(User.FirmId)). However, I would say that form 2 is easier to understand for anyone not familiar with modern C# features (or ternary operators, which I have found to be surprisingly unheard of).

ReSharper suggests a middle ground (probably because it isn't sophisticated enough to transcribe form 2 to form 1):

public static long? GetFirmId(this IPrincipal principal)
{
    var claim = ((ClaimsPrincipal) principal)?.FindFirst(nameof(User.FirmId));

    if (claim == null)
    {
        return default(long?);
    }

    return long.TryParse(claim.Value, out var firmId) ? firmId : default(long?);
}

I'm looking for recommendations as to which form is "best," or an alternative suggestion. The project this is from has about ten of these methods for various custom claims of bool, bool?, char, char?, int, int?, long, long? and string. We are using custom claims to prevent needing a database trip (and additional code to make said database trip) to fetch commonly-used  user-specific data.


texts:
I am trying to count the rows of two tables generated by SQL connections in Excel VBA. My plan was to use ListObject.DataBodyRange.Rows.Count however, this errors when a table is empty, which one often is. I found it completely impossible to use On Error GoTo ... twice within one sub so I pulled out the counts as functions like this. I based my error handling pattern on this answer. Is this the best way to go?

Function CountCurrencyTrades() As Integer

    Dim sheetCurrencyTable As Worksheet
    Set sheetCurrencyTable = Worksheets("CurrencyTable")

    Dim tblCurrencyTrades As ListObject
    Set tblCurrencyTrades = sheetCurrencyTable.ListObjects("CurrencyQuery")
    On Error GoTo CurrencyTradesEmpty
    CountCurrencyTrades = tblCurrencyTrades.DataBodyRange.Rows.Count

CleanExit:

    Exit Function

CurrencyTradesEmpty:

    CountCurrencyTrades = 0
    Resume CleanExit

End Function


texts: Stylish underline when input is focused, modern browsers only

texts:
I've got a text input element which is decorated with an underline. The underline goes up half the height of the input on either side of it and turns blue when the input is focused. It's similar to how inputs look on Android devices.

Here's a JSFiddle and some accompanying code.

    <input placeholder="Search..." type="text" value="">

//  Start:normalize
*, *:before, *:after {
    box-sizing: border-box;
}

input:focus {
    outline: none
}
//  End:normalize

.input-underline-wrapper {
    display: inline-block;
    width: 100%;
}

input {
    width: calc(100% - 2px);
    margin-left: 1px;
    padding-bottom: 2px;
}

input[type=text] {
    border: 0;
    cursor: text;
}

.underline {
    background-color: #ebebeb;
    transition: color 0.3s, background 0.3s, border 0.3s, text-shadow 0.3s;
    z-index: 0;
    height: 5px;
    margin-top: -4px;
    width: 100%;
}

input:focus ~ .underline {
    background-color: #4EA6EA;
}

This all works well and good, but it feels a bit verbose. I'm wondering if I've missed something simple here. Is it possible to achieve the same effect using a white box-shadow which covers the upper-half of the input and omit using a wrapper and a second, underlining div? I only need to support the latest version of Google Chrome.


texts:
I'm interested in seeing different ways the proc can be expressed inside a method that takes args.

This method is meant to be a sort of FizzBuzz that will dynamically replace "Fizz" or "Buzz" as well as the traditional divisors 3 & 5.

def fizz_buzz_custom(string_1="Fizz", string_2="Buzz", num_1=3, num_2=5)
  proc do |length|
    index = length + 1
    val = if (index % 3 == 0 && index & 5 == 0)
      (string_1+string_2)
    elsif index % 3 == 0
      string_1
    elsif index % 5 == 0
      string_2
    else
      index
    end
  end
end

Here are some examples with test output:

fizz_buzz_custom[15]                         # returns 16
fizz_buzz_custom[44]                         # returns "FizzBuzz" (45 is divisible by 3 and 5)
fizz_buzz_custom('Hey', 'There')[25]         # returns 26
fizz_buzz_custom('Hey', 'There')[11]         # returns "Hey" (12 is divisible by 3)
fizz_buzz_custom("What's ", "up?", 3, 7)[80] # returns "What's " (81 is divisible by 3)


texts:
The aim is to duplicate and append each .grid__item into the .gallery element. The following code was my first instinct, and works fine, but can't help wonder if there is a more efficient way to write this. My concern is when the element count gets up to a high amount, that there will be some delay.

Generate Dummy Elements (PHP)

    <?php for ($i = 0; $i < 100; $i++) :
        $randH = rand(500, 1010);
        $randW = rand(500, 1010);
        $imgUrl = 'http://placehold.it/' . $randH . 'x' . $randW;
    ?>

            <img src="<?php echo $imgUrl; ?>">

<?php echo $imgUrl; ?>

    <?php endfor;?>

Copy Elements (JS)

let $gridItems = document.querySelectorAll('.grid__item'),
    $gallery = document.querySelector('.gallery');

let timeBefore = new Date().getTime();

for (let i = 0; i < $gridItems.length; i++) {
    $gallery.innerHTML += '
' + $gridItems[i].innerHTML + '
';
}

let timeAfter = new Date().getTime();

console.log(timeAfter - timeBefore)


texts: writeln() and format() with variadic templates

texts:
I wanted to get better acquainted with variadic templates, so I decide to try to implement a function like D's writeln(), just for fun.

void writeln()
{
    std::cout << "\n";
}

template<typename T, typename ...Args>
void writeln(T firstArg, Args... extraArgs)
{
    std::cout << firstArg;
    writeln(std::forward<Args>(extraArgs)...);
}

Usage example:

writeln("hello ", "world ", 42, "\t", 3.141592);
writeln(); // prints just a newline

Next, I implemented a format() function, which writes to a string instead of cout:

// Need this because there is no to_string for string in the std namespace.
std::string to_string(const std::string & s)
{
    return s;
}

std::string format()
{
    return "";
}

template<typename T, typename ...Args>
std::string format(T firstArg, Args... extraArgs)
{
    using namespace std;
    std::string s = to_string(firstArg);
    s += format(std::forward<Args>(extraArgs)...);
    return s;
}

// sample:
std::string s = format("hello ", "world ", 42, "\t", 3.141592);

It is uses std::to_string() for the native types. If I want to print custom types, then I can define a local to_string() and the overload resolution should find it.

My concerns are:

I haven't had many chances to use variadic templates so far, so I might be missing some caveat here. I was expecting it to be more complicated... Did I miss some corner case?
Is my use of std::forward appropriate?
Any other comments and suggestion are very welcome.


texts:
I implemented a stable marriage problem in Haskell few month ago. It's not optimized at all and I'd like to know how to make it better from performance and readability perspective.

data Sex = Male | Female deriving (Eq, Show)
data Virtue = Intelligence | Appearence | Kindness deriving (Eq, Show, Enum)

data Parameter = Parameter{
    virtue :: Virtue,
    value :: Int
} deriving (Eq, Show)

data Person = Person{
    name :: String,
    sex :: Sex,
    preferences :: [Virtue],
    parameters :: [Parameter],
    partner :: Maybe Person
} deriving (Eq, Show)

Results list of women sorted by preferences of one man by defaultRateFunction :: Person -> Person -> Int. In my implementation it depends on judges preferences and rated person parameters. I won't put it there for brevity. You can find full program in a link to Gist at the bottom of post. Imagine that function to be anything you want.

personalRating :: Person -> [Person] -> [Person]
personalRating x ys = sortBy (comparing (\y -> defaultRateFunction x y)) ys

Man makes an engagement proposal for the woman and if she don't have partner — she replies positively (True) and if she does, if new partner's rating > than the old one's — "returns" True and if it does not — False

proposal :: Person -> Person -> Bool
proposal male female
    | isNothing (partner female) = True
    | defaultRateFunction female male > defaultRateFunction female (fromJust $ partner female) = True
    | otherwise = False

Man makes a proposal for each woman in females untill he'll find the one who'll reply positively. Assumed that there are at least one of this type in the array

findTheBride :: Person -> [Person] -> Person
findTheBride male females
    | proposal male (head females) == True = head females
    | otherwise = findTheBride male (tail females)

The ugliest part is marrige algorhitm itself. As I call it recursively I have to clean person from array of corresponded sexes every time it finds partner and also check if woman has an ex-partner, and deal with thier "breakup" also.

marrige :: [Person] -> [Person] -> [Person]
marrige males females
        | sm == [] = females
        | isNothing ex = marrige
            (fsmWithNewPartner:(delete fsm males))
            (fsmPartnerWithFsm:(delete fsmPartner females))
        | otherwise = marrige
            (fsmWithNewPartner:((fromJust ex) {partner = Nothing}):(delete fsm $ delete (fromJust ex) males))
            (fsmPartnerWithFsm:(delete fsmPartner females))
    where
        sm = filter (\x -> partner x == Nothing) males -- Single males
        fsm = head sm -- Fist single male
        fsmPartner = findTheBride fsm (personalRating fsm females) -- Fist single male's partner
        ex = partner fsmPartner -- Partner's ex (Maybe)
        fsmWithNewPartner = fsm {partner = Just fsmPartner}
        fsmPartnerWithFsm = fsmPartner {partner = Just fsm}

Full version of program (where random Person data are generated) avialible on Gist.


texts: Extension methods for methods and properties that don't use non-public data

texts:
Generally speaking, I try and write my classes so they are highly cohesive.

Sometimes I have accessors (this problem isn't limited to accessors) which derive their value from non-public data only, which lowers cohesion. (http://www.ndepend.com/metrics.aspx#LCOM)

Take the following class example:

public class Person
{
    public DateTime Birth { get; set; }
    public DateTime? Death { get; set; }

    public double Age
    {
        get
        {
            return (Death ?? DateTime.Now - Birth).TotalDays / 365;
        }
    }
}

Ignoring the probable compile errors and lack of error checking, Age could easily be an extension method GetAge as it doesn't rely on non-public data.

The code would look as follows:

public class Person
{
    public DateTime Birth { get; set; }
    public DateTime? Death { get; set; }
}

public static class PersonExtensions
{
    public static double GetAge(this Person person)
    {
        return (person.Death ?? DateTime.Now - person.Birth).TotalDays / 365;
    }
}

What is a good approach to determine whether something should be an extension method or implemented in the class itself?

Some arguments against doing this that I find extension methods have lower visibility, you have to know the extension exists, while if it was a class property its existence would be obvious.

For languages that don't use extension methods (C++, php, etc.) the extension method could be written as a static method which accepts a Person as it's parameter.


texts: Unsafe collection which allows immutable access while also allowing push()

texts:
To get myself used to writing unsafe code, I wrote a collection which allows the user to keep immutable references to the elements of a vector while still being able to add new elements to it.

I would like to know if there is either a security problem with this code, an already implemented better alternative or some possible improvements in general (readability / performance).

pub struct UnsafeHolder<T> {
    items: Vec<Box<(T,String)>> // the vector contains Boxes, due to the fact that
                                // vectors can reallocate when adding elements
                                // which would end up creating dangling pointers
}

impl<T> UnsafeHolder<T> {
    pub fn new() -> Self {
        UnsafeHolder {
            items: vec![],
        }
    }

    // this method pretends to be immutable while actually adding
    // elements to the vector, this allows for continuous reference to
    // previous elements
    pub fn add_element(&self, element: T, key: String) {
        if !(self.items.iter().any( |i| i.1 == key)) {
            let mut items = unsafe {change_mut(&(self.items))};
            items.push(Box::new((element,key)));
        }
    }

    pub fn get_element(&self, key: &str) -> Option<&T> {
        if let Some(return_val) = self.items.iter().find(|i| i.1 == key) {
            Some(&return_val.0)
        }
        else {
            None
        }
    }

    pub fn clear(&mut self) {
        self.items = vec![];
    }
}

// this is used to change '&self' to '&mut self' to avoid the borrow checker
unsafe fn change_mut<T>(x: &T) -> &mut T {
    &mut *(x as *const T as *mut T)
}

This is the whole module, meaning that there should be no other ways than these 4 methods to interact with UnsafeHolder.

There is currently a problem due to the fact that items can be changed by multiple threads at once, resulting in an error.

Here is a link to the most recent version on playground.


texts:
I'm relatively new to python and for an assignment I had to write a program that fetches a webpage with BeautifulSoup, extract all Paragraphs from it, and extract all words ending with "ing", and in the end save it to a file with the format "Word" + tab + "wordcount" + "newline".
This is my code so far. Is there a more pythonic way to handle this?
Or generally ways to improve the code?
from bs4 import BeautifulSoup
import requests
import re

def main():
    site = "https://en.wikipedia.org/wiki/Data_science"
    r = requests.get(site).content
    soup = BeautifulSoup(r)
    ps = soup.findAll('p')
    fulltext = ''
    for p in ps:
        fulltext += p.get_text()
    words = match_words(fulltext)
    formated_words = sort_and_format(words)
    with open(r"Q1_Part1.txt","w") as file:
        file.write(formated_words)

def match_words(string):
    pattern = re.compile(r'\b(\w*ing)\b')
    words = re.findall(pattern, string.lower())
    matching_words = {}
    for word in words:
        if word in matching_words:
            matching_words[word] += 1
        else:
            matching_words[word] = 1
    return matching_words

def sort_and_format(dict):
    ordered_keys = sorted(dict, key=dict.get, reverse=True)
    output_string = ''
    for r in ordered_keys:
        output_string += f"{r}\t{dict[r]}\n"
    return output_string

main()


texts:
I worked on implementing a simple moving average function in Rust, that works on a collection of year/revenue tuples:

fn compute_moving_average(window: &Box<&[(u32, u32)]>) -> (u32, f32) {
    let window_size = window.len();

    let current_year = window
        .iter()
        .nth((window_size as f32/ 2.0).floor() as usize)
        .unwrap().0;

    let sum = window
        .iter()
        .fold(0, |a, x| a + x.1) as f32 / window_size as f32;

    (current_year, sum)
}

fn extract_moving_average_for_year(year: u32, moving_average: &Vec<(u32, f32)>) -> Option<f32> {
    let x = moving_average
        .iter()
        .find(|a| a.0 == year);

    match x {
        Some(a) => Some(a.1),
        None => None,
    }
}

fn merge_moving_average(a: (u32, u32), avg: Option<f32>) -> (u32, u32, Option<f32>) {
    (a.0, a.1, avg)
}

fn main() {
    let vec = vec![
        (2003, 4),
        (2004, 6),
        (2005, 5),
        (2006, 8),
        (2007, 9),
        (2008, 5),
        (2009, 4),
        (2010, 3),
        (2011, 7),
        (2012, 8),
    ];

    let moving_average = vec
        .windows(5)
        .map(|a| compute_moving_average(&Box::new(a)))
        .collect::<Vec<_>>();

    vec
        .iter()
        .map(|a| merge_moving_average(*a, extract_moving_average_for_year(a.0, &moving_average)))
        .inspect(|a| println!("{:?}", a))
        .collect::<Vec<_>>();
}

Output:

(2003, 4, None)
(2004, 6, None)
(2005, 5, Some(6.4))
(2006, 8, Some(6.6))
(2007, 9, Some(6.2))
(2008, 5, Some(5.8))
(2009, 4, Some(5.6))
(2010, 3, Some(5.4))
(2011, 7, None)
(2012, 8, None)


texts:
I'm trying to study network diffusion. I took the code form this. However, I would like to see if there's any potential to optimize the code to be faster and clearer. This is what I'm trying to do.

In a node, get all the successors and loop through to get the property in an edge to see if the probability is more than random number from (0,1). If yes, then that node should be activated, if no then move on. I use iGraph library for any graph manipulation.

def independent_cascade_igraph(G, seeds, steps=0):
    # init activation probabilities
    for e in G.es():
        if 'act_prob' not in e.attributes():
            e['act_prob'] = 0.1
        elif e['act_prob'] > 1:
            raise Exception("edge activation probability:", e['act_prob'], "cannot be larger than 1")

    # perform diffusion
    A = copy.deepcopy(seeds)  # prevent side effect
    if steps <= 0:
        # perform diffusion until no more nodes can be activated
        return _diffuse_all(G, A)
    # perform diffusion for at most "steps" rounds
    return _diffuse_k_rounds(G, A, steps)

def _diffuse_all(G, A):
    tried_edges = set()
    layer_i_nodes = [ ]
    layer_i_nodes.append([i for i in A])  # prevent side effect
    while True:
        len_old = len(A)
        (A, activated_nodes_of_this_round, cur_tried_edges) = _diffuse_one_round(G, A, tried_edges)
        layer_i_nodes.append(activated_nodes_of_this_round)
        tried_edges = tried_edges.union(cur_tried_edges)
        if len(A) == len_old:
            break
    return layer_i_nodes

def _diffuse_k_rounds(G, A, steps):
    tried_edges = set()
    layer_i_nodes = [ ]
    layer_i_nodes.append([i for i in A])
    while steps > 0 and len(A) < G.vcount():
        len_old = len(A)
        (A, activated_nodes_of_this_round, cur_tried_edges) = _diffuse_one_round(G, A, tried_edges)
        layer_i_nodes.append(activated_nodes_of_this_round)
        tried_edges = tried_edges.union(cur_tried_edges)
        if len(A) == len_old:
            break
        steps -= 1
    return layer_i_nodes

def _diffuse_one_round(G, A, tried_edges):
    activated_nodes_of_this_round = set()
    cur_tried_edges = set()
    for s in A:
        for nb in G.successors(s):
            if nb in A or (s, nb) in tried_edges or (s, nb) in cur_tried_edges:
                continue
            if _prop_success(G, s, nb):
                activated_nodes_of_this_round.add(nb)
            cur_tried_edges.add((s, nb))
    activated_nodes_of_this_round = list(activated_nodes_of_this_round)
    A.extend(activated_nodes_of_this_round)
    return A, activated_nodes_of_this_round, cur_tried_edges

def _prop_success(G, src, dest):
    '''
    act_prob = 0.1
    for e in G.es():
        if (src, dest) == e.tuple:
            act_prob = e['act_prob']
            break
    '''
    return random.random() <= 0.1

And this is how you test the code. The idea is to test how far your message can go in your network.

test_g = Graph([(1,2), (2,1), (1,3), (3,1), (2,3), (2,4), (3,4), (3,5), (4,5), (5,6), (6,5), (6,4), (6,2)], directed=True)
test_g.es['act_prob'] = [.5, .5, .2, .2, .3, .5, .1, .2, .2, .6, .6, .3, .4]

independent_cascade_igraph(test_g, [1])


texts: Box partitioning with arrays of boost::intervals

texts:
I need to write a function that takes a box in space, represented as an std::vector of boost::intervals, and split it into several smaller boxes.
First, for convenience, I made some definitions

#include <iostream>
#include <boost/numeric/interval.hpp>
#include <vector>

namespace bn = boost::numeric;
namespace bi = bn::interval_lib;

// Interval typedefs
using Interval = bn::interval<
      double,
      bi::policies<
          bi::save_state<bi::rounded_transc_std<double> >,
          bi::checking_base<double>
      >
  >;

template<typename T> using array = std::vector<T>;

Then, I shamelessly used code from this stackoverflow question that describes how to achieve a Cartesian product of a set (vector) of sets (vectors). I turned it into a Template (for generality purpose) like so:

template <class T>
class Combinator
{
public:
    Combinator(array<array<T>>& tsttors)
        : m_tsttors(tsttors)
    {
        m_combination.reserve(m_tsttors.size());
        for(auto& v : m_tsttors)
            m_combination.push_back(v.begin());
    }

    bool next() {
        // iterate through tsttors in reverse order
        for(int i = m_tsttors.size() - 1; i >= 0; --i) {
            array<T>& v = m_tsttors[i];
            typename array<T>::iterator& it = m_combination[i];

            if(++it != v.end())
                return true;
            it = v.begin();
        }
        return false;
    }

    array<typename array<T>::iterator> combination() const {
        return m_combination;
    }

private:
    array<array<T>>& m_tsttors; // reference to data
    array<typename array<T>::iterator> m_combination;
};

After that, I decided I would split each dimension of the box (which is not of fixed dimension) into some number n of subintervals and then take their cartesian product to get what I called a grid of boxes. I implemented this like:

array<array<Interval>> box_grid(const array<Interval> &box, const int &parts){
    array<array<Interval>> splits;
    for(const auto& components : box) { // iterating through all box-dimensions
        const double &length = width(components);
        const double &start = components.lower();
        array<Interval> split_oned; // split each dimension

        for(int i = 0; i< parts; i++){ // evenly into "parts" parts
            Interval ival {start+ i*length/parts, start + (i+1)*length/parts};
            split_oned.push_back(ival);
        }
        splits.push_back(split_oned); // collect each split dimension
    }

    // and take their cartesian product for the boxes
    Combinator<Interval> combinator(splits);
    array<array<Interval>> box_array;
    do
    {
        const array<array<Interval>::iterator> combination = combinator.combination();
        array<Interval> single_box;
        for(const auto& it : combination){
            single_box.push_back(*it);
        }
        box_array.push_back(single_box);
    } while(combinator.next());

    return box_array;
}

As I am new to C++ and not very adept at programming in general, I would love to have some feedback and suggestions on improvement. I will use this code for scientific purposes, so performance is crucial.
Thanks in advance.


texts:
I am trying to implement a basic circuit breaker design for my internal API calls. I would appreciate some criticism and feedback about my code. I am also planning to implement an interface off of the class once I am happy with it. As mentioned this circuit breaker design will be used for internal gRPC calls between my microservices. This was written in .NET Core 3.0.

I look forward to your feedback!

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Timers;

namespace CircuitBreaker
{
    public class CircuitBreaker
    {
        private Action _currentAction;

        private int _failureCount = 0;
        private readonly int _threshold = 0;
        private readonly System.Timers.Timer _timer;

        private CircuitState State { get; set; }

        public enum CircuitState
        {
            Closed,
            Open,
            HalfOpen
        }

        public CircuitBreaker(int threshold, int timeOut)
        {
            State = CircuitState.Closed;
            _threshold = threshold;
            _timer = new Timer(timeOut);
            _timer.Elapsed += TimerElapsed;
        }

        public void ExecuteAction(Action action)
        {
            _currentAction = action;
            try
            {
                action();
            }
            catch (Exception ex)
            {
                if (ex.InnerException == null)
                    throw;
                if (State == CircuitState.HalfOpen)
                    Trip();
                else if (_failureCount < _threshold)
                {
                    _failureCount++;
                    Invoke();
                }
                else if(_failureCount >= _threshold)
                    Trip();
            }

            if(State == CircuitState.HalfOpen)
                Reset();

            if (_failureCount > 0)
                _failureCount = 0;
        }

        public void Trip()
        {
            if (State != CircuitState.Open)
                ChangeState(CircuitState.Open);

            _timer.Start();
        }

        public void Reset()
        {
            ChangeState(CircuitState.Closed);

            _timer.Stop();
        }

        private void ChangeState(CircuitState callerCircuitState)
        {
            State = callerCircuitState;
        }

        private void Invoke()
        {
            ExecuteAction(_currentAction);
        }

        private void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (State == CircuitState.Open)
            {
                ChangeState(CircuitState.HalfOpen);

                _timer.Stop();

                Invoke();
            }
        }
    }
}


texts:
For my classes, I had to finish this task:

  Directory's disk usage list

  For indicated directory print a list of files and subdirectories in
  descending order according to their total disk usage. Disk usage of a
  simple file is equivalent to its size, for a subdirectory - a sum of
  the sizes of all files in its filesystem branch (subtree). Printed
  list format:

  <disk usage> <holder name> <type> <name> In the preceding print format
  is in case of a file not being a directory an owner, otherwise, the
  holder of a directory is the owner of the files having greatest total
  disk usage in it. <type> is a letter: d for a directory, - for a
  standard file, l - for a symbolic link etc.

  Below file disk usage list, print a summary:

  Total disk usage of the files in directory's subtree, the list of
  total disk usage of files in directory's subtree with respect to the
  owners (sums over owners). CAUTION: during recursive directories
  listing do not dereference symbolic links.

Here is my code:

#!/bin/bash

cd "$1"
ls -lA | awk 'NR != 1{
        name=$8
        for ( i=9; i<=NF; i++) name=name " " $i
        type=substr($1,1,1)
        if (type!="d")
        {
                print $5,$3,type,name
                sum_all+=$5
                usr_sum_all[$3]+=$5
        }
        else
        {
                sum=0;delete usr_sum;
                find_proc="find " name " -printf \"%s %u\\n\" 2>/dev/null"
                while ( find_proc | getline )
                {
                        sum+=$1;usr_sum[$2]+=$1;
                        sum_all+=$1;usr_sum_all[$2]+=$1;
                }
                close(find_proc)

                owner=""
                owner_sum=-1
                for ( iowner in usr_sum ) if ( usr_sum[iowner] > owner_sum ) {owner = iowner; owner_sum=usr_sum[iowner]}
                print sum " " owner " d " name
        }
}
END {
        print "Space taken: " sum_all
        for ( iowner in usr_sum_all ) print "\t user: " iowner " " usr_sum_all[iowner]
}' | sort -gr

Is it ok? Should I make any changes?


texts: Python exception handling class - Getting as much details printed

texts:
I'm trying to write a Exception Handling class in Python so that I can re-use.  If you have any ideas on how I can improve this to output more detailed information I would appreciate it:

class EHandle:
    @staticmethod
    def printit():
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
        frm = inspect.trace()[-1]
        mod = inspect.getmodule(frm[0])
        modname = mod.__name__ if mod else frm[1]
        print 'Thrown from', modname

And I call the class and method like below:

try:
    ggg()
    runafunction()
except:
    EHandle.printit()
    sys.exit()


texts:
I have implemented a program that produces a permuted index.
Actually it is this exercise:
https://stackoverflow.com/questions/4015016/what-is-a-permuted-index

Could anyone tell me if I did something wrong, and if it could be done better?

An input is for example:

The quick brown fox

And result:

      The quick     brown fox
The quick brown     fox
            The     quick brown fox
                    The quick brown fox

main.cpp

#include "myImplementation.cpp"

using namespace std;

vector<string> split(const string &s) {
    vector<string> ret;
    string::size_type i = 0;
    while (i != s.size()) {
        while (i != s.size() && isspace(s[i]))
            ++i;
        string::size_type j = i;
        while (j != s.size() && !isspace(s[j]))
            j++;
        if (i != j) {
            ret.push_back(s.substr(i, j - i));
            i = j;
        }
    }
    return ret;
}

int main() {
    string phrase;
    cout << "Please give me some phrase" << endl;
    getline(cin, phrase);

    vector <string> splitted = split(phrase);

    vector<string> permuted = makePermutedIndex(splitted);

    for (const auto i : permuted) {
        cout << i << endl;
    }

    return 0;
}

myImplementation.cpp

#include <vector>
#include <sstream>
#include <algorithm>

using namespace std;

vector<string> concatLeftAndRight(const vector<string> &left, const vector<string> &right,
                                  const string::size_type maxLengthOfLeftLine) {
    vector<string> ret;
    for (vector<string>::size_type i = 0; i != left.size(); ++i) {
        std::stringstream ss;
        ss << string(maxLengthOfLeftLine - left[i].size(), ' ')
        << left[i] << "   " << right[i];
        ret.push_back(ss.str());
    }
    return ret;
}

vector<string> makePermutedIndex(const vector<string> &splitted) {

    vector<string> sorted(splitted);

    std::sort(sorted.begin(), sorted.end());

    string::size_type maxLengthOfLeftLine = 0;

    vector<string> left;
    vector<string> right;

    for (auto index : sorted) {
        string rightLine, leftLine;
        bool indexEncountered = false;

        for (auto word : splitted) {
            if ((index != word) && !indexEncountered) {
                leftLine += word;
                leftLine += " ";
            }
            else {
                indexEncountered = true;
                rightLine += word;
                rightLine += " ";
            }
        }
        maxLengthOfLeftLine = max(maxLengthOfLeftLine, leftLine.size());
        left.push_back(leftLine);
        right.push_back(rightLine);
    }
    return concatLeftAndRight(left, right, maxLengthOfLeftLine);
}


texts:
I'm using this JS to sticky website footers at the bottom and I would like to know if is there anything to be optimised?

(function($, window, document){
    //Screen_height = Header_height + Main_Content_height + Footer_height + alltoplvlContainersMarginTop_Bottom + alltoplvlContainersPaddingTop_Bottom
    $.fn.sticky_footer = function(header,footer,content) {
        if(typeof header != undefined && typeof footer != undefined && typeof content != undefined) {
            var screen_height = $(window).height(); //Total height of the screen which is rendered within a browser window without having to scroll-down.

            var sum_of_top_bottom_props = function(id){ //Returns the sum of float values of padding-top,bottom margin-top,bottom, border-top,bottom-width.
                    if(typeof id != undefined){
                        var elem_id = id;
                        if(elem_id.length>0) { //If id exists in the page, fetch the sum of float values of the properties.
                           var prop_padding = parseFloat(elem_id.css('padding-top'))+parseFloat(elem_id.css('padding-bottom')),
                               prop_margin = parseFloat(elem_id.css('margin-top'))+parseFloat(elem_id.css('margin-bottom')),
                               prop_border = parseFloat(elem_id.css('border-top-width'))+parseFloat(elem_id.css('border-bottom-width'));
                           return prop_padding+prop_margin+prop_border;
                       } else{ //If id soesnot exist return 0;
                           console.error("The id: "+id+" doesn't exists! Pleas enter a valid id.");
                           return 0;
                       }
                   }};

            var header_height = (header.length>0) ? header.height():0, //Height of header
                footer_height = (footer.length>0) ? footer.height():0, //Height of footer
                header_props = sum_of_top_bottom_props(header), //Height of properties that contribute to header's height.
                footer_props = sum_of_top_bottom_props(footer), //Height of properties that contribute to footer's height.
                main_props = sum_of_top_bottom_props(content), //Height of properties that contribute to content's height.
                main_height = screen_height-(header_height + header_props + main_props + footer_props + footer_height);

            if(content!= undefined && content.length>0) { content.css('min-height',main_height); return true; }
            else return false;
        }
        else return false;
    }
})(jQuery, window, document);

GitHub: https://github.com/Elavarasanlee/sticky-footer.js


texts: Optimize Clock Update Code To Prevent Bottleneck Resulting In Time Lost

texts:
I use the following PHP Code to output the user's local time and the servers time (office time). $local_time and $remote_time are the corresponding UNIX timestamps:

<span class='icon-time' data-time='<?php echo $local_time; ?>' id='local-time'>
Local : <?php echo date('D, M j, h:ia', $local_time); ?>

<span class='icon-time text-<?php

echo (6 > date('N') && 9 <= date('G') && date('G') <= 17) // change class if open/closed
    ? 'success'
    : 'error';

?>' data-time='<?php echo $remote_time; ?>' id='remote-time'>
Office : <?php echo date('D, M j, h:ia', $remote_time); ?>

I then have the following JavaScript to update the clocks in real-time:

// update local/office clocks
window.setInterval(function () {

    lclock = $('#local-time');
    rclock = $('#remote-time');

    // convert to UNIX timestamp, add 60 secs since setInterval() will no start onload but after 60 secs
    ltime = new Date((lclock.data('time') * 1000) + 60000);
    rtime = new Date((rclock.data('time') * 1000) + 60000);

    lhours = ltime.getHours();
    rhours = rtime.getHours();

    // make 12hr time format and left-pad with zero
    lshours = ((0 === lhours) ? 12 : (lhours - ((12 < lhours) ? 12 : 0)));
    rshours = ((0 === rhours) ? 12 : (rhours - ((12 < rhours) ? 12 : 0)));

    lmins = ltime.getMinutes();
    rmins = rtime.getMinutes();

    rday = rtime.getDay();

    // determine if office is closed and change class
    ostatus = 'icon-time ' + ((6 > rday && 0 < rday && 9 <= rhours && 17 >= rhours)
        ? 'text-success'
        : 'text-error');

    // update clock, increment timestamp by 60 secs
    lclock.text('Local : ' + days[ltime.getDay()] + ', '
    + months[ltime.getMonth()] + ' ' + ltime.getDate() + ', '
    + ((10 > lshours) ? '0' + lshours : lshours) + ':'
    + ((10 > lmins) ? '0' + lmins : lmins)
    + ((12 <= lhours) ? 'pm' : 'am')).data().time += 60;

    // update clock, change CSS class, increment timestamp by 60 secs
    rclock.text('Office : ' + days[rtime.getDay()] + ', '
    + months[rtime.getMonth()] + ' ' + rtime.getDate() + ', '
    + ((10 > rshours) ? '0' + rshours : rshours) + ':'
    + ((10 > rmins) ? '0' + rmins : rmins)
    + ((12 <= rhours) ? 'pm' : 'am')).attr('class', ostatus).data().time += 60;

}, 60000);

It works great. However, after a few hours the time can end up being off by up to -7 minutes. I tried caching as many objects as I could and optimizing it the best I could to reduce the amount of variable value assignments, and used chaining as well, but can't see how else to speed it up to make it not lose time.

How can I optimize this further, in either my method, code being used, or is there something I am doing wrong?


texts:
A particular application may refer to a specific property in one of three languages in different contexts: in lowercase English, in uppercase English, and in Hebrew. To facilitate ease of converting one language to another, this monstrosity exists:

public string translatePersonType(string personType, string lang)
{

    switch (personType)
    {
        case "employee":
        case "EMPLOYEE":
        case "עובד":
            switch (lang)
            {
                case "eng":
                    return "employee";
                case "ENG":
                    return "EMPLOYEE";
                case "heb":
                    return "עובד";
            }
            break;

        case "contractor":
        case "CONTRACTOR":
        case "קבלן":
            switch (lang)
            {
                case "eng":
                    return "contractor";
                case "ENG":
                    return "CONTRACTOR";
                case "heb":
                    return "קבלן";
            }
            break;

        case "supplier":
        case "SUPPLIER":
        case "ספק":
            switch (lang)
            {
                case "eng":
                    return "supplier";
                case "ENG":
                    return "SUPPLIER";
                case "heb":
                    return "ספק";
            }
            break;

        case "customer":
        case "CUSTOMER":
        case "לקוח":
            switch (lang)
            {
                case "eng":
                    return "customer";
                case "ENG":
                    return "CUSTOMER";
                case "heb":
                    return "לקוח";
            }
            break;

        default:
            return "";

    }// end switch (personType)

    return "";

}// end translatePersonType

Can this be refactored to be more concise and maintainable? For reference, this is the database field behind the property:

personType SET('CUSTOMER','SUPPLIER','EMPLOYEE', 'CONTRACTOR') NOT NULL

Thanks.


texts:
I am currently changing the background colour of a sidebar each time a menu item is clicked using the following code:

$( 'a[href = "#masthead"' ).click(function() {
  $('#sidebar').css('background-color', '#3b6dac');
});

$( 'a[href = "#section2"' ).click(function() {
  $('#sidebar').css('background-color', '#23d4d7');
});

$( 'a[href = "#section3"' ).click(function() {
  $('#sidebar').css('background-color', '#59d078');
});

It does what I want, but I am relatively new to JavaScript and jQuery, and I imagine there is likely to be a better way...

jsFiddle


texts: Can not clearing a local java.util.Vector cause a memory leak?

texts:
In the code below, does not clearing or setting the local variable completed to null create the potential for a memory leak?

private Vector<Element> elements;

private void update()
{
    Vector<Element> completed = new Vector<Element>();
    for( Element e : elements )
    {
        if( e.isComplete() )
        {
           completed.add( e );
        } else {
           e.update();
        }
    }

    elements.removeAll( complete );
}

Should I add complete.clear() before the update() method exits?

The elements Vector is an instance variable on a class that is populated with Element objects elsewhere in the program.


texts: is my add method in binary search tree correct

texts:
I want to implement code for inserting a new Node in a binary search tree in java  so please check if my code is correct ,,, Here is my method :

public class BinarySearchTree {
      …

      public boolean add(int value) {
            if (root == null) {
                  root = new BSTNode(value);
                  return true;
            } else
                  return root.add(value);
      }
}
        public class BSTNode {
         …

      public boolean add(int value) {
            if (value == root.data)
                  return false;
            else if (value <root.data) {
                  if (root.left == null) {
                        root.left = new BSTNode(value);
                        return true;
                  } else
                        return root.left.add(value);
            } else if (value > root.data) {
                  if (root.right == null) {
                        root.right = new BSTNode(value);
                        return true;
                  } else
                        return root.right.add(value);
            }
            return false;
      }
}


texts:
I am practicing some simple Java coding problems in an attempt to learn while doing them. I would like to know if my code is redundant/is there an easier way to accomplish the same thing?

Question: Which Alien?

  "A person who witnessed the appearance of the alien has come forward
  to describe the alien's appearance."

  The program will determine which alien has arrived. The three alien
  species that it could be is:

  TroyMartian, has at least 3 antenna and at most 4 eyes
  VladSaturnian, has at most 6 antenna and at least 2 eyes
  GraemeMercurian, has at most 2 antenna and at most 3 eyes

  Sample session (with output shown in text, user input in italics)

    How many antennas?

    2

    How many eyes?

    3

    VladSaturnian

    GraemeMercurian

  If the description does not match any of the aliens, there is no
  output.

My code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Alien {

public static int antenna;
public static int eye;

public static void main(String args[]) {
    try (BufferedReader in = new BufferedReader(new InputStreamReader(
            System.in))) {

        System.out.println("How many antennas?");

        antenna = Integer.parseInt(in.readLine());

        System.out.println("How many eyes?");

        eye = Integer.parseInt(in.readLine());

        if(troy(antenna, eye)) {
            System.out.println("TroyMartian");
        }

        if(vlad(antenna, eye)) {
            System.out.println("VladSaturnian");
        }

        if(graeme(antenna, eye)) {
            System.out.println("GraemeMercurian");
        }

        return;

    }

    catch (IOException e) {
        System.err.println("Error");
    }

}

public static boolean troy(int antenna, int eye) {
    if ((antenna >= 3) && (eye <= 4)) {
        return true;
    } else {
        return false;
    }

}

public static boolean vlad(int antenna, int eye) {
    if ((antenna <= 6) && (eye >= 2)) {
        return true;
    } else {
        return false;
    }

}

public static boolean graeme(int antenna, int eye) {
    if ((antenna <= 2) && (eye <= 3)) {
        return true;
    } else {
        return false;
    }

}
}


texts: LeetCode 1638: Count Substrings That Differ by One Character

texts:
I'm posting a solution for LeetCode's "Count Substrings That Differ by One Character". If you'd like to review, please do. Thank you!
Problem

Given two strings s and t, find the number of ways you can choose a
non-empty substring of s and replace a single character by a different
character such that the resulting substring is a substring of t. In
other words, find the number of substrings in s that differ from some
substring in t by exactly one character.
For example, the underlined substrings in "computer" and "computation"
only differ by the 'e'/'a', so this is a valid way.
Return the number of substrings that satisfy the condition above.
A substring is a contiguous sequence of characters within a string.

Example 1:

Example 2:

Constraints:

1 <= s.length, t.length <= 100
s and t consist of lowercase English letters only.

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

static const size_t getCounts(
    const char *source,
    const char *target,
    size_t s_index,
    size_t t_index
) {
    size_t counter = 0;
    size_t prev = 0;
    size_t curr = 0;

    while (s_index < strlen(source) && t_index < strlen(target)) {
        ++curr;

        if (source[s_index] != target[t_index]) {
            prev = curr;
            curr = 0;
        }

        counter += prev;
        ++s_index;
        ++t_index;
    }

    return counter;
}

static const int countSubstrings(
    const char *source,
    const char *target
) {
    size_t counters = 0;

    for (size_t s_index = 0; s_index < strlen(source); ++s_index) {
        counters += getCounts(source, target, s_index, 0);
    }

    for (size_t t_index = 1; t_index < strlen(target); ++t_index) {
        counters += getCounts(source, target, 0, t_index);
    }

    return counters;
}

int main() {
    printf ("%i \n", countSubstrings("aba", "baba"));
    printf ("%i \n", countSubstrings("ab", "bb"));
    printf ("%i \n", countSubstrings("a", "a"));
    printf ("%i \n", countSubstrings("abe", "bbc"));
    printf ("%i \n", countSubstrings("abeaskdfjpoirgfjifjwkdafjaksld",
                                     "fqowuerflqfdjcasdjkvlfkjqheofkjsdjfasldkf"));
    return 0;
}

Outputs:
6
3
0
10
1314


texts:
Recently I was given homework to make a hangman game, where I wrote the below.
How can I refactor this to use classes?

import secrets

def guess_the_word():
    tries_left = 9
    output = ["_"] * len(secret_word)

    print(str(' '.join([letter for letter in output])).strip())

    while tries_left >= 0 and not secret_word == str(''.join([letter for letter in output])):
        # print tries left
        print("\nYou have {} tries left".format(tries_left))
        # display the _ which is length of the secret_word and fill in _ as and when the user
        # types correct word

        guessed_letter = input("Guess a letter from secret word:")

        if guessed_letter in secret_word:
            print("You guessed correct")
            for i, x in enumerate(secret_word):
                if x is guessed_letter:
                    output[i] = guessed_letter
        else:
            tries_left -= 1
            print("You guessed incorrect")

        print(str(' '.join([letter for letter in output])).strip())

print("\nWelcome to Hangman Game!\n")
# open words.txt file to read words
with open("words.txt") as words_file:
    words_list = words_file.read().split()
# choose a random word from words_list
secret_word = secrets.choice(words_list)
guess_the_word()


texts: Need fast csv parser for Python to parse 80GB csv file

texts:
I am looking for the fastest way to parse an 80GB csv file with 300 columns in Python.

The csv file does not have backquote commas, e.g  a,"blah,blah,blah",c

I have tried Python's built-in csv module which gives me ~50MB/s speed.

with open(file_name) as csvfile:
    reader = csv.reader(csvfile,delimiter=',')
    for row in reader:
        pass

With plain line.split() I get ~55MB/s:

with open(file_name) as csvfile:
    for line in csvfile:
        row = line.split(',')

Without parsing, I get ~400MB/s:

with open(file_name) as csvfile:
    for line in csvfile:
        pass

Using cperf I see that most of time time is used for split() or csv.reader() or re.split(), which I have also used.

Can I make this faster? If a plain read from disk is 400MB/s, I would like to get ~200MB/s while parsing the csv file if possible.


texts: Symlinking shared libraries from a platform-specific directory

texts:
We have a setup script for setting up a development environment, and setting up the image libraries is getting a bit messy:

# this is to get PNG and JPEG support working in PIL on Ubuntu
if [ -d /usr/lib/x86_64-linux-gnu ] ; then # 64 bit ubuntu
    sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib/
    sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/
    sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib/
fi

if [ -d /usr/lib/i386-linux-gnu/ ] ; then # 32 bit ubuntu
    sudo ln -s /usr/lib/i386-linux-gnu/libfreetype.so /usr/lib/
    sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/
    sudo ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib/
fi

if [ -d /usr/lib64/ ] ; then # Redhat
    sudo ln -s /usr/lib64/libjpeg.so /usr/lib/
    sudo ln -s /usr/lib64/libz.so /usr/lib/
    sudo ln -s /usr/lib64/libfreetype.so /usr/lib/
fi


texts: Analyze huge set of sentences for word presence

texts:
I have a huge file (1Gb) with English sentences and I need to filter only those containing the Alice word.
Actual tests could be more complex, e.g. matching a verb by its wordforms (go, goes, gone, went, going).
To solve the task I have designed a method, which feeds English word as it is ready to a consumer and if test returns back positive the method returns immediately.
I have improved performance twice in comparison with storing words in a list first and matching them afterwards. Still I have the following benchmarks:

read:  1.6s / 100MB;
process: 1.5s / 100MB.

Could this code be improved further:
import java.util.function.Function;

public class ExtractEnglishWordsAndTest {
    public static boolean extractEnglishWordsAndTest(String text, Function<String, Boolean> consumer) {
        if (text == null || text.isEmpty()) {
            return false;
        }

        char[] buf = new char[text.length()];
        int bufIndex = -1;

        boolean isEnglishPiece = isEnglishLetterOrHyphen(text.charAt(0));

        for (char ch : text.toCharArray()) {
            boolean isEnglishLetter = isEnglishLetterOrHyphen(ch);

            if (isEnglishPiece && !isEnglishLetter || !isEnglishPiece && isEnglishLetter) {
                if (isEnglishPiece) {
                    if (consumer.apply(new String(buf, 0, bufIndex + 1))) {
                        return true;
                    }
                }

                isEnglishPiece = !isEnglishPiece;

                bufIndex = -1;
            }

            bufIndex++;
            buf[bufIndex] = ch;
        }

        if (isEnglishPiece) {
            if (consumer.apply(new String(buf, 0, bufIndex + 1))) {
                return true;
            }
        }

        return false;
    }

    public static boolean isEnglishLetterOrHyphen(char ch) {
        return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '-';
    }

    public static void main(String[] args) {
        // could be used for just splitting
        ExtractEnglishWordsAndTest.extractEnglishWordsAndTest("Some key-phrases that may hint to you " +
                "that the question is better suited for Code-Review " +
                "are like the following:", (word) -> {
            System.out.print(word + " ");
            return false;
        });

        System.out.println();

        System.out.println("test: " + ExtractEnglishWordsAndTest.extractEnglishWordsAndTest("In another moment down went Alice after it, " +
                "never once considering how in the world " +
                "she was to get out again.", (word) -> word.equals("Alice")));

        System.out.println("test: " + ExtractEnglishWordsAndTest.extractEnglishWordsAndTest("Presently she began again.",
                (word) -> word.equals("Alice")));
    }
}

Output:

Some key-phrases that may hint to you that the question is better
suited for Code-Review are like the following
test: true
test: false


texts:
I have an Android app that shows some fragments, but I'm repeating lots of code.

MainActivity.java

public class MainActivity extends FragmentActivity {
    MyPagerAdapter pageAdapter;
    ViewPager pager;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
        pager = (ViewPager)findViewById(R.id.myViewPager);
        pager.setAdapter(pageAdapter);
    }

    public void homeButtonPressed(View v) {
        // go home
        pager.setCurrentItem(0);
    }
}

MyPagerAdapter.java

public class MyPagerAdapter extends FragmentPagerAdapter {
    public List<Fragment> fragments;

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
        this.fragments = new ArrayList<Fragment>();
        fragments.add(new Page1());
        fragments.add(new Page2());
        fragments.add(new Page3());
        fragments.add(new Page4());
        fragments.add(new Page5());
        fragments.add(new Page6());
        fragments.add(new Page7());
        fragments.add(new Page8());
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}

I'm loading in the page adapter the fragments to show, but they are all the same with a few differences.

Layout for page 1

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F7F4E7">
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/page_1" />
</RelativeLayout>

Page1.java

public class Page1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.page1_layout, container, false);
        return view;
    }
}

The only difference on each page is the

  android:src="@drawable/page_1"

and showing a button or hiding it for certain fragments.

I come from Objective-C, and I understand that I need to abstract this, as I have created all of this classes PageN, that are the same! ,but I don't yet understand how to load them on the pagerAdapter .


texts:
There can only be better ways to do this?

create strings for  today's directory
strDate is yesterday's date in format ddmmyyyy (e.g. 08122016)
DateStr is yesterday's date in format yymmdd (e.g 161208)

strDate = '{d.year}{d.month:02}{d.day:02}'.format(d=datetime.datetime.now()- timedelta(1))
strDate = str(strDate)

day = calendar.day_name[datetime.datetime.today().weekday()-1]
day = day[:3]

week  = datetime.datetime.today().isocalendar()[1]

fpath = strDate + "_" + str(day)  + "_" +  str(week) + ".zip"

DateStr = '{d.day:02}{d.month:02}{d.year}'.format(d=datetime.datetime.now()- timedelta(1))
DateStr = str(DateStr[:4]+DateStr[6:])


texts:
I'm new to Rhino mock and I would like to know if the test I did is not fake testing, as I've read a lot about it. Are there any improvements that need to be done?

[Test]
public void GenerateDateTable_Returns_DataTableOfGroup()
{
    //Arrange
    var groupStub = MockRepository.GenerateStub<Group>();
    var groupEnumerable = new[] { groupStub };
    var mockgroup = MockRepository.GenerateMock<FillTableRow<Group>>();
    mockgroup.Replay();
    //Act
    mockgroup.GenerateDateTable(groupEnumerable);

    //Assert
    Assert.IsTrue(mockgroup.DataTableBatch.Columns.Count == 3);
}

public class FillTableRow<T>
{
    public DataTable DataTableBatch { get; set; }

    public DataTable GenerateDateTable(IEnumerable<T> enumerable)
    {
        IDbObjectFactory<T> tableFactory = new TableFactory<T>();
        DataTableBatch = (DataTable)tableFactory.GetDbObject();

        foreach (var row in enumerable)
        {
            AddRow(row);
        }
        return DataTableBatch;
    }
}


texts:
I am reading a book on DSA, and the author explains how to generate the permutation of strings using recursion.  I want to know if there are better ways of doing the same, unless this is the best solution.  Also, could someone help me understand the time-complexity of this algorithm?  Recursion is something I use very rarely but am trying to learn about now.

public class Anagrams {
private char[] chArray;
private int size;
private static int count;

public Anagrams(String anagramString, int size) {
    if (size <= 0) {
        System.out.println("Please enter a valid String");
    }
    chArray = anagramString.toCharArray();
    this.size = size;

}

public static void main(String args[]) {
    String str = "dogs";
    Anagrams anagramGenerator = new Anagrams(str, str.length());
    anagramGenerator.generateAnagrams(str.length());

}

public void generateAnagrams(int newSize) {
    if (newSize == 1)
        return;

    for (int i = 0; i < newSize; i++) {
        generateAnagrams(newSize - 1);
        if (newSize == 2)
            displayWord();
        rotate(newSize);
    }

}

private void rotate(int newSize) {
    // TODO Auto-generated method stub
    int position = size - newSize;
    char tempCh = chArray[position];
    int i;
    for (i = position + 1; i < size; i++) {
        chArray[i - 1] = chArray[i];
    }
    chArray[i - 1] = tempCh;

}

private void displayWord() {
    // TODO Auto-generated method stub
    String word = "";
    count++;
    for (int i = 0; i < chArray.length; i++) {
        word += chArray[i];
    }
    System.out.println(count + ")" + word);
}
}


texts:
This is my first project using Python. I made a simple password generator that checks user input. How can I improve it?
import random
def password_generator():
    password = []
    letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
               "v", "w", "x", "y", "z"]
    password_length = 0
    password_numbers = []
    password_letters = []
    # Input the length of the password
    while True:
        password_length_input = input("Choose the length of your password with numbers between 6 and 15:\n")
        if not password_length_input.isnumeric():
            print(f"{password_length_input} is not a number, try again:")
            continue
        else:
            password_length = int(password_length_input)
            print(f"Password length: {password_length}")
        if 6 <= password_length <= 15:
            break
        else:
            print("The password must be between 6 and 15 characters, try again:")
            continue
    # Input the amount of numbers in password
    while True:
        password_numbers_input = \
            input(f"Choose the amount of numbers you want in your password, max {password_length}\n")
        if not password_numbers_input.isnumeric():
            print(f"{password_numbers_input} is not a number try again")
            continue
        elif int(password_numbers_input) > password_length:
            password_numbers = 0
            print(f"The value is too high, choose maximum {password_length} numbers")
            continue
        else:
            password_numbers = int(password_numbers_input)
            print(f"Password numbers: {password_numbers}")
            for number in range(0,password_numbers):
                password.append(random.randrange(0,9))
            break
    # Check for numbers and letters in password
    while True:
        if password_numbers == password_length:
            print(f"The password will be only {password_numbers} numbers, no letters.")
            break
        else:
            password_letters = password_length - password_numbers
            print(f"""Your password will be {password_length} characters with {password_numbers} numbers and {password_letters} letters.""")
            for letter in range(0,password_letters):
                password.append(random.choice(letters))
            break
    random.shuffle(password)
    password_string = ''.join([str(item) for item in password])
    print(f"Your password is:\n{password_string}")

password_generator()

Usage example:
Choose the length of your password with numbers between 6 and 15:
Password length: 8
Choose the amount of numbers you want in your password, max 8
Password numbers: 2
Your password will be 8 characters with 2 numbers and 6 letters.
Your password is:
pzc11bmf


texts: Sanitize file or folder names to work with a legacy system

texts:
I'm in the unfortunate position to where I have to create files and folders programmatically that have to work with a legacy system. In this process, the file and folder names have to be heavily sanitized.

The POST requests that create the files and folders are sent from the client in javascript, while the actual creation happens on a server. For this, I wrote a function used to display to users what their input folder or file names will look like and to sanitize their input to work with the legacy system.

I've let this run over quite a few test cases including irregular file names that broke the legacy system prior and it seems to work fine. I'm curious about what could be improved though, especially with respect to readability and extensibility.

/**
 * @description sanitizes a folder or file name to work with #name of legacy system
 * @author me
 * @param {string} object_name
 * @param {string} mode     "file" / "folder"
 */

function sanitizeFolderOrFile(object_name, mode) {

    if (mode !== 'file' && mode !== 'folder') {
        return false;
    }

    let suffix = '';
    let retvar = '';

    if (mode === 'file') {
        suffix = object_name.split('.').pop();
        retvar = object_name.replace(new RegExp('(\.' + suffix + ')', 'g'), '');
    } else if (mode === 'folder') {
        retvar = object_name;
    }

    // values to replace
    const replace_values = [{
        value: '+\\&',
        replacement: 'u'
    }, {
        value: 'äÄ',
        replacement: 'ae'
    }, {
        value: 'öÖ',
        replacement: 'oe'
    }, {
        value: 'üÜ',
        replacement: 'ue'
    }, {
        value: 'ß',
        replacement: 'ss'
    }, {
        value: ' \\`\\´\\?\\(\\)\\[\\]\\{\\}\\/\\\\$\\§\\"\\\'\\!\\=\\-\\.\\,\\;\\:<>\\|\\^\\°\\*\\+\\~\\%',
        replacement: '_'
    }];

    replace_values.forEach(function(element) {
        retvar = retvar.replace(new RegExp('([' + element.value + '])', 'g'), element.replacement);
    });

    retvar = retvar.toLowerCase();

    if (mode === 'file') {
        retvar += '.' + suffix;
    }

    return retvar;
}


texts: Clearing duplicates from an Excel 2007 sheet

texts:
This is the original code I had for removing duplicates from a sheet:

Sub Remove_Duplicates()
'
Application.ScreenUpdating = False

    ActiveSheet.Range("$A$1:$Z$2000").RemoveDuplicates Columns:=Array(5, 10, 11, 12, 13, 14, 15, 16), Header:=xlYes

Range("C" & Rows.Count).End(xlUp).Offset(1).Select

Application.ScreenUpdating = True

Call Hide_Columns_Swivel

End Sub

I added a section to this code (see below) that clears contents of fake empty cells. But now the code takes up to 15 seconds to run. It works as it is suppose to, just really slowly.

Sub Remove_Duplicates()
'
Application.ScreenUpdating = False

Dim usedrng As Range

    ActiveSheet.Range("$A$1:$Z$2000").RemoveDuplicates Columns:=Array(5, 10, 11, 12, 13, 14, 15, 16), Header:=xlYes

    For Each usedrng In ActiveSheet.UsedRange
        If usedrng.Value = "" Then
            usedrng.ClearContents
        End If
    Next

Range("C" & Rows.Count).End(xlUp).Offset(1).Select

Application.ScreenUpdating = True

Call Hide_Columns_Swivel

End Sub

I need help making this more efficient as I do not know enough about VBA to do that. All assistance is greatly appreciated.


texts: Should I re-throw exceptions within a method, or is there a better way to handle it?

texts:
When handling errors in C#, is it acceptable/appropriate to re-throw exceptions that are caught in a try/catch?

My scenario is that I am making an HTTP request and then checking the content of the response for a specific key (access_token). If that key is missing, I throw an error.

However, as all of the code within the method is in a try/catch block (just in case HTTP requests go awry), the exception that I throw is being caught. The solution that I've settled on for now is to re-throw the error that is caught, to ensure that I don't lose additional detail that was included with the custom exception. You can see a full example of my code at the bottom of this question.

I've found a number of other possibilities though, and I'd be interested to know what the C# community thinks is the best way to handle such scenarios (even if it turns out that none of them are appropriate!). There are of course other questions/resources that are similar to this, but some of the information is ambiguous and being a novice at C#, I'd like get a bit of extra context with a real-life example.

Possibilities

A separate catch block to re-throw the known error (see example 1).
Check for the type of exception in a single catch block (see example 2).
Return an exception should 'access_token' not be present (as opposed to throwing it).
Don't wrap all the code in a try\catch.

Example 1

catch (WhException ex)
{
    // Capture and rethrow a 'WhException', ensurig that the detail is not lost.
    throw ex;
}
catch (Exception ex)
{
    // Capture any generic exception and retrhow it as a 'WhException'.
    throw new WhException("An error occurred whilst attempting to generate a bearer access token.", ex.Message, ex);
}

Example 2

catch (Exception ex)
{
    if (ex is WhException)
        // Capture and rethrow a 'WhException', ensurig that the detail is not lost.
        throw ex;
    else
        // Capture any generic exception and retrhow it as a 'WhException'.
        throw new WhException("An error occurred whilst attempting to generate a bearer access token.", ex.Message, ex);
}

Full working example

public static async Task<string> GetAzureAccessTokenAsync(this HttpClient http, WhConfigRaw config)
{
    try
    {
        Dictionary<string, string> form = new Dictionary<string, string>()
        {
            { "grant_type", "client_credentials" },
            { "client_id", config.ServicePrincipalId },
            { "client_secret", config.ServicePrincipalKey },
            { "resource", AppSettings.Get("AzureCoreUri") }
        };
        FormUrlEncodedContent requestContent = new FormUrlEncodedContent(form);
        string uri = string.Format(AppSettings.Get("ClientCredentialsUri"), config.TenantId);

        // Query the Azure management API to get client credentials.
        HttpResponseMessage response = await http.PostAsync(uri, requestContent);

        // Read the content of the response for the Azure management API.
        JObject content = await response.Content.ReadAsJsonAsync<JObject>();

        // Check whether or not the content of the response contains and 'access_token'.
        if (!content.ContainsKey("access_token"))
        {
            throw new WhException("An error occurred whilst attempting to generate a bearer access token.", content);
        }

        return content["access_token"].ToString();
    }
    catch (WhException ex)
    {
        // Capture and rethrow a 'WhException', ensurig that the detail is not lost.
        throw ex;
    }
    catch (Exception ex)
    {
        // Capture any generic exception and retrhow it as a 'WhException'.
        throw new WhException("An error occurred whilst attempting to generate a bearer access token.", ex.Message, ex);
    }
}


texts: Querying multiple related records in Rails

texts:
I have an Account, User and Group model. All User and Group records belong to an Account, so it is possible for both users and groups to be related to various accounts.

Basically, I have some really hacky, pieced together SQL queries that lookup all Account records related to a given User or Group record through various
associations.

Even though it's fast and only requires a single query for everything to work, I really hate the way it's written.

I was wondering if there is any way I could do this more programatically with something like arel, or if there was a better approach. I also have some security concerns about the code.

class Account < ActiveRecord::Base

  belongs_to :accountable, touch: true, polymorphic: true

  CLAUSE_FOR_RELATED = '"accounts"."accountable_type" = \'%s\' AND "accounts"."accountable_id" IN (%s)'.freeze

  def self.related_to_user(user)
    groups = user.groups.select('"groups".id')
    friends = user.following_friendships.select('"friendships".following_id')

    queries = []
    queries.push ['Group', groups.to_sql]
    queries.push ['User', friends.to_sql]
    queries.push ['User', user.id]

    self.related_to(queries)
  end

  def self.related_to_group(group)
    queries = [
      ['User', group.members.select('"users".id').to_sql]
    ]

    self.related_to(queries)
  end

  def self.related_to(queries)
    clauses = queries.map do |clause|
      sprintf(CLAUSE_FOR_RELATED, clause[0], clause[1])
    end

    self.where(clauses.join(" OR "))
  end
end


texts: Should I call this extension method Remove or RemoveMany?

texts:
I know this is extremely trivial, but would you call the extension method below Remove or RemoveMany? Please provide justification.

public static void Remove<TEntity>(this DbSet<TEntity> set, IEnumerable<TEntity> entities)
    where TEntity : class
{
    foreach (var entity in entities)
        set.Remove(entity);
}

-- or --

public static void RemoveMany<TEntity>(...) { ... }


texts: Handling Excel column letter index as struct

texts:
I've designed a little struct that should help me deal with Excel columns in terms when the letter index is used. The idea is to use the struct implicitly most of the time for iterations over Excel columns etc.

The struct works in the cases i've intended it to. However, on the one hand, I'm not sure if it isn't a little over the top for a struct and i should rather use a class. On the other hand I was a little surprised why the struct did actually work implicitly when combining it with an integer and assigning it to a string value like this

int rowIndex = 1;
ExcelColumn column = 1;
string cellId = column + rowIndex.ToString();

results in the string being assigned to

  A1

So my questions are:

Why is that the case?
Is the struct properly designed for its purpose?

Below is the code for the struct:

public struct ExcelColumn
{
    #region Constants
    private const int MAX_COLUMN_COUNT = 16384;
    #endregion

    #region Fields
    private readonly int _value;
    #endregion

    #region Constructors
    public ExcelColumn(int columnIndex)
    {
        if (columnIndex < 1)
            throw new IndexOutOfRangeException("Index below 1 not allowed.");
        if (columnIndex > MAX_COLUMN_COUNT)
            throw new OverflowException("Max Column number exceeded");

        _value = columnIndex;
    }
    #endregion

    #region Methods
    private string GetValue()
    {
        string value = "";
        int val = _value - 1;
        do
        {
            value = Convert.ToChar(65 + val % 26) + value;
            val = (val - val % 26) / 26 - 1;
        }
        while (val >= 0);
        return value;
    }
    public override string ToString()
    {
        return GetValue();
    }
    #endregion

    #region Operators
    public static ExcelColumn operator +(ExcelColumn x, ExcelColumn y)
    {
        return new ExcelColumn(x._value + y._value);
    }
    public static ExcelColumn operator +(ExcelColumn x, int y)
    {
        return new ExcelColumn(x._value + y);
    }
    public static ExcelColumn operator +(int x, ExcelColumn y)
    {
        return new ExcelColumn(x + y._value);
    }
    public static ExcelColumn operator ++(ExcelColumn x)
    {
        return new ExcelColumn(x._value + 1);
    }

    public static ExcelColumn operator -(ExcelColumn x, ExcelColumn y)
    {
        return new ExcelColumn(x._value - y._value);
    }
    public static ExcelColumn operator -(ExcelColumn x, int y)
    {
        return new ExcelColumn(x._value - y);
    }
    public static ExcelColumn operator -(int x, ExcelColumn y)
    {
        return new ExcelColumn(x - y._value);
    }
    public static ExcelColumn operator --(ExcelColumn x)
    {
        return new ExcelColumn(x._value - 1);
    }

    public static implicit operator ExcelColumn(int x)
    {
        return new ExcelColumn(x);
    }
    public static explicit operator int(ExcelColumn x)
    {
        return x._value;
    }
    #endregion

    #region Properties
    public string Value { get { return GetValue(); } }
    public int Index { get { return _value; } }
    #endregion
}


texts:
Earlier this year, before I learnt about Code Review Stack Exchange, I gave this answer in response to a question about how to combine ASP.NET, jQuery, and JSON:

I keep thinking that there must be a better way to handle the JSON than just using escaped string literals, but I'd like to know for sure.

urlToHandler = 'handler.ashx';
jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }';
$.ajax({
                url: urlToHandler,
                data: jsonData,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json',
                success: function(data) {
                    setAutocompleteData(data.responseDateTime);
                },
                error: function(data, status, jqXHR) {
                    alert('There was an error.');
                }
            }); // end $.ajax

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";

        DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
        string stringParam = (string)Request.Form["stringParam"];

        // Your logic here

        string json = "{ \"responseDateTime\": \"hello hello there!\" }";
        context.Response.Write(json);
    }


texts:
I am trying to write an SQL Procedure that will calculate the Last Price paid for a certain Part.

DECLARE @ItemId int;

SET @ItemId = 1;

SELECT
SD.Price
FROM SalesOrderHeaders AS SH
INNER JOIN SalesOrderDetails AS SD
ON SH.Id = SD.HeaderId
WHERE (SD.LineItemId = @ItemId)
AND (SH.OrderDate = (SELECT
    MAX(SH.OrderDate) AS Expr1
FROM SalesOrderHeaders AS SH
INNER JOIN SalesOrderDetails AS SD
    ON SH.Id = SD.HeaderId
WHERE (SD.LineItemId = @ItemId))
)

This does produce the results I wanted but, I am doing everything twice. Would someone point me in a better direction?


texts:
class User {

    protected $DBH;
    protected $STH;

    public function __construct($DBH) {
        $this->DBH = $DBH;
    }

    public function logged_in() {
        if (isset($_SESSION['userid']) && isset($_SESSION['hash'])) {
            $hash = sha1($_SESSION['userid'] . $_SERVER['HTTP_USER_AGENT']);

            if ($_SESSION['hash'] == $hash)
                return true;
        }
        return false;
    }

    public function login($username, $password) {
        $password = sha1($password);
        $this->STH = $this->DBH->prepare("SELECT id, banned, activated FROM users WHERE username = ? AND password = ?");
        $this->STH->setFetchMode(PDO::FETCH_OBJ);
        $this->STH->execute(array($username, $password));

        if ($this->STH->rowCount() > 0)
            return $this->STH->fetch();
    }

    public function create_account($username, $password, $email) {
        $password = sha1($password);
        $activation_key = md5($username . $email);

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

        try {
            $this->STH = $this->DBH->prepare("INSERT INTO users(username, password, email, activation_key, created) VALUES(:username, :password, :email, :activation_key, :created)");
            $this->STH->bindParam(':username', $username);
            $this->STH->bindParam(':password', $password);
            $this->STH->bindParam(':email', $email);
            $this->STH->bindParam(':activation_key', $activation_key);
            $this->STH->bindParam(':created', time());
            $this->STH->execute();
        } catch (PDOException $e) {
            //$e->getMessage();
            return false;
        }

        return true;
    }

    public function check_username($username) {
        $this->STH = $this->DBH->prepare("SELECT username FROM users WHERE username = ?");
        $this->STH->execute(array($username));

        if ($this->STH->rowCount() > 0)
            return false;

        return true;
    }

    public function check_email($email) {
        $this->STH = $this->DBH->prepare("SELECT email FROM users WHERE email = ?");
        $this->STH->execute(array($email));

        if ($this->STH->rowCount() > 0)
            return false;

        return true;
    }

    public function activate($key) {
        $this->STH = $this->DBH->prepare("SELECT activation_key FROM users WHERE activation_key = ?");
        $this->STH->execute(array($key));

        if ($this->STH->rowCount() > 0) {
            $this->STH = $this->DBH->prepare("UPDATE users SET activated = 1, activation_key = null WHERE activation_key = ?");
            $this->STH->execute(array($key));

            return true;
        }

        return false;
    }
}

Am I doing this right?
What should I change? Add, etc. Should I use more try { } catch blocks/etc. Give me some tips on how to improve the code. (Better performance, etc).


texts:
First line will contain two integers N and M separated by a single space. Then the next M lines will contain three integers a, b and k separated by a single space. N is the length of the sequence. M is the number of operations performed on that sequence. a is the starting index from a sequence and b is ending index from a sequence. I have to add k to all elements in between a and b. (I have to do this M times on N length sequence)

Here is my code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Solution {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        int m=sc.nextInt();
        List l= new ArrayList(Collections.nCopies(n, 0));
        //System.out.println(l);

        for(int i=1;i<=m;i++){
            int a=sc.nextInt();
            int b=sc.nextInt();
            int k=sc.nextInt();
            for(int j=0;j<n;j++){
                //if((a-j)<=b){
                if(j+1>=a && j+1<=b){
                    int ab= (int) l.get(j);
                    int sum=ab+k;
                    l.set(j,sum);
                }
            }
        }
        int total=0;
        total=(int) l.get(0);
        for(int i=0;i<n;i++){
            int num=(int) l.get(i);
            if(num>total){
                total=num;
            }
        }
        System.out.println(total);
    }
}

Question: My code fails due to time out, and may be due to some other issues which i'm not aware of..please help to solve this or optimize my code.
It works for small inputs (100 lines)..


texts:
Funny thing, the following test works:

    [TestMethod]
    public void Iterate_Once()
    {
        var x = new[] { 1, 2, 3, 4, 5, 6 }.ToIterable();
        CollectionAssert.AreEqual(new[] { 1, 2 }, x.Take(2).ToArray());
        CollectionAssert.AreEqual(new[] { 3, 4, 5 }, x.Take(3).ToArray());
    }

Where:

static class Iterable
{
    public static IEnumerable<T> ToIterable<T>(this IEnumerable<T> source)
    {
        var it = source.ToList().GetEnumerator();
        return once();

        IEnumerable<T> once()
        {
            while (it.MoveNext())
                yield return it.Current;
        }
    }
}

That should be safe to do not dispose an iterator of in-memory collection.

Please do not put me in jail for that :)


texts:
Given a string, reverse only the vowels present in it and print the
    resulting string.

    Input:

  First line of the input file contains an integer T denoting the
  number of test cases. Then T test cases follow. Each test case has a
  single line containing a string.

    Output:

  Corresponding to each test case, output the string with vowels
   reversed.

    Example:

    Input:

    4

    geeksforgeeks

    practice

    wannacry

    ransomware

    Output:

    geeksforgeeks

    prectica

    wannacry

    rensamwora

My approach:

/*package whatever //do not write package name here */

import java.util.Scanner;
import java.io.IOException;
import java.lang.StringBuffer;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

class GFG {

    private static String reverseVowels (String str) {

        List <Character>vowels = new ArrayList <>();
        vowels.add('a');
        vowels.add('e');
        vowels.add('i');
        vowels.add('o');
        vowels.add('u');

        List <Character>values = new ArrayList <>();
        List <Integer>keys = new ArrayList <>();

        for (int i = 0; i < str.length(); i++) {
            if (vowels.contains(str.charAt(i))) {
                keys.add(i);
                values.add(str.charAt(i));
            }
        }

        StringBuffer sb = new StringBuffer(str);

        Collections.reverse(values);
        int count = 0;

        for (Integer num : keys) {
            sb.replace(num.intValue(),num.intValue() + 1,String.valueOf(values.get(count)));
            count++;
        }

        return sb.toString();

    }

    public static void main (String[] args) throws IOException {
        Scanner sc = new Scanner (System.in);
        int numTests = sc.nextInt();

        for (int i = 0; i < numTests; i++) {
            String str = sc.next();
            System.out.println(reverseVowels(str));
        }
    }
}

I have the following questions about my code:

1) How can I further improve my approach?

2) Is there a better way to solve this question?

3) Are there any grave code violations that I have committed?

4) Can space and time complexity be further improved?

My time complexity is O(n) and space complexity is also O(n) currently.

Reference


texts: Handling multiple dimensions of arrays with speed

texts:
I'm looking to learn how to write efficient Haskell code. This snippet works, but the run time is slow. How can I write faster Haskell code?

Input: maxPrice = 7

Input: vendorsDelivery = [5, 4, 2, 3]

Input: vendorsProducts = [[1, 1, 1],[3, -1, 3],[-1, 2, 2],[5, -1, -1]]

Output: [1,2] (fastest delivery time for a given order)

import Data.List
import Data.List.Split
import Control.Monad

data Vendor a = Vendor { vendorNbr :: Int
                       , deliveryTime :: Int
                       , itemPrice :: Int
                       } deriving (Show)

populate d v = map (filter (\x -> itemPrice x /= (-1))) $ transpose $ map (\(x,y,z) -> map (\xs -> Vendor x y xs) z) $ zip3 [0..] d v

minimalBasketPrice mP vD vP = nub . get1 $ foldr (\x xs -> if get2 x < (get2 xs) then x else xs) (possible !! 0) possible
    where combos = sequence (populate vD vP)
          possible = filter (\(_,_,x) -> x <= mP) [((accu vendorNbr y), (total deliveryTime y), (total itemPrice y)) | y <- combos]

-- | Helper Functions

get1 (x,_,_) = x
get2 (_,x,_) = x

total f = foldr (\x y -> (f x) + y) 0
accu f = foldr (\x y -> (f x) : y) []


texts:
I am a relatively novice programmer, and I am taking steps into graphics programming. I am writing a quick pong clone and want to cap the FPS to save system resources. This is how I have implemented this (I've omitted other code for brevity)

#include <stdio.h>
#include <stdbool.h>
#include "SDL.h"
#include "Windows.h"
#define WIN32_LEAN_AND_MEAN
#define FPS 30

Uint32 starttime, endtime, deltatime;

int main()
{
 //initialize SDL and do other stuff
 //start game loop
 timeBeginPeriod(1);
 while (appisrunning)
 {
 starttime = GetTickCount();
    SDL_PollEvent(&event);
    if (event.type == SDL_QUIT)
    {
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
        appisrunning = false;
        break;
    }
 // render stuff here
 endtime = GetTickCount();
    if (endtime > starttime)
    {
        deltatime = endtime - starttime;
    }
    else // handles wraparound
    {
        deltatime = ((2 ^ 32) - starttime) + endtime;
    }
    if (deltatime > (1000 / FPS)) {}
    else
    {
        Sleep((1000 / FPS) - deltatime);
    }
 }
 timeEndPeriod(1);
 return 0;
}

I use timeBeginPeriod(1) in an effort to give Sleep() a ~1ms resolution. According to the MSDN documentation, this function sets the timer resolution system wide and can result in higher CPU usage as the scheduler has to switch tasks more often (if I understand correctly).

Is this the right approach for this task? What feedback do you have for me?


texts: Loading attributes of cars and orders from JSON

texts:
I am creating an application that deals with cars and orders.

A order contains a car and other information (BUYER, OWNER, ...), which constructs an orderObject.

A car has around 80 different attributes (TYP_WHEEL, TYP_DOOR, QUANTITY_WHEELS, ...) for the different car-parts.

I get the car-attributes and their values from a JSON string and put them into a map named allCarAttributes.

The JSON has this structure:

result:
    data[]:
        characteristics_0[]: …
            …
        characteristics_1[]: …
            …
            …
            …
        characteristics_N[]: …

Each characteristics-array contains some attributes:

"result": {
    "data": [
        {
            "characteristics": [
                {
                    "description": "Car ceiling color",
                    "id": "COL_CAR_CEILING",
                    "value": "F8",
                    "valueDescription": "F8 - White"
                },
                {
                    "description": "Color Car Finishes",
                    "id": "COL_CAR_ACCESSORIES",
                    "value": "T",
                    "valueDescription": "ST- Stainless Steel"
                },
                {
                    "description": "Car flooring color",
                    "id": "COL_CAR_FLOORING",
                    "value": "RD10",
                    "valueDescription": "RD10, grey"
                },
                (...)

Then I go through this map and based on the attribute name I set the respective value in the orderObject.

My problem:
Since the methods to set the values in the orderObject each have different names, I am not able to find a more efficient way than using a switch-case with 80 cases.

for (Map.Entry<String, String> attribute : allCarAttributes.entrySet()) {

        switch (attribute.getKey()) {
        case "TYP_DOOR":
            orderObject.setDoor(attribute.getValue());
            break;
        case "TYP_WHEEL":
            orderObject.setWheelType(attribute.getValue());
            break;
        case "QANTITY_WHEELS":
            orderObject.setWheelNumber(attribute.getValue());
            break;

        (...)

        default:
            break;
        }
    }

The orderObject-class simply has several fields and setters/getters for them:

private String car_width;
private String car_depth;
private String car_height;
private String car_weight;
(...)

public String getCar_width() {
    return car_width;
}

public void setCar_width(String car_width) {
    this.car_width = car_width;
}

How can I get rid of this huge switch-case?

Should I get rid of it at all? The switch-case works fine as it is, it is just very long and ugly.


texts:
My Code measures the longest path, not allowing cycles. For the example input below, the longest chain would be 4

Please can you review my code?

import numpy as np
inputgrid = np.array([['.','.','.','.','.'],
                      ['C','-','C','-','C'],
                      ['.','.','|','.','.'],
                      ['.','.','C','.','.'],
                      ['.','.','|','.','.'],
                      ['.','.','C','.','.'],
                      ['.','.','.','.','.']])# This Is Input

inputgrid = np.where(inputgrid=='.', 0, inputgrid)
inputgrid = np.where(inputgrid=='C', 1, inputgrid)
inputgrid = np.where(inputgrid=='-', 9, inputgrid)
inputgrid = np.where(inputgrid=='|', 9, inputgrid)

np.array(inputgrid).tolist()

grid = [[int(item) for item in row] for row in inputgrid]

def display(grid):
    for row in grid:
      print(row)

display(grid)

lst = []
for rows, row in enumerate(grid):
    for cols, col in enumerate(row):
        if grid[rows][cols] in [1]:
            lst.append((rows, cols))

bondlst = []
for rows, row in enumerate(grid):
    for cols, col in enumerate(row):
        if grid[rows][cols] in [9]:
            bondlst.append((rows, cols))

print(lst)
print(bondlst)

bondx = []
bondy = []

for item in bondlst:
    (bondx).append(item[0])
    (bondy).append(item[1])

print(bondx)
print(bondy)

adjacencylist = []

def adjacentnode(nodea ,nodeb):
    if nodea[0] == nodeb[0] and nodea[1] == nodeb[1]+2:
        adjacent = True
    elif nodea[0] == nodeb[0] and nodea[1] == nodeb[1]-2:
        adjacent = True
    elif nodea[1] == nodeb[1] and nodea[0] == nodeb[0]+2:
        adjacent = True
    elif nodea[1] == nodeb[1] and nodea[0] == nodeb[0]-2:
        adjacent = True
    else:
        adjacent = False
    return adjacent

print (adjacentnode((1,0),(1,2)))

count = 0

tempgraph = {}
for node in range(len(lst)):
    print (node)
    adjacencylist.append((lst[node] ,[]))
    for neighbour in range(len(lst)):
        adjacentnodes = (adjacentnode(lst[node] ,lst[neighbour]))
        print(adjacentnodes)
        if adjacentnodes == True:
            count = count +1
            adjacencylist[node][1].append(lst[neighbour])
            # adjacencylist.append((lst[node],[]))
            # adjacencylist.append(lst[node])
            # adjacencylist.append(lst[neighbour])

print (count)
print (adjacencylist)

for item in adjacencylist:
    tempgraph[str(item[0])] = (item[(1)])

carbongraph = {}
for i in tempgraph:
    carbongraph[i] = [str(k) for k in tempgraph[i]]

print(carbongraph)

#print(adjacencylist)

#print (carbongraph)
'''
carbongraph = {'(0, 1)' :['(0, 2)'], '(0, 2)' :['(0, 1)' ,'(0, 3)' ,'(1, 2)'],
               '(0, 3)' :['(0, 2)'], '(1, 2)' :['(0, 2)', '(2, 2)'], '(2, 2)': ['(1, 2)']}

WEIGHTS = 1
'''
def shortestpath(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if start not in graph:
        return None
    for node in graph[start]:
        if node not in path:
            newpath = shortestpath(graph, node, end, path)
            if newpath:
                return newpath
    return None

LeafArray = []
for leaf in carbongraph:
    degree = (len(carbongraph[leaf]))
    if degree == 1:
        LeafArray.append(leaf)

print(LeafArray)

chainlist = []
for node in LeafArray:
    for neighbour in LeafArray:
        currentpath = (shortestpath(carbongraph, node, neighbour))
        carbonchain = len(currentpath)
        print(currentpath)
        chainlist.append(carbonchain)

longestchain = max(chainlist)
print(longestchain)

def Prfix():
    global prefix
    if longestchain == 4:
        prefix = "But"
    elif longestchain == 5:
        prefix = "Pent"
    elif longestchain == 6:
        prefix = "Hex"
    elif longestchain == 7:
        prefix = "Hept"
    elif longestchain == 8:
        prefix = "Oct"
    return prefix

print(Prfix())
```


texts: In place solution to remove duplicates from a sorted list

texts:
I am working on the problem removeDuplicatesFromSortedList

  Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

  Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

  Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

My solution and TestCase

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        """
        """
        #Base Case
        if len(nums) < 2: return len(nums)

        #iteraton Case
        i = 0  #slow-run pointer
        for j in range(1, len(nums)):
            if nums[j] == nums[i]:
                continue
            if nums[j] != nums[i]: #capture the result
                i += 1
                nums[i] = nums[j] #in place overriden
        return i + 1

class MyCase(unittest.TestCase):
    def setUp(self):
        self.solution = Solution()

    def test_raw1(self):
        nums = [1, 1, 2]
        check = self.solution.removeDuplicates(nums)
        answer = 2
        self.assertEqual(check, answer)

    def test_raw2(self):
        nums = [0,0,1,1,1,2,2,3,3,4]
        check = self.solution.removeDuplicates(nums)
        answer = 5
        self.assertEqual(check, answer)

unittest.main()

This runs but I get a report:

  Runtime: 72 ms, faster than 49.32% of Python3 online submissions for Remove Duplicates from Sorted Array.
  Memory Usage: 14.8 MB, less than 5.43% of Python3 online submissions for Remove Duplicates from Sorted Array.

Less than 5.43%, I employ the in-place strategies but get such a low rank, how could improve it?


texts:
I have my class DBFuntcions containing this 2 methods:

The method for the connection to the database:

Connection connection_db(String username, String password, String dbname, Connection c) {
    try {
        Class.forName("org.postgresql.Driver");
        c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"
                + dbname, username, password);
        System.out.println("Opened database successfully");
    } catch (ClassNotFoundException | SQLException e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage() + "\n\n\n");
    }
    return c;
}

And the method for the query.

void viewAll(String tableName, long startDate, long endDate, Connection c, String path) {
    String query = "SELECT * FROM " + tableName + " WHERE CAST(receivedtime AS integer) BETWEEN ? AND ? ORDER BY source, receivedtime;";

    try (PreparedStatement stmt = c.prepareStatement(query)) {              //try with resources
        stmt.setLong(1, startDate);                                         //prepare query
        stmt.setLong(2, endDate);
        ResultSet rs = stmt.executeQuery();

        try {
            while (rs.next()) { ... }

My question it is the best to open and close the connection?

Just before calling the query and closing right after?
Opening and closing the connection inside the query method?
Or it is better to open it in the main and close it at the end?

I think it should depends of the number of time I try to access to it. Let's say for the moment I only have this query and run it only once.


texts: Sklearn: Regularized ridge regression for predicting fantasy football performance from several sources' projections

texts:
I've been working on trying to predict fantasy performance of players in this upcoming NFL season based on projections from several experts/sources. I trained the data on projections from last year and performed cross validation using the actual fantasy points that each player ended up scoring. I was just wondering if I could get some feedback on this little project of mine. I don't have any specific questions. Just point out anything I may have overlooked. Here's the code and also the input data:

import pandas as pd
import os
import sklearn.linear_model as linear_model
from sklearn.grid_search import GridSearchCV
from sklearn.preprocessing import StandardScaler

def ridge_pipeline(df,df_2017):
     x_unscaled=df.filter(regex=('.*_proj_pts'))
     x=StandardScaler().fit_transform(x_unscaled)
     y=df.actual_points
     param_grid={'alpha':[0.0001,0.001,0.1,1,10,100,500,1000]}
     grid = GridSearchCV(linear_model.Ridge(), param_grid, cv=10,n_jobs=-1)
     grid.fit(x, y)
     best_alph=grid.best_params_['alpha']
     if best_alph in [0.0001,1000]:
         return 'WARNING: best_alph at endpoint'+': '+str(best_alph)
     else:
         ridge=linear_model.Ridge(alpha=best_alph).fit(x,y)
         x_2017=df_2017.loc[:,list(x_unscaled)]
         x_2017=StandardScaler().fit_transform(x_2017)
         df_2017['my_proj']=ridge.predict(x_2017)
         return df_2017.loc[:,['player','position',
              'my_proj']].sort_values('my_proj',ascending=False)

 df_2017=pd.read_csv('2017_projections.csv')
 masterDf=pd.read_csv('2016_actual_and_proj.csv')
 d={}
 for pos in ['DST','QB','RB','WR','TE']:
      result=ridge_pipeline(masterDf.loc[masterDf
           ['position']==pos],df_2017.loc[df_2017['position']==pos])
      d[pos]=result
 myProjDf=pd.concat([df for df in d.values()],ignore_index=True)
 myProjDf.to_csv('my_projections.csv',index=False)

2016_actual_and_proj

2017_projections