texts: Prefixing prices of certain product categories with text in Woocommerce

texts:
I had the need to prefix the price for certain product categories on only the shop page (because the price can be higher depending on extras that the customer might want).

These were my requirements for this code:

Add the prefix only on the shop page, not on the product page;
Only add the prefix to certain (hardcoded) product categories.

I'd like some advice on possible improvements and certainly about possible security risks, if there are any.

Along with that, I've heard that globals are considered bad practise, but I see them a lot in Wordpress. What are the alternatives, if there's any.

This is the code:

add_filter('woocommerce_get_price_html', 'change_product_price_html');
function change_product_price_html($price){

  // Check if we're on the shop page
  // Don't want the prefix on the product pages.
  if( is_shop() ) {
    global $product;

    // ID of categories to add the prefix to
    $categories = ["17"];

    // Loop through all the category ID's if they equal one of the values
    // in the array, add the prefix.
    foreach( $product->get_category_ids() as $id ) {
      if( in_array($id, $categories) ) {

        // Add prefix
        $prefixedPrice   = "<span class='woocommerce-Price-amount amount'>Starting at </span>";
        $prefixedPrice  .= $price;

        return $prefixedPrice;
      }
    }
    // Nothing matched in the loop,
    // return the price without the prefix.
    return $price;
  }
  // We're not on the shop page so
  // return the price without the prefix.
  return $price;
}


texts: Batch file that checks for wifi connection - reconnects if no internet

texts:
There is a remote Windows PC that has access to "landline" unmetered WiFi and there is a Verizon 4G LTE MiFi (metered WiFi) as backup. This script checks to see if the PC is connected to any WiFi, connected to metered WiFi, or has any internet connection. It will be called a few times a day by Task Scheduler. Everything seems to work OK while testing at home.

@echo off
SETLOCAL enabledelayedexpansion

rem get computer name
set host=%COMPUTERNAME%
set wifi=
if "%host%"=="HOME" (
    set landline=xxx
    set metered=Verizon-4GLTE-xxx-xxxx
)
if "%host%"=="WORK" (
    set landline="xxx spaces in name xxx"
    set metered=Verizon-4GLTE-xxx-xxxx
)
echo.
echo **************************************************
echo %host%
echo landline wifi = !landline!
echo metered wifi = !metered!
echo **************************************************
echo.
echo.
echo ping test and if no response, connect to !metered! ...
echo *************************************************************************************
ping 8.8.8.8 -n 1 || netsh wlan connect name=!metered!
echo *************************************************************************************
timeout /t 10

echo.
echo Attempting to connect to landline wifi %landline% ...
netsh wlan connect name=%landline%
timeout /t 10

echo.
echo.
echo Fail safe...
echo ping test and if no response, connect to !metered! ...
echo *************************************************************************************
ping 8.8.8.8 -n 1 || netsh wlan connect name=!metered!
echo *************************************************************************************


texts: Sort an array of sentences alphabetically, ignoring the first word if it equals 'the' (case insensitive)

texts:
function order_ignore_the($a, $b){
     // orders sentences ascending alphabetically, ignoring the  work "the"
     $args = func_get_args();
     foreach($args as $k=>$v){

          $sort = explode(" ",$v);
          $args[$k] = (strtolower($sort[0]) == "the" ? $sort[1] : $sort[0]);
     }

    return strcmp($args[0], $args[1]);
}

usort($array_of_sentences,'order_ignore_the');


texts: Programming Challenge from Kattis: Apparatus

texts:
I am trying to solve apparatus problem, paraphrased below.

  There is an apparatus with n on/off switches with a one-to-one correspondence to n lights (but with an unknown permutation).
  We have several different photographs of the apparatus showing different configurations of the switches and lights. Are these photos sufficient to fully describe the device?

  Input

  First line contains two integers: n (the number of switches, 1 ≤ n ≤ 1000) and m (the number of photographs, 0 ≤ m ≤ 1000).

  Each subsequent pair of lines describes the switches and the lights as a string of 1 (on) and 0 (off).

  Output

  Write the number of possible different wirings, modulo 1000003.

I have a solution but it takes longer than 2 seconds which is the time limit. I've tried to optimize my code for speed but can't get it within the 2 second limit.

import sys
import math

for line in sys.stdin:

    line = line.strip("\n").split(" ")
    numSwitches = int(line[0])
    numPics = int(line[1])

    wiring = {}
    inValid = False
    for i in range(numPics):
        if (inValid):
            break
        x = sys.stdin.readline().strip("\n")
        f_x = sys.stdin.readline().strip("\n")

        x_ones = 0
        f_x_ones = 0

        digit = 0
        for i in range(numSwitches):
            if f_x[i]=='1':
                digit += 2**(numSwitches-i-1)
                f_x_ones += 1

        for switch in range(numSwitches):
            if (x[switch]=='1'):
                x_ones += 1
                if not (switch in wiring.keys()):
                    wiring[switch] = digit
                else:
                    wiring[switch] &= digit

        if x_ones != f_x_ones:
            inValid = True
            break

    if not inValid:
        for i in wiring.values():
            if i==0:
                inValid = True
                break

    for possibilities in set(wiring.values()):
        frequency = wiring.values().count(possibilities)
        if frequency>1:
            oneBits = 0
            while (possibilities>0):
                oneBits += (possibilities%2==1)
                possibilities /= 2
            if oneBits < frequency:
                inValid = True
                break

    if not inValid:
        print math.factorial(numSwitches-numPics)%1000003
    else:
        print 0

I'm looking for suggestions of ways I should have approached the problem or input on how I can optimize my current code.

Note:
Consider the following test case:

3 2
110
011
011
011

My code finds that is invalid in the following manner. First, upon encountering the first photograph (110, 011). The wiring dictionary gets assigned the following keys and values:

wiring[0] = 011
wiring[1] = 011

This means that the first and second switch can light up either the second or third lights. Upon encountering the second photograph (011, 011). wiring is updated as follows:

wiring[1] = 011 & 011 = 011
wiring[2] = 011

Now observe that the state of wiring indicates that all three switches can light up either the second and third lights. This is an inconsistency since 3 switches have to light up three lights, here we have three switches lighting up 2 lights.


texts: Simplify an if else construct with assignment before if and else

texts:
I want to simplify an if: .. else: .. construct:

def find_eulerian_tour(graph):
    available_edges, path = initial_state(graph)
    while incomplete(available_edges):
        edge = propose_extension_edge(available_edges, path)
        if extension_is_possible(edge):
            extend_path(available_edges, path, edge)
        else:
            node = propose_node_for_reorder(available_edges, path)
            if reorder_is_sensible(node):
                path = reorder_path(available_edges, path, node)
            else:
                return None
    return path

It seems unnecessarily complicated, because the idea can be expressed much simpler.

def find_eulerian_tour(graph):
    available_edges, path = initial_state(graph)
    while incomplete(available_edges):
        if extension_is_possible(available_edges, path):
            extend_path(available_edges, path)
        elif reorder_is_sensible(available_edges, path):
            path = reorder_path(available_edges, path)
        else:
            return None
    return path

But now I have to do the calculations from

edge = propose_extension_edge(available_edges, path)

and

node = propose_node_for_reorder(available_edges, path)

twice because I can't keep the results in variables (edge = .., node = ..).

I am looking for an idea to keep code as simple as it is with the elif construction while doing the propose_node..-calculation only once.

def find_eulerian_tour(graph):
    available_edges, path = initial_state(graph)
    while incomplete(available_edges):
        edge = propose_extension_edge(available_edges, path)
        if extension_is_possible(edge):
            extend_path(available_edges, path, edge)
        else:
            node = propose_node_for_reorder(available_edges, path)
            if reorder_is_sensible(node):
                path = reorder_path(available_edges, path, node)
            else:
                return None
    return path

def initial_state(graph):
    available, path = graph[:], []
    if len(available) > 0:
        path.append(available[0][0])
    return available, path

def incomplete(available_edges):
    return len(available_edges) > 0

def propose_extension_edge(available_edges, path):
    last_node = path[-1]
    for edge in available_edges:
        if last_node in edge:
            return edge
    return None

def extension_is_possible(edge):
    return edge

def extend_path(available_edges, path, edge):
    if edge[0] == path[-1]:
        path.append(edge[1])
    else:
        path.append(edge[0])
    available_edges.remove(edge)

def propose_node_for_reorder(available_edges, path):
    if reorder_is_possible(path):
        return find_split(available_edges, path)
    return None

def reorder_is_possible(path):
    return is_tour(path)

def find_split(available_edges, path):
    options = edgenodes(available_edges)
    for node in options:
        if node in path:
            return node
    return None

def reorder_is_sensible(node):
    return node

def is_tour(path):
    return path[0] == path[-1]

def edgenodes(edges):
    result = []
    for edge in edges:
        for node in edge:
            if not node in result:
                result.append(node)
    return result

def reorder_path(available_edges, tour, split):
    split_location = tour.index(split)
    return tour[split_location:-1] + tour[0:split_location+1]

Example use:

graph1 = [(1, 2), (2, 3), (3, 1)]
graph2 = [(0, 1), (1, 5), (1, 7), (4, 5), (4, 8), (1, 6), (3, 7), (5, 9), (2, 4), (0, 4), (2, 5), (3, 6), (8, 9)]
graph3 = [(1, 13), (1, 6), (6, 11), (3, 13), (8, 13), (0, 6), (8, 9),(5, 9), (2, 6), (6, 10), (7, 9), (1, 12), (4, 12), (5, 14), (0, 1), (2, 3), (4, 11), (6, 9), (7, 14), (10, 13)]

print find_eulerian_tour(graph1)
print find_eulerian_tour(graph2)
print find_eulerian_tour(graph3)


texts: How to simplify the following distance function for the taxicab ring metric space?

texts:
Consider the taxicab ring metric space shown below. This is a discrete metric space in which we have both a grid and concentric diamond rings. This metric space stretches infinitely in all four directions, but I have only drawn four rings.
I want to write a function that returns the shortest distance between any two points in this metric space. Obviously, the shortest distance must be lesser than or equal to the taxicab distance because sometimes we can take the diagonal shortcuts. For example, the taxicab distance between (2,-1) and (3,1) is 3. However, we can reduce this to 2 when we follow the diagonal shortcut from (2,-1) to (3,0). Similarly, the taxicab distance between (2,-1) and (-1,3) is 7. However, we can reduce this to 5 when we follow the diagonal shortcut from (2,0) to (0,2).

So, here's the function that I came up with in Haskell. It computes the taxicab distance and then subtracts the diagonal shortcut distance to get the final result. The shortcut distance is calculated in one to three steps. First, we translate and rotate p2 such that p1 is at the origin. This is so that we don't repeat ourselves by duplicating code for each of the four quadrants. If the new p2 is in the upper right quadrant then the shortcut distance is 0 because we're moving in a line perpendicular to the diagonal.
If the new p2 is in the upper left or the lower right quadrants then we are moving parallel to the diagonal. Hence, we can compute the shortcut distance accordingly. It's the minimum of the difference in x and y coordinates and the corresponding absolute coordinate of p1, i.e. x1 for upper left quadrant and y1 for the lower right quadrant.
Finally, if the new p2 is in the lower left quadrant then we take advantage of symmetric property of distance functions to perform the above steps again with p1 and p2 swapped. If both p1 and p2 are in opposite quadrants then we'll eventually call the opposite function. Now, there are two paths to get from p1 to p2. Either we go down first and then left or vice versa. Hence, we compute the shortcut distance for both and then select the one which is greater.
type Coord = (Integer, Integer)

type Metric = Coord -> Coord -> Integer

dist :: Metric
dist p1@(x1, y1) p2@(x2, y2) = abs (x2 - x1) + abs (y2 - y1) - diag p1 p2

diag :: Metric
diag = adjacent (adjacent opposite)

adjacent :: Metric -> Metric
adjacent metric p1@(x1, y1) p2@(x2, y2)
    | x >= 0 && y >= 0 = 0
    | x <= 0 && y >= 0 = minimum [abs x, abs y, abs x1]
    | x >= 0 && y <= 0 = minimum [abs x, abs y, abs y1]
    | otherwise        = metric p2 p1
    where
        x = if x1 < 0 then x1 - x2 else if x1 > 0 then x2 - x1 else abs x2
        y = if y1 < 0 then y1 - y2 else if y1 > 0 then y2 - y1 else abs y2

opposite :: Metric
opposite (x1, y1) (x2, y2) =
    max (minimum [abs (x2 - x1), abs x1, abs y2])
        (minimum [abs (y2 - y1), abs x2, abs y1])

Anyway, is it possible to simplify the above distance function? For example, diag is currently defined as the application of an iterated function to another function. Can we get rid of this without duplicating code? Alternatively, is it possible to replace the call to diag with a closed-form expression? The diag function is quite complex. Is it possible to simplify it?


texts: “Removing” reference from its ReferenceQueue

texts:
Sometimes I need to ensure that some references won't be processed while examination from the associated ReferenceQueue. Generally at those moments I don't know reachability status of the referent.

The only way I've came up with:

class MyReference<V> extends SoftReference<V> {
    private boolean active = true;

    public MyReference(V referent, ReferenceQueue<? super V> queue) {
        super(referent, queue);
    }

    public void disable() {
        active = false;
    }

    public boolean isActive() {
        return active;
    }
}

// examination
Reference<? extends V> ref;
while ((ref = referenceQueue.poll()) != null) {
    @SuppressWarnings("unchecked")
    MyReference<V> myRef = (MyReference<V>) ref;
    if (myRef.isActive()) {
        // process ref
    }
}

Is this the right approach?


texts: Keep div fixed when it is inside it's container on scroll

texts:
The required behaviour is :

The yellow span must be positioned relatively to viewport (position:fixed;) when it is inside the pink div.
The height of yellow span must always be the same as viewport height minus 100px. It has a fixed width in px.
The yellow span must be verticaly centered in the viewport (this rule is modified by rule 4).
On scroll, the yellow span must never be outside the boundaries of the pink div. If the page is scrolled further than the pink div, the yellow span must be absolutely positionned to the bottom of the pink div and scroll up with it
If the page is scrolled back up to the pink div, the yellow span must go back to fixed position (as in rule 1 and 2).

I know sticky positioning does exaclty that but I can't use it because of poor browser support. So I made this snippet and would like to know if it can be optimized or shortened :

$(document).scroll(function() {
  var span = $('span'),
    div = $('div'),
    spanHeight = span.outerHeight(),
    divHeight = div.height(),
    spanOffset = span.offset().top + spanHeight,
    divOffset = div.offset().top + divHeight;

  if (spanOffset >= divOffset) {
    span.addClass('bottom');
    var windowScroll = $(window).scrollTop() + $(window).height() - 50;
    if (spanOffset > windowScroll) {
      span.removeClass('bottom');
    }
  }
});
*{margin:0;}
div {
  position: relative;
  background: pink;
  height: 800px;
  margin-bottom: 800px;
}
span {
  position: fixed;
  right: 0;
  bottom: 50px;
  width: 10%;
  height: calc(100vh - 100px);
  background: gold;
}
.bottom {
  position: absolute;
  bottom: 0;
  right: 0;
}

  some content


texts:
Purpose

I recently came across an interview question that stumped me for a while

  Given a list of integers, write a function that returns the largest sum of non-adjacent numbers.

I am looking for feedback around both my implementation and the correctness of my proposed solution (I have some test
cases, but I could have missed a case).

Approach

For arrays with 1 or 2 values, the answer is trivial.

For arrays with more than 2 values, keep track of the maximum sum from the preceding non-adjacent elements that
includes the most recent non-adjacent element, and the maximum sum from the preceding non-adjacent elements that
excludes the most recent non-adjacent element.

So for [3, 1, 1, 5, 1] at index 3, the maximum sum from preceding non-adjacent elements that includes the most recent
non-adjacent element is 1, while the maximum sum from preceding non-adjacent elements that excludes the most recent
non-adjacent element is 3.

Taking the max of these two sums and adding them to the current value will produce the maximum sum for non-adjacent
elements up to that index. Continuing this process for each remaining index and then comparing the last two calculated
sums will produce the maximum sum.

Let's walk through this process with [3, 1, 1, 5, 1].

At index 0, the max sum is 3
At index 1, the max sum is 1
At index 2, the max sum from including the most recent non-adjacent element is 3, while the max sum from excluding
the most recent non-adjacent element is 0. Thus, we choose 3 and add that to the current value (1). 4 is now
the max non-adjacent sum for index 2.
At index 3, the max sum from including the most recent non-adjacent element is 1, while the max sum from excluding
the most recent non-adjacent element is 3. Thus, we choose 3 and add that to the current value (5). 8 is now
the max non-adjacent sum for index 3.
At index 4, the max sum from including the most recent non-adjacent element is 4, while the max sum from excluding
the most recent non-adjacent element is 3. Thus, we choose 4 and add that to the current value (1). 5 is now
the max non-adjacent sum for index 4.
The final two sums were 8 and 5 - we take the max (8).

Apologies if this was confusing to follow, it was difficult to describe my thought process.

Implementation

public class MaximumNonAdjacentElementSumIdentifier {
    public static int identify(int[] values) {
        if (values == null || values.length == 0) {
            throw new RuntimeException("Unable to identify sum");
        }

        if (values.length == 1) {
            return values[0];
        }

        int firstSum = 0;
        int secondSum = values[0];
        int previousValueSum = values[1];

        for (int i = 2; i < values.length; i++) {
            int value = values[i];
            int maximumCurrentElementSum = Math.max(firstSum, secondSum) + value;
            firstSum = Math.max(firstSum, secondSum);
            secondSum = previousValueSum;
            previousValueSum = maximumCurrentElementSum;
        }

        return Math.max(secondSum, previousValueSum);
    }
}


texts: Randomized Algorithm for finding optimal path in graph

texts:
Note: the optimal path can be chosen as the shortest path or the longest path
I made a randomized algorithm for finding random paths in a graph. The graph has weights on the edges.  For non-cyclic graphs, the algorithm does not form any cycles. However, cyclic graphs can form cycles.
These paths are required to go from a start node to the end node. I am wondering if the average time and average space analysis is correct for distinct inputs on the make paths function.
The output of the code is the paths and the total of the weights. These are both parallel arrays.
Below is the code.

"""
Randomized Algorithm to find nodes from start_point to end_point
"""

def make_paths(graph, edges, goal_point, start_point, num_of_paths):
    """
    graph: dict
    edges: dict
    paths: list
    start_point: str
    returns: List[str], the paths

    Note: randomly goes through graph data structure to generate paths
    Also Note: can contain cycles within the paths

    avg time: O(len(graph) * num_of_paths)
    avg space: O(num_of_paths + num_of_paths * len(graph))

    amortized time: O(len(graph) * len(graph))
    amortized space: O(num_of_paths + num_of_paths * len(graph))
    """

    paths = [start_point for row in range(num_paths)]
    for path in paths:
        while not path[-1] == goal_point:
            end_point = path[-1]
            added_point = random.choice(graph[end_point])
            path.append(added_point)
    return paths

def calculate_totals(paths, edges):
    """
    paths: List[str]
    edges: Dict[Tuple[str, str], int]
    returns: List[int], totals for these paths

    avg time: O(len(paths) * len(paths))
    avg space: O(len(paths))

    amortized time: O(len(paths) * len(paths))
    amortized space: O(len(paths))
    """
    totals = [0 for row in range(len(paths))]
    for row in range(0, len(paths)):
        for col in range(0, len(paths) - 1):
            edge = edges[(paths[row][col], paths[row][col + 1])]
            totals[row] = totals[row] + edge
    return totals

def main():
"""
Driver Program
"""
    graph = dict()
    graph['a'] = ['a', 'b']
    graph['b'] = ['a']

    edges = dict()
    edges[('a', 'a')] = 0
    edges[('a', 'b')] = 1

    start_point = 'a'
    goal_point = 'b'
    num_of_paths = 3

    paths = make_paths(graph, edges, goal_point, start_point, num_of_paths)
    totals = calculate_totals(paths, edges)

    print(totals)

if __name__ == '__main__':
    main()


texts: Javascript inheritance: is my solution correct?

texts:
I have been developing Javascript for few months, and, as a former Java developer, needed a simple way to perform class inheritance.

My needs are:

having private members not accessible (encapsulation),
to make inheritance simple,
to avoid 'new' keywords bugs,
to let the superclass methods accessible using the this.super property.

The purpose of this request is to indicate me if the solution I developped should be applied into my project or if there are some misbehaviour risks by using it, and if you have remarks on how to enhance it.

My code is below, thank you for your reviews.

/**
* Allows to retrieve the global object (used to test if the 'new' keyword is needed)
*/
function getGlobal(){
    return (function(){
            return this;
    }).call(null);
}

if (typeof Object.extend !== 'function') {
    Object.extend = function (object, superClassConstructor, superConstructorArgs) {
        //Inherits from the super object
        superClassConstructor.apply(object, superConstructorArgs);

        //make this.super allow to access to inherited object original functions
        object.super = {};
        for (var property in object){
            object.super[property] = object[property];
        }
    };
}
//The superclass
function SuperClass(options){
    //Make sure we will not alter global object
    if (this === getGlobal()){
        throw new Error("Constructor cannot be called as a function (new keyword should not be omitted)");
    }
    //Use of jshashtable-2.1:
    var attributes = new Hashtable();

    for (var key in options){
        attributes.put(key, options[key]);
    }

    this.setValue = function(key, value){
        if(value != null){
            attributes.put(key, value);
        }
        else{
            attributes.remove(key);
        }
    };

    this.getValue = function(key){
        return attributes.get(key);
    };
}

/**
* Inheriting class
*/
function ProjectModel(projectId) {
    //Make sure we will not alter global object
    if (this === getGlobal()){
        throw new Error("Constructor cannot be called as a function (new keyword should not be omitted)");
    }
    //extends SuperClass
    Object.extend(this, SuperClass, [{
                                    id:projectId,
                                    'one':1,
                                    'two':"2"
                                    }]);

    this.myType = "ProjectNumber";
    //Overriding a function
    this.getValue = function(key){
        return this.myType + ":" + this.super.getValue(key);
    };
}

var project = new ProjectModel(123);
alert(project.getValue('one')); //this displays 'ProjectNumber:123'


texts: Android single activity app structure for smooth ux

texts:
I have an app that has only one activity and 5 fragments. I removed the navigation component because it was buggy and restored the old navigation, which is simply a BottomNavigationView with OnClickListener.

The problem is, that I don't want to recreate the fragment views, because it takes up to a second for 2 of them (and also I don't want that the webview is recreated, because it would have to load the page again). Thats why I just simply hide/show them. And here is the first problem: They are still running in background and recieve events, etc. what I don't want.

But the real problem is performance: I set slide in/out transitions and they lagg, while opening a fragment with only 1x RecyclerView and 10 items in it. The items only contain 4 strings...

I have a fragment with a WebView where it is much worse. The thing is, when I open the fragments the first time it still takes a second, because it has to create the view, but after that, it only has to animate the old fragment out and the new one in. Why does it skip frames? The UI thread is overwhelmed with just the animation!?! When I remove the animation, it nearly changes fragments instantly, maybe there is like 30ms delay (not even worth mentioning) and it doesn't look laggy.

I am new to android and I saw that there are a lot of ways of handling fragments and navigation, what is the best practice to display fragments, save their state and animate them smooth? Or is there even an alternative to fragments?

I don't need working code, just a step in the right direction.

How I am currently changing fragments:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

//Set animations
if(activeFragment < index){
    ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
} else {
    ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
}

//Hide old Fragment
if (Fragments.get(activeFragment).isAdded())
{
    ft.hide(Fragments.get(activeFragment));
    Fragments.get(activeFragment).getView().setTranslationZ(0);
}

//Add/Show new Fragment
if (Fragments.get(index).isAdded()) { // if the fragment is already in container
    ft.show(Fragments.get(index));
    Fragments.get(index).getView().setTranslationZ(1f);
} else { // fragment needs to be added to frame container
    ft.add(R.id.fragment_container, Fragments.get(index), Integer.toString(index));
}

// Commit changes
ft.commit();


texts:
I started learning my first functional programming language (Haskell) yesterday and I have been working on a lexer for an expression evaluator. The lexer is now basically feature complete, but I'm not sure what I can do to improve the code.

import Data.Char
import Data.List

data TokenType = Identifier |
                 RealNumberLiteral |
                 PlusSign |
                 MinusSign |
                 Asterisk |
                 ForwardSlash |
                 Caret |
                 LeftParenthesis |
                 RightParenthesis
    deriving (Show)

data Token = Token TokenType String
    deriving (Show)

read_token :: String -> Token
read_token [] = error "Unexpectedly reached the end of the source code while reading a token."
read_token source_code@(next_character:_)
    | isSpace next_character = read_token (dropWhile isSpace source_code)
    | isAlpha next_character = Token Identifier (takeWhile isAlpha source_code)
    | isDigit next_character = let token_lexeme = (takeWhile (\x -> isDigit x || x == '.') source_code)
                               in let period_count = length (filter (=='.') token_lexeme)
                                  in Token RealNumberLiteral (if period_count <= 1
                                                                  then token_lexeme
                                                                  else error "There can only be one period in a real number literal.")
    | next_character == '+' = Token PlusSign "+"
    | next_character == '-' = Token MinusSign "-"
    | next_character == '*' = Token Asterisk "*"
    | next_character == '/' = Token ForwardSlash "/"
    | next_character == '^' = Token Caret "^"
    | next_character == '(' = Token LeftParenthesis "("
    | next_character == ')' = Token RightParenthesis ")"
    | otherwise = error ("Encountered an unexpected character (" ++ [next_character] ++ ") while reading a token.")

append_read_tokens :: [Token] -> String -> [Token]
append_read_tokens tokens source_code
    | null source_code = tokens
    | isSpace (head source_code) = append_read_tokens tokens (dropWhile isSpace source_code)
    | otherwise = let next_token@(Token next_token_type next_token_lexeme) = read_token source_code
                  in append_read_tokens (tokens ++ [next_token]) (drop (length next_token_lexeme) source_code)

tokenize :: String -> [Token]
tokenize [] = []
tokenize source_code = append_read_tokens [] source_code


texts:
Should I check Count before Linq Single() call if I expect only one element?

if (objects.Count != 1)
{
    throw new
        InvalidOperationException(
            "%Collection% should contain one %element%, but now it's: "
                 + objects.Count);
        }

return objects.Single();

Single implements the same check and throwing. But its message is less specific.

P.S. in my case wrong count is handled just writing log message like

_log.Error("Error during %operation%", ex);
task.Complete(TaskResult.Fail);


texts:
This is still my first week of learning C++, I solved the lower bound STL challenge in HackerRank Lower Bound STL but I'm having time exceeded issue for long input. I'm open to constructive criticism, ways to improve in terms of syntax, style and performance.

You are given \$N\$ integers in the sorted order. Then you are given
\$Q\$ queries. In each query, you will be given an integer and you have
to tell whether that integer is present in the array if so you have
to tell at which index it is present and if it is not present you have
to tell the index at which the smallest integer that is just greater
than the given number is present. Lower bound is a function that can
be used with a sorted vector.
Input Format
The first line of the input contains the number of integers \$N\$.
The next line contains \$N\$ integers in sorted order. The next line
contains \$Q\$, the number of queries. Then \$Q\$ lines follow each
containing a single integer \$Y\$.
If the same number is present multiple times, you have to print the first index at which it occurs. The input is such that you always have
an answer for each query.
Constraints

\$1 \leq N \leq 10^5\$
\$1 \leq X_i \leq 10^9\$, where \$X_i\$ is \$i^{th}\$ element in the    array
\$1 \leq Q \leq 10^5\$
\$1 \leq Y \leq 10^9\$

Output Format
For each query you have to print "Yes"(without the quotes) if the
number is present and at which index it is present separated by a
space. If the number is not present you have to print "No"(without the
quotes) followed by the index of the next smallest number just greater
than that number. You have to output each query in a new line.
Sample Input
 8
 1 1 2 2 6 9 9 15
 4
 1
 4
 9
 15

Sample Output
 Yes 1
 No 5
 Yes 6
 Yes 8

Here is my code
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int N;
    int query;
    int queryLength;
    {

    std::vector<int>::iterator low;
    std::vector<int>::iterator  foundValue;
    std::cin >> N;

    std::vector<int> v(N);
    //populate the vector
     for(int i =0; i<N; i++){
         std::cin >> v[i];
     }

    std::cin >> queryLength;

    for(int j = 0; j < queryLength; j++){
         std::cin >> query;
         foundValue= find(v.begin(), v.end(), query);
         if (foundValue != v.end())
         {
             std::cout << "Yes "<< (foundValue-v.begin()+ 1) << std::endl;
         }
          else{
            low = std::lower_bound (v.begin(), v.end(),query);
             std::cout << "No "<< find(v.begin(), v.end(), *low)-v.begin()+ 1 << std::endl;
          }
    }
}
    return 0;
}


texts:
My aim is to sort a list of strings where words have to be sorted alphabetically. Words starting with s should be at the start of the list (they should be sorted as well), followed by the other words.

The below function does that for me.

def mysort(words):
    mylist1 = sorted([i for i in words if i[:1] == "s"])
    mylist2 = sorted([i for i in words if i[:1] != "s"])
    list = mylist1 + mylist2
    return list

I am looking for better ways to achieve this, or if anyone can find any issues with the code above.


texts: CodeWars - Assembly Language - Check List For Value

texts:
I'm doing assembly language problems on CodeWars, a website with practice problems.
Problem
https://www.codewars.com/kata/545991b4cbae2a5fda000158/train/nasm

Create a method that accepts a list and an item, and returns true if the item belongs to the list, otherwise false.

Solution In C
To give you an idea what the assembly code will be doing.
#include <stdbool.h>
#include <stddef.h>

bool include(const int* arr, size_t size, int item)
{
    int i = 0;
    loop:
    if ( i < size ) {
        if ( arr[i] == item ) {
            return true;
        }
        i++;
        goto loop;
    }
    return false;
}

Solution In NASM Assembly (Linux x64)
CodeWars provided the 7 lines at the top.
SECTION .text
global include
include:

    ; bool include(const int* arr, size_t size, int item)
    ; sizeof(int) = 4 bytes (32bit)
    ; sizeof(size_t) = 8 bytes (64bit)

    ;rdi = &arr    pointer, 8 bytes
    ;   arr[i]          signed int, 4 bytes (dd)
    ;rsi = size    size_t, unsigned int, 8 bytes
    ;edx = item    signed int, 4 bytes

    ; Avoid using registers that we need to preserve (RBX, RBP, R12-R15). Else we'd have to push and pop them onto the stack.

    mov rcx, 0      ; unsigned int i = 0;
loop1:
    cmp rcx, rsi    ; if ( i < size ) {
    jae skip_loop

    mov r8d, [rdi + 4 * rcx]        ; make a temp variable so we can see this in step debugging
    cmp edx, r8d    ; if ( arr[i] == item ) {
    jne skip_if
    mov rax, 1      ; return true;
    ret

skip_if:
    inc rcx         ; i++;
    jmp loop1

skip_loop:
    mov rax, 0      ; return false;
    ret

Questions
I'm brand new to assembly. Any feedback on patterns and best practices would be appreciated. For example

Is there a standard pattern to use when writing loops?
Is there a standard pattern to use when writing if/elseif/else?
Are there better word choices and formatting for the labels?


texts: JavaScript popup component with state depending on existing class

texts:
Making long story short, I got a chance to jump from DevOps to Software Development (Frontend). Because I'm quite new to JS design patterns, I need some quality advice about the job I've done recently.

The goal is to create a component which checks if there's a particular class on the current page, and if yes, add event listeners for the document (one default & one custom) that will hold the logic for triggering a popup. The popup should appear only once, then the event listener should not perform any anymore actions. For this, I defined the lockPopup variable (state management). There is also screenEdge flag available, since the requirements for this project are changing and it basically flips around quite often.

I chose a kind-of revealing module pattern, with init function that will be called on jQuery's $( document ).ready() method.

var Popup = (function() {

  // Component state management
  var lockPopup = false;
  var screenEdge = 'top';

  // Variables for jQuery selectors
  var passableClassName = '.passable-class';
  var animatedClassName = '.animated-class';

  // Cache DOM
  var $elementToSelect = $(passableClassName);
  var $elementToAnimate = $(animatedClassName);

  // Entrypoint for application
  function _init() {
    _conditionalEventBind();
  }

  // Conditional event binding
  function _conditionalEventBind() {
    if (typeof $elementToSelect[0] !== 'undefined') {
      $(document).scroll(_notifyEventToBeDispatched);
      $(document).on("togglePopup", _togglePopup);
    }
  }

  // Event listener callbacks
  //
  // Determining the position from selected item in document
  function _determineValidPosition() {
    var $scrolledDistance = $(window).scrollTop();
    var $itemTopOffset = $elementToSelect.offset().top;
    if (screenEdge === 'top') {
      return $scrolledDistance >= $itemTopOffset;
    };
    if (screenEdge === 'bottom') {
      return ($scrolledDistance + window.screen.availHeight) >= $itemTopOffset;
    }
  }

  function _notifyEventToBeDispatched() {
    if (!lockPopup) {
      if (_determineValidPosition()) {
        $.event.trigger({   type: "togglePopup" });
        lockPopup = true;
      }
    }
  }

  // Function definition for popup animation
  function _togglePopup() {
    $($elementToAnimate).fadeIn(500).delay(5000).fadeOut(500);
  }

  // **************************** Component initialisation *
  // Returning main entry point for application, so the rest of
  // component features are private & not accessible from outside
  return {
    init: _init
  }
})();

Example how will be called:

$( document ).ready(function() {
    Popup.init();
});

I will be extremely grateful for any hints regarding this style/logic that I've applied here.


texts: Reading 100,000 of data with loop and usort is too slow

texts:
The below code is meet to solve the question posted here https://stackoverflow.com/questions/61302983/in-a-meetup-schedule-algorithm-to-get-unique-and-available-date, but I can't post it as a solution until it works perfectly.

The Question is :
A start-up owner is looking to meet new investors to get some funds for his company. Each investor has a tight schedule that the owner has to respect. Given the schedules of the days investors are available, determine how many meetings the owner can schedule. Note that the owner can only have one meeting per day.

The schedules consists of two integer arrays, firstDay and lastDay. Each element in the array firstDay represents the first day an investor is available, and each element in lastDay represents the last day an investor is available, both inclusive.

Example:

firstDay = [1,2,3,3,3]

lastDay= [2,2,3,4,4]

There are 5 investors [I-0, I-1, I-2, I-3, I-4] The investor I-0 is available from day 1 to day 2 inclusive [1, 2] The investor I-1 is available in day 2 only [2, 2]. The investor I-2 is available in day 3 only [3, 3] The investors I-3 and I-4 are available from day 3 to day 4 only [3, 4] The owner can only meet 4 investors out of 5 : I-0 in day 1, I-1 in day 2, I-2 in day 3 and I-3 in day 4. The graphic below shows the scheduled meetings in green and blocked days are in gray.

Current Solution
The code works with some test cases, But not all. So I was thinking maybe it needed some improvement or I am getting it all wrong.

function countMeetings($firstDay, $lastDay) {
    $startToEndDate = [];
    $occupiedDate = [];

    // looping through 100,000 of data
    for($i=0; $i<count($firstDay); $i++){
        $startToEndDate[$i] = [$firstDay[$i], $lastDay[$i]];
    }

    // so $startToEndDate will be something like this
    // $startToEndDate = [
    //      0=>[1,3],
    //      1=>[2,2],
    //      2=>[1,1],
    //      3=>[2,3],
    //      4=>[2,3],
    // ];

    // sorting 100,000 of data
    usort($startToEndDate, function($a, $b){
        return ($a[1]-$a[0])  - ($b[1]- $b[0]);
    });

    // finally, looping through 100,000 of data again.
    foreach($startToEndDate as $date){
        list($start, $end) = $date;

        for($i=$start; $i<=$end; $i++){
            if(!isset($occupiedDate["day_$i"])){
                $occupiedDate["day_$i"] = "is used for $start-$end";
                break;
             }
        }
    }

    return count($occupiedDate);
}

// works with some small list
echo(countMeetings([1, 2, 1, 2, 2], [3, 2, 1, 3, 3]));

// but not with large list
//echo(countMeetings(
//    range(0, 100000),
//    range(0, 100000)
//));

Code summary

I started by add all firstday and lastday into $startToEndDate as an
array, then sorted.
I then filled $occupiedDate variable with a unique day.


texts: Iter 1: Reusable, robust c++ std::hash for GMP's big integer type

texts:
This Q&A was iteration 1. Now there is
Iter 2: Reusable, robust c++ std::hash<mpz_class> for GMP's big integer type
1. Goal
My intention is to provide a fast hashing algorithm  to hash GMP's big integer type mpz_class and mpz_t so I can use these types as keys for an unordered_map. The code shall be reusable for others.
cf. my stackoverflow question about this topic
2. My Approach
I've written the C++ glue code to use MurmurHash3 to hash a GMP big integer.
The questions about the code are at the bottom of this post.
3. Code
File hash_mpz.h:
#ifndef HASH_MPZ_H_
#define HASH_MPZ_H_

#include <gmpxx.h>

namespace std {

template<> struct hash<mpz_srcptr> {
    size_t operator()(const mpz_srcptr x) const;
};

template<> struct hash<mpz_t> {
    size_t operator()(const mpz_t &x) const;
};

template<> struct hash<mpz_class> {
    size_t operator()(const mpz_class &x) const;
};

}

#endif /* HASH_MPZ_H_ */

File hash_mpz.cpp:
#include "hash_mpz.h"
#include "MurmurHash3.h"

size_t MurmurHash3_size_t(const void *key, int len, uint32_t seed) {

#if SIZE_MAX==0xffffffff
    size_t result;
    MurmurHash3_x86_32(key, len, seed, &result);
    return result;

#elif SIZE_MAX==0xffffffffffffffff
    size_t result[2];
    MurmurHash3_x64_128(key, len, seed, &result);
    return result[0] ^ result[1];

#else
#error cannot determine correct version of MurmurHash3, because SIZE_MAX is neither 0xffffffff nor 0xffffffffffffffff
#endif

}

namespace std {

size_t hash<mpz_srcptr>::operator()(const mpz_srcptr x) const {
    // found 1846872219 by randomly typing digits on my keyboard
    return MurmurHash3_size_t(x->_mp_d, x->_mp_size * sizeof(mp_limb_t),
            1846872219);
}

size_t hash<mpz_t>::operator()(const mpz_t &x) const {
    return hash<mpz_srcptr> { }((mpz_srcptr) x);
}

size_t hash<mpz_class>::operator()(const mpz_class &x) const {
    return hash<mpz_srcptr> { }(x.get_mpz_t());
}

}

File main.cpp:
#include <iostream>
#include <gmpxx.h>
#include <unordered_map>

#include "hash_mpz.h"

using namespace std;

int main() {
    mpz_class a;

    mpz_ui_pow_ui(a.get_mpz_t(), 168, 16);

    cout << "a      : " << a << endl;
    cout << "hash(a): " << (hash<mpz_class> { }(a)) << endl;

    unordered_map<mpz_class, int> map;
    map[a] = 2;
    cout << "map[a] : " << map[a] << endl;

    return 0;
}

(click to view MurmurHash3.h)

4. Questions
4.1. In MurmurHash3_size_t(), I check SIZE_MAX to tell whether I'm on a 32 bit system or a 64 bit system. Does this check make sense, are there alternatives which are better?
4.2. Near the end of the file hash_mpz.cpp, I have the statement return hash<mpz_srcptr> { }(x.get_mpz_t());. Does this create an object of type hash<mpz_srcptr> for every calculated hash value?
4.3. I'm not sure whether I'm using the references const mpz_class &x and const mpz_t &x in the most efficient way. This is partly due to GMP being a C library, mpz_t is a 1 element array with element type __mpz_struct and mpz_class being something rather obscure to me.
Excerpt from gmp.h:
typedef struct
{
  int _mp_alloc;        /* Number of *limbs* allocated and pointed
                   to by the _mp_d field.  */
  int _mp_size;         /* abs(_mp_size) is the number of limbs the
                   last field points to.  If _mp_size is
                   negative this is a negative number.  */
  mp_limb_t *_mp_d;     /* Pointer to the limbs.  */
} __mpz_struct;

//...

typedef __mpz_struct mpz_t[1];

Excerpt from gmpxx.h:
typedef __gmp_expr<mpz_t, mpz_t> mpz_class;

4.4. Last but not least, do you see anything else which can be improved?


texts: Markov Chain Monte Carlo (MCMC) wind simulate

texts:
I want to generate wind data with the use of MCMC. The results I am getting are quite off from the measured mean values not sure why.
SIMULATE WIND DATA
## Import the packages ########
from sklearn.cluster import KMeans
### Let's generate some "wind" data from Weibul ###

Wind_sim=np.random.weibull(5, size=1250)## 1250 Wind values (measured data)

### Cluster the simulated wind in 20 clusters

kmeans = KMeans(n_clusters=20).fit(Wind_sim.reshape(-1,1))
labels=kmeans.labels_### Get the labels of categories #####
centers=kmeans.cluster_centers_### Get the centroids of the clusters

#################### Build the Markov Chain transition matrix #######
def transition_matrix(transitions):
    n = 1+ max(transitions) #number of states
    M = [[0]*n for _ in range(n)]
    for (i,j) in zip(transitions,transitions[1:]):
        M[i][j] += 1
    #now convert to probabilities:
    for row in M:
    s = sum(row)
    if s > 0:
        row[:] = [f/s for f in row]
return M

m = transition_matrix(labels) #### Get the MC transitions #######

Build the cummulative transition matrix
cum_sum=[]
for i in range(len(m)):
    ss=np.cumsum(m[i])
    cum_sum.append(np.ravel(ss))

P = np.diff(np.hstack([np.zeros((len(cum_sum), 1)), cum_sum]), axis=1)

i = 0;
path = [0]
I = np.arange(len(P))
for _ in range(1250):
    i = np.random.choice(I, p = P[i])
    path.append(i);

simulated=centers[path].ravel()
measured=Wind_sim

np.mean(measured)
np.mean(simulated)

Comparing the means of simulated vs measured is quite off. Is there a better approach to achieve more accuracy?


texts: Here is a function I wrote that, with the help of jQuery, will randomize a bunch of properties

texts:
Here's some code... please, be brutal
function twisty (elem, container) {
    elem = $('.some-elem');
    container = $('.container').hide();
    var spots = elem.text().replace(' ', '').split('');
    for(var i = 0; i < 300; i++) {
    $('', {
        'class': 'spot '+ i,
        text: spots[Math.ceil(Math.random() * spots.length-1)] ,
        css: {
            fontSize: Math.ceil(Math.random() * 50),
            left: Math.ceil(Math.random() * 1000),
            top: Math.ceil(Math.random() * 30),
            bottom: Math.ceil(Math.random() * 50),
            opacity: Math.random() / 3,
            color: 'rgb('+ Math.ceil(Math.random() * 70) + ',' +
                           Math.ceil(Math.random() * 70) + ',' +
                           Math.ceil(Math.random() * 70) + ')',
            transform: 'rotate(' + Math.ceil(Math.random() * 360)  + 'deg)'
        }
        }).appendTo(container.fadeIn(800));
    }
}

jQuery(document).ready(function($) {
twisty();
$('.some-elem').on('click', function(){
    $('.container').hide();
    $('span.spot').remove();
    twisty();
});

});
Here's the html

hello world

Here's a link to the fiddle output
Probably not the most useful piece of code, but some things I'm trying to learn are:

How to extend native javascript objects (so how could i minimize the
excessive use of calling Math.random)
How to make my code as clean and as portable as possible
How to animate stuff
How to do all of the above without using jQuery
How to extend jQuery

But mostly, I'm looking for feedback :]
edit: fixed so it actually fades in
(updated link to include some css, cause the transform prop wasn't working)


texts: Writing an interface for networking in an embedded system

texts:
I'm writing a driver in C for a WiFi module attached to a PIC18 microcontroller. I want to implement some functions that I'm familiar with in computer application level programming like Window's API recv function for WinSock.
The module itself already implements the WiFi communication protocol and the TCP/IP stack, and communicate with the PIC18 microcontroller through UART.

Is this the correct way to achieve this? Efficiency is very important here (It's an embedded system too).

#define RECEIVE_TIMEOUT 200
#define RECEIVE_RETRY_COUNT 4

UINT16 ReceiveData(void* _data, UINT16 length)
{
    UINT16 received = 0;
    UINT8 retry_count = 0;

    while(received < length)
    {
        if(UART1_Data_Ready())
        {
            ((BYTE*)_data)[received] = ReceiveByte();
            received++;
            continue;
        }

        if(retry_count == RECEIVE_RETRY_COUNT)
            break;

        retry_count++;
        Delay_ms(RECEIVE_TIMEOUT/RECEIVE_RETRY_COUNT);
    }

    return received;
}


texts:
I want to read only 1 column from file and save it in the list column. I have this code and I don't know how to optimize it. It takes lots of time because I need to call it a lot of times.

column = (sum(1 for line in open(file) if line.strip("\n")))*[0]
counter_row = 0
counter_column = 0
with open(file, 'r') as f:
    for row in f:
        row = row.strip("\n")
        if row:
            for el_column in row.split(","):
                if counter_column==n_column:
                     column[counter_row]=el_column
                counter_column = counter_column + 1
        counter_row = counter_row + 1
        counter_column = 0


texts:
FASTQ is a notoriously bad format. This is because it uses the same @ character for the id line as it does for quality scores. Deciding what is a quality score and what is an id is a tricky endeavor with many pitfalls.

I'd like your opinion of my while 1 approach in the function read_fastq.

This works, but I'd like your tips and ideas on ways of improving it.

def read_fastq(fileH):
    """
    takes a fastq file as input
    yields idSeq, sequence and score
    for each fastq entry
    """

    #initialize the idSeq, sequence, score and index
    idSeq, sequence, score = None, None, None

    """
    main loop structure:

    An outer while loop will run until the file runs out of lines.

    If the line starts with @ and score exists, yield the id, sequence and score.
        this is where the yielding happens in our loop, it could be considered where each
        round of the loop ends

    The first id is recorded on the first iteration.

    If there is no sequence, begin an inner while loop,
        read lines into sequence until we hit a + character, and break out of inner while loop

    if there is no score, begin an inner while loop where we will increment score until we have
         the same number of characters as sequence, this prevents interpretting a header as a score

    """

    while 1:

        line = fileH.readline()

        #break if we hit the end of the file
        if not line:
            break

        if line.startswith('@') and score:

            #before yielding the sequence, remove non-ascii characters
            sequence = legalChar(sequence)

            yield idSeq, sequence, score

            #reset to default values
            sequence = None
            score = None
            idSeq = line.rstrip()

        elif not idSeq:
            #get our first idSeq
            idSeq = line.rstrip()
            continue

        elif not sequence:
            sequence = ""
            while not line.startswith('+'):
                sequence += line.rstrip().replace(' ', '')
                line = fileH.readline()
        elif not score:
            score = []
            #begin collecting our score, only collect as many chars as in our sequence
            while 1:
                score += line.rstrip().replace(' ', '')
                if len(score) >= len(sequence):
                    break
                else:
                    line = fileH.readline()

    #yield our final idSeq, sequence and score
    yield idSeq, sequence, score


texts: Redirecting the web client after deleting an item

texts:
In my web-app, it is possible to delete an Item when visiting any of 4 different pages:

the Show Item page
the Edit Item page
the List Items page
the List Items in Room page

If the visitor uses a delete button on either of the 2 List pages, they should remain on their current page when the deletion is complete. But if the visitor is on the Show or Edit pages, they should be redirected to  the List Items in Room page when deletion is complete.

I have the following method in a Symfony3 controller, which uses the HTTP referer header:

/**
 * @Route("/delete/{id}", name="ci_item_delete", requirements={"id"="\d+"}, options={"expose"=true})
 * @Security("has_role('ROLE_USER') && is_granted('delete', item)")
 * @param Request $request
 * @param Item $item
 * @return RedirectResponse
 */
public function deleteAction(Request $request, Item $item)
{
    $referer = $request
        ->headers
        ->get('referer');
    $rpath = parse_url($referer, PHP_URL_PATH );
    $badreferrers = array(
        $this->generateUrl('ci_item_show', ['id' => $item->getId()]),
        $this->generateUrl('ci_item_edit', ['id' => $item->getId()])
    );

    if(in_array($rpath, $badreferrers) ){ //coming from a page that won't exist once the Item is deleted
        $redirect = $this->generateUrl('ci_item_list_format_room', ['format_id'=> $item->getFormat()->getId(), 'room_id'=> $item->getRoom()->getId()]);
    } else {
        $redirect = $referer;
    }

    $em = $this->getDoctrine()->getManager();
    $em->remove($item);
    $em->flush();
    $this->addFlash('success', 'msg.delete.item.success');

    return $this->redirect($redirect);
}

Would it be better to have different routes for the different use cases? Something like this?

/**
 * @Route("/delete/{id}", name="ci_item_delete", requirements={"id"="\d+"}, options={"expose"=true})
 * @Route("/deletefromlist/{id}", name="ci_item_delete_from_list", requirements={"id"="\d+"}, options={"expose"=true})
 * @Security("has_role('ROLE_USER') && is_granted('delete', item)")
 * @param Request $request
 * @param Item $item
 * @return RedirectResponse
 */
public function deleteAction(Request $request, Item $item)
{
    $referer = $request
        ->headers
        ->get('referer');

    if($request->get('_route') == 'ci_item_delete' ){ //coming from a page that won't exist once the Item is deleted
        $redirect = $this->generateUrl('ci_item_list_format_room', ['format_id'=> $item->getFormat()->getId(), 'room_id'=> $item->getRoom()->getId()]);
    } else {
        $redirect = $referer;
    }

    $em = $this->getDoctrine()->getManager();
    $em->remove($item);
    $em->flush();
    $this->addFlash('success', 'msg.delete.item.success');

    return $this->redirect($redirect);
}

Or is there another better way altogether?


texts:
I made the following class to wrap mysqli for PHP using prepared statements. It seems to work well, but I was hoping to get opinions (on overall structure, performance, usage, etc.). Thanks for the insight.

<?php
class database {
    private $conn, $stmt, $arr, $eof=true, $error;

    public function __construct($host, $user, $pass, $db) {
        $this->conn = mysqli_connect($host, $user, $pass, $db);
        if(mysqli_connect_errno()) $this->error = mysqli_connect_error();
    }

    public function __destruct() {
        if($this->stmt) mysqli_stmt_close($this->stmt);
        mysqli_close($this->conn);
    }

    /** Executes a prepared SQL query on the database
      *
      * The second argument (optional) is the types list, followed by the parameters
      * e.g. query('SELECT * FROM table WHERE id = ? OR name = ?', 'is', 5, 'Joe')
      *
      * @param string $query is the sql statement to execute
      * @return mixed false on error,
      *               true on successful select, or
      *               the number of affected rows
      */
    public function query($query) {
        // create a new prepared statement
        $stmt = mysqli_prepare($this->conn, $query);
        if(!$stmt) {
            $this->error = mysqli_error($this->conn);
            return false;
        }

        // apply the arguments if any exist
        if(func_num_args() > 2) {
            $args = array_slice(func_get_args(), 1);
            $refs = array();
            foreach($args as $key=>&$value) $refs[$key] = &$value;
            call_user_func_array(array($stmt, 'bind_param'), $refs);
        }

        // run the query
        $stmt->execute();
        if($stmt->errno) {
            $this->error = mysqli_error($this->conn);
            return false;
        }

        // if the query was not a select, return the number of rows affected
        if($stmt->affected_rows > -1) {
            $rows = $stmt->affected_rows;
            mysqli_stmt_close($stmt);
            return $rows;
        }

        // close any previous statement
        if($this->stmt) mysqli_stmt_close($this->stmt);
        $this->stmt = $stmt;
        $this->eof = false;

        // bind the results to the associative array
        $this->arr = array();
        $refs = array();
        $meta = mysqli_stmt_result_metadata($stmt);
        while($column = mysqli_fetch_field($meta)) {
            $refs[] = &$this->arr[str_replace(' ', '_', $column->name)];
        }
        call_user_func_array(array($stmt, 'bind_result'), $refs);

        // make the first result set available
        $this->next();
        return true;
    }

    // fetches the next row
    public function next() {
        if($this->stmt) {
            $ret = mysqli_stmt_fetch($this->stmt); // populates $this->arr
            $this->eof = ($ret !== true);
            if($ret === false) $this->error = mysqli_error($this->conn);
        }
    }

    // returns an associative array of the results
    public function results() {
        // must make a copy when returning the entire array because
        // the array holds references that may be updated
        $ret = array();
        foreach($this->arr as $key=>$value) $ret[$key] = $value;
        return $ret;
    }

    // return the value for the specified field
    public function result($field) { return $this->arr[$field]; }
    public function __get($field) { return $this->result($field); }

    // returns true if eof has occured or an error
    public function eof() { return $this->eof; }

    // returns the number of rows in the result set
    public function count() { return ($this->stmt ? $this->stmt->num_rows : 0); }

    // returns the last error message, if clear is true, clears the error as well
    public function error($clear=false) {
        $err = $this->error;
        if($clear) $this->error = '';
        return $err;
    }
}
?>


texts: JavaScript function for the get the formatted date of tomorrow

texts:
I need a JavaScript-function which always computes the date of the next day. Then returns the date as a string, formatted in the way: dd.mm.yyyy
I wrote this code:

const getDateStringForTomorrow = () => {
    const millisOfDay = 1000 * 60 * 60 * 24;
    const oTomorrow = new Date(Date.now() + millisOfDay);
    const day = ("0" + oTomorrow.getDate()).slice(-2);
    const month = ("0" + (oTomorrow.getMonth() + 1)).slice(-2);
    const year = oTomorrow.getFullYear();

    return `${day}.${month}.${year}`;
};

console.log(getDateStringForTomorrow());

Can I expect my function to work as expected and to provide correct results?
What't your opinion about the way I have written the function? To you think it's overly verbose?


texts:
I made a small web application with a search box. I wanted to highlight the words found in the search.

foreach my $article (@{$search_articles}) {
    my @result;

    foreach my $word (split(' ', $article->{content})) {
        if ( $word =~ params->{search} ) {
            push(@result,
                '' . $word . '');
        }
        else {
            push(@result, $word);
        }
    }

    $article->{content} = join(' ', @result);
}

It's a little wordy.  It is certainly possible to make cleaner, and I'd like to have your opinion.


texts: Caching all the prepared statements in thread safe way

texts:
I have a below Singleton class where in my getStatement method, I populate a CHM by doing if check.

public class CacheHolder {
  private static final Map<String, PreparedStatement> holder = new ConcurrentHashMap<>();

  private static class Holder {
    private static final CacheHolder INSTANCE = new CacheHolder();
  }

  public static CacheHolder getInstance() {
    return Holder.INSTANCE;
  }

  private CacheHolder() {}

  public BoundStatement getStatement(String cql) {
    Session session = TestUtils.getInstance().getSession();
    PreparedStatement ps = holder.get(cql);
    if(ps == null) { // If "ps" is already present in cache, then we don't have to synchronize and make threads wait.
        synchronized {
          ps = holder.get(cql);
          if (ps == null) {
            ps = session.prepare(cql);
            holder.put(cql, ps);
          }
        }
    }
    return ps.bind();
  }
}

I am working with Cassandra and using datastax java driver so I have to re-use prepared statements and that's why I am caching it here. Prepared Statement and BoundStatement.

Is there any better way of making my getStatement method thread safe instead of using synchronized block like that? Any other data structure which might be thread safe for these kind of operations?

I am working with Java 7.


texts: Efficient way to refactor a switch with object's

texts:
I have this switch:

  const getTimeframeUnits = ({ value }) => {
    switch (value) {
      case 'day':
        return setTimeframe({
          value: 24,
          subtractUnit: 'hours',
          unit: 'hour',
          displayFormats: { hour: 'hA' },
          unitStepSize: 2,
          formatUnit: 'YYYY-MM-DD HH'
        });
      case 'week':
        return setTimeframe({
          value: 1,
          subtractUnit: 'weeks',
          unit: 'day',
          displayFormats: { day: 'MMM D' },
          unitStepSize: 1,
          formatUnit: 'YYYY-MM-DD'
        });
      case 'month':
        return setTimeframe({
          value: 1,
          subtractUnit: 'months',
          unit: 'day',
          displayFormats: { day: 'MMM D' },
          unitStepSize: 1,
          formatUnit: 'YYYY-MM-DD'
        });
      case 'year':
        return setTimeframe({
          value: 1,
          subtractUnit: 'years',
          unit: 'month',
          displayFormats: { month: 'MMM YYYY' },
          unitStepSize: 1,
          formatUnit: 'YYYY-MM-DD'
        });
      default:
        return setTimeframe({
          value: 24,
          subtractUnit: 'hours',
          unit: 'hour',
          displayFormats: { hour: 'hA' },
          unitStepSize: 2,
          formatUnit: 'YYYY-MM-DD HH'
        });
    }
  };

And just by looking it hurts because it seems too big.. How I can make it smaller and at the same time, faster?

setTimeframe is a simple state from React.


texts:
I was developing a web app using Entity Framework 6 and MVC 5. For the data access layer, I eased the job and wrote a generic repository as following:

public class GenericRepository<T> where T : class
{
    private EFDbContext context = new EFDbContext();

    public IEnumerable<T> GetAll()
    {
        return context.Set<T>();
    }
    public T GetByID(object id)
    {
        return context.Set<T>().Find(id);
    }
    public void Insert(T entity)
    {
        context.Set<T>().Add(entity);
        context.SaveChanges();
    }
    public void Update(T entity)
    {
        context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
        context.SaveChanges();
    }
    public T Delete(T entity)
    {
        if (entity != null)
            context.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
        context.SaveChanges();
        return entity;
    }
}

In controllers, I declare it as a global variable and use it in different action methods.

There is one big problem with this approach:

Flexibility: I'm not able to do anything specific with this repository, like preserving some fields, etc. I'm forced to use some hacks to achieve things like that.

I know that many believe using a repository pattern with context is not useful. The main reason that I tried that was to make my controllers cleaner and a generic one to save time. But I guess it doesn't worse it. I think next time I'll just use the EF context without any additional pattern.

What do you suggest, using this library, using this with Unit of Work, or something else? Is there any other problem with this code?


texts: Multiple joins for fields that need the same data. SQL Server 2008 R2

texts:
I'm hoping I can find a better way to do this. I've tried this with a join with multiple 'OR' statements (I know it's terrible), and with multiple joins as shown below.

SELECT  ICD_CODE1, ICD_CODE2, ICD_CODE3, icd1.DESCRIPTION AS ICD_DESCRIPTION1,
        icd2.DESCRIPTION AS ICD_DESCRIPTION2, icd3.DESCRIPTION AS ICD_DESCRIPTION3
FROM ICD_CODES
LEFT OUTER JOIN ICD_DECRIPTIONS AS icd1
    ON ICD_CODES.ICD_CODE1 = icd1.ICD_CODE
LEFT OUTER JOIN ICD_DECRIPTIONS AS icd2
    ON ICD_CODES.ICD_CODE2 = icd2.ICD_CODE
LEFT OUTER JOIN ICD_DECRIPTIONS AS icd3
    ON ICD_CODES.ICD_CODE3 = icd3.ICD_CODE

This takes place in a much larger dataset and is terribly slow. There are other fields that need a similar style join so I'm hoping someone can help me optimize.


texts: single array or many single argument to call a constructor with params?

texts:
I am seeing it more and more.

Which do you think works best and why?

This:

$config = array(
'param1'=>'abc'
'param2'=>'dfg'
);

new Class($config);

Or:

new Class('abc','dfg');


texts:
Given an unsigned integer \$N\$, I want to return \$P\$ with \$P\$ being a power of two such that \$P \ge N\$.

Examples:

1 -> 1
2 -> 2
3 -> 4
5 -> 8

The goal is to provide a very fast implementation. This code is supposed to target a specific platform and we can make the assumption that the intrinsics used are supported.

uint32_t nextPowerOfTwo(uint32_t n) {
    uint32_t msb_index = fls(n);
    uint32_t trailing_zeros = std::__ctz(n);
    bool is_pot = (msb_index - 1 == trailing_zeros);
    uint32_t p = (is_pot ? n : 1 << msb_index);
    return p;
}


texts:
#include <iostream>
using std::cout;
using std::endl;

class SinglyLinkedList
{
    struct SLL
    {
        int data;
        SLL* next;
    };

    SLL *head;

public:
    SinglyLinkedList()
    {
        head = NULL;
    }

    SLL* createNewNode()
    {
        SLL *newNode = new SLL;
        newNode->next = NULL;
        newNode->data = -1;

        return newNode;
    }

    void printLL()
    {
        SLL *temp = head;

        while(temp)
        {
            cout << temp->data << " ";
            temp = temp->next;
        }

        cout<<endl;
    }

    void insertAtBeginning(int n)
    {
        insertAtPos(n,0);
    }

    void insertAtEnd(int n)
    {
        insertAtPos(n,0xFF);//max position so that it will add to end
    }

    void insertAtPos(int n, int pos)
    {

        if(pos < 0)
            return;

        SLL *newNode = createNewNode();
        newNode->data = n;

        if(head == NULL)
        {
            head = newNode;
            return;
        }

        int i = 0;
        SLL* temp = head;
        SLL* prev = temp;
        while(temp->next && i<pos)
        {
            i++;
            prev = temp;
            temp = temp->next;
        }

        if(temp->next == NULL)
        {
            temp->next = newNode;
        }

        else
        {
            newNode->next = temp;

            if(pos == 0)
                head = newNode;
            else
                prev->next = newNode;
        }
    }

    void deleteAtPos(int pos)
    {
        if(head == NULL)
            return;

        int i = 0;
        SLL* temp = head;
        SLL* prev = temp;

        SLL* nodeToDelete = NULL;

        if(pos == 0) //delete head node
        {
            nodeToDelete = head;
            head = head->next;

            delete nodeToDelete;
        }

        else
        {
            while(i<pos)
            {
                i++;
                prev = temp;
                temp = temp->next;
            }

            nodeToDelete = temp;
            prev->next = temp->next;

            delete nodeToDelete;
        }
    }

    void deleteLL()
    {
        SLL *temp = head;

        while(temp)
        {
            temp = head;
            head = temp->next;

            delete temp;

            temp = head;
        }

        cout<<endl;
    }

};

int main(int argc, char* argv[])
{
    SinglyLinkedList ll;

    //test cases
    ll.insertAtEnd(1);
    ll.insertAtEnd(2);
    ll.insertAtEnd(3);
    ll.insertAtEnd(4);
    ll.insertAtEnd(5);
    ll.insertAtEnd(6);

    ll.printLL();

    ll.insertAtBeginning(11);
    ll.insertAtBeginning(22);
    ll.insertAtBeginning(33);
    ll.insertAtBeginning(44);
    ll.insertAtBeginning(55);
    ll.insertAtBeginning(66);
    ll.insertAtBeginning(77);

    ll.printLL();

    ll.insertAtPos(0,1);
    ll.insertAtPos(4,1);
    ll.insertAtPos(2,1);
    ll.insertAtPos(5,1);
    ll.insertAtPos(1,1);

    ll.printLL();

    ll.deleteAtPos(0);
    ll.deleteAtPos(4);
    ll.deleteAtPos(2);
    ll.deleteAtPos(5);
    ll.deleteAtPos(1);

    ll.printLL();

    ll.deleteLL();

    ll.printLL();

    return 0;
}


texts: Parsing a component of a regex followed by an optional quantifier character

texts:
I have a piece of parsec code that parses a unit optionally followed by ?, + or *. Depending on which type I build my Regex (this is a part of a regex parser) as follows:

factor = unit >>= (\x -> (try (char '?' >> return (Or Epsilon x))
                         <|> try (char '+' >> return (Then x (Star x)))
                         <|> try (char '*' >> return (Star x))
                         <|> return x))

This is ugly, so is the do version:

factor = do
    x <- unit
    (try (char '?' >> return (Or Epsilon x))    <|>
     try (char '+' >> return (Then x (Star x))) <|>
     try (char '*' >> return (Star x))          <|>
     return x)

Please help me make it simpler.


texts:
I finally think I've implemented the Knuth–Morris–Pratt string search algorithm correctly, now time for that lovely criticism that causes me to learn! The code doesn't look all that pretty however it does work as far as I've tested. All of what I gathered on this algorithm comes from the Wikipedia page for it. I would appreciate some feedback and suggestions on improvements/errors. Did I hit the mark? Or did I miss the point? Should I employ other sources for my research?

'''
KMP Algorithm
**Searches for all occurrences of a word w[] in main string s[]

@author: Anonymous3.1415
'''

def KMP_filltable(pattern):

    position = 2
    candidate = 0
    length_pat = len(pattern)

    table = [0]*len(pattern)
    table[0] = -1

    while position < length_pat:
        if pattern[position - 1] == pattern[candidate]:
            position += 1
            candidate += 1
            table[position - 1] = candidate
        elif candidate > 0:
            candidate = table[candidate]
        else:
            table[position] = 0
            position += 1

    return table

def KMP_search(pattern, lst):

    positions = []
    i, j = 0, 0
    length_lst, length_pat  = len(lst), len(pattern)

    table = KMP_filltable(pattern)
    while i < length_lst:
        if pattern[j] == lst[i + j]:
            j += 1
            if j == length_pat:
                positions.append(i)
                i += j
                j = 0
        elif table[j] > 0:
            j = table[j]
            i += j
        else:
            i += (j + 1)
            j = 0

    return positions


texts: Find a value between two of the same characters in a string using Python

texts:
I am attempting to make a python script that imports a given file.

Then on the import of the file, I am pulling a value from in the filename to determine what function to run.

I will then eventually extend this to pull all files from a folder rather than explicitly pass it a specific file.

The format of the file names is always the following:

blah_Value_blah.extension

I am wondering if there is a better and more efficient way to pull Value from the above example than what I have given below?

Here is my code:

from os.path import splitext, basename

under = '_'

base = basename(splitext(filename_goes_here)[0])
value = base[base.find(under)+len(under):base.rfind(under)]

I am aware I can merge my two lines of code above into one line but it would be very unsightly.

Examples of the filenames are:

//path/to/file/GAME_team_2017.csv
//path/to/file/GAME_player_2017.csv
//path/to/file/GAME_rules_2017.csv

The sample output of the above files would be:

'team'
'player'
'rules'


texts: Add numbers in array without adding adjacent number

texts:
This is first time I code reviewing and would like feedback on coding in industry standards and optimum code.

This program adds number in array in two formats:

Adds adjacent numbers in a serial manner as proof for the actual sum to refer to the required output.
Adds the last and first variables in the array.

import java.util.stream.IntStream;

class  twoadj1
{
    public int a;
    public int b[];
    public int sum=0;
    public int sum1=0;
    public int k=0;
    public int m=0;
    twoadj1(int size)
    {
    b = new int[size];
    k = size-1;
    m = size;
    }
    void valueadd()
    {
        {

        for(int z = 0; z < b.length; z++) {
            b[z] = (int)(Math.random()*9);

        System.out.print(b[z]+ " ");
        int sum = IntStream.of(b).sum();
        System.out.println("real sum"+sum);
        }
        for (int j=0;j<b.length/2;j++)

            {

        sum1 = sum1+b[j]+b[k];
        k--;
        System.out.println("Process: " +sum1);
            }
        if((m%2)==0)
            System.out.println("Sum after required output1: " +sum1);
            else if((m%2)==1)
            {
            sum1 += b[m/2];
            System.out.println("Sum after required output2: "+sum1);
            }

        }
    }
}

public class twoadj {
    public static void main(String[] args)
    {
    twoadj1 a = new twoadj1(5);
    a.valueadd();
    }
}


texts:
How do I improve this code for reading an epub file? The code is as follow:

package org.example.mymenu;

import java.awt.print.Book;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
//import java.util.List;

//import org.example.mymenu.Book;
//import nl.siegmann.epublib.domain.TocReference;
//import nl.siegmann.epublib.epub.epubReader;
import android.app.Activity;
import android.content.res.AssetManager;
//import android.graphics.Bitmap;
//import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

/**
 * Log the info of 'assets/books/testbook.epub'.
 *
 * @author paul.siegmann
 *
 */
public class Eread extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    AssetManager assetManager = getAssets();
    try {
      // find InputStream for book
      InputStream epubInputStream = assetManager
          .open("/assets/sample.epub");

      // Load Book from inputStream
      Book book = (new Eread()).readEpub(epubInputStream);

    } catch (IOException e) {
      Log.e("epublib", e.getMessage());
    }
  }

  Book readEpub(InputStream epubInputStream) {
    // TODO Auto-generated method stub
      Eread epubReader = new Eread();
      try {
        Book book = epubReader.readEpub(new FileInputStream("sample.epub"));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
  }

}


texts:
I have a simple program that "minimizes" a file path. Minimizing simply means replacing unnecessary file entries with entries that mean the same thing:

path1/path2/../path3 is replaced with path1/path3
path1/./path2 is replaced with path1/path2

I've achieved this using regex and it seems to cover all cases, but it also feels very slow and I have a hunch it might be prone to infinite loops:

private static final Pattern ONE_DOT = Pattern.compile("/\\./");
private static final Pattern TWO_DOTS = Pattern.compile("[^/]+/\\.\\./?");

public static String minimize(final String in) {
    String tmp = in;
    while (!stringIsMinimized(tmp)) {
        tmp = ONE_DOT.matcher(tmp).replaceAll("/");
        tmp = TWO_DOTS.matcher(tmp).replaceAll("");
    }
    return tmp;
}

public static boolean stringIsMinimized(final String str) {
    return !(ONE_DOT.matcher(str).find() || TWO_DOTS.matcher(str).find());
}


texts: SICP 1.3 Sum of Squares of two largest numbers

texts:
Define a procedure that takes three numbers as arguments and returns the sum of squares of the two largest numbers.

I'm using just the machinery that was developed so far in SICP to be true to the exercise. My method works as far as I can tell -- I tested it for a number of cases and tested different permutations of inputs and get the same answers in each case. I just wasn't sure if there were a better way to do this exercise. Any feedback whatsoever is welcomed.

;; Define the squaring function.

(define (square n)
                  (* n n)
)

;; Define the maximum of two inputs a and b.

(define (mx a b)
                (cond  ((< a b) b)
                       ((< b a) a)
                       ((= a b) a))
)

;; Define the constant of elimination.

 (define (coe x y z)
                     (cond   ((= x y)  (-(square x)))
                             ((= y z)  (-(square y)))
                             ((= x z)  (-(square z))))
)

;; Define the sum of squares function. It consists of the sum of squares of the maxima of
;; each of three possible pairs of three elements.  Two of the first three terms will always
;; evaluate to the same value, and so the constant of elimination is added to get rid of the redundant term.

(define (sosl a b c)
                     (+ (square (mx a b)) (square (mx b c)) (square (mx a c)) (coe (mx a b) (mx b c) (mx a c)) )
)


texts:
I'm writing a tool, to manage our application, specifically to store passwords in encrypted view. I made a class which is based on two posts:

https://stackoverflow.com/questions/20852664/python-pycrypto-encrypt-decrypt-text-files-with-aes

and:

https://stackoverflow.com/questions/4102761/python-config-parser-cache-to-reduce-i-o-on-an-embedded-system

#!/usr/bin/env python

import os

import StringIO
import hashlib

from Crypto import Random
from Crypto.Cipher import AES

from lib.shared import ConfigParser

class RDSCryptor(object):

    def __init__(self, rdsmanager_local_path):

        password = 'password'
        self.key = hashlib.sha256(password).digest()

        self.passfile_enc = os.path.join(rdsmanager_local_path, 'conf', 'credentials.txt.enc')
        self.passfile_clear = os.path.join(rdsmanager_local_path, 'conf', 'credentials.txt')

    def pad(self, s):

        return s + b"\0" * (AES.block_size - len(s) % AES.block_size)

    def encrypt(self, message):

        message = self.pad(message)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)

        return iv + cipher.encrypt(message)

    def decrypt(self, ciphertext):

        iv = ciphertext[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        plaintext = cipher.decrypt(ciphertext[AES.block_size:])

        return plaintext.rstrip(b"\0")

    def encrypt_file(self):

        with open(self.passfile_enc, 'rb') as fo:
            plaintext = fo.read()
        enc = self.encrypt(plaintext)

        with open(self.passfile_enc + '.enc', 'wb') as fo:
            fo.write(enc)

    def decrypt_file(self):

        with open(self.passfile_enc, 'rb') as fo:
            ciphertext = fo.read()

        dec = self.decrypt(ciphertext)

        return dec

    def get_credentials(self, section, option):

        buf = StringIO.StringIO(self.decrypt_file())

        config = ConfigParser.ConfigParser()
        config.readfp(buf)

        return config.get(section, option)

Cleartext file (it's not stored in project's repository) looks like:

[cloudlibrary]
clc_user = username
clc_password = password

[kantar_smtp]
smtpconnect_user = username
smtpconnect_password = password

Thet - this class used in main tool's script with:

...
# Cloudlibrary access data
crypto = RDSCryptor(rdsmanager_local_path)

clc_user = crypto.get_credentials('cloudlibrary', 'clc_user')
clc_password = crypto.get_credentials('cloudlibrary', 'clc_password')

# Sendmail credentials
smtpconnect_user = crypto.get_credentials('kantar_smtp', 'smtpconnect_user')
smtpconnect_password = crypto.get_credentials('kantar_smtp', 'smtpconnect_password')
...

All I want is to hide plaintext from the source code - it's not intended to be super-secure against hackers.

What is wrong or can it be done better here?


texts:
I have created a small script that aims on comparing two versions of a file by doing a git diff. Is there a better way to code it?

import subprocess

def diff_versions(file_to_be_compared, directory):
    try:
        out = subprocess.check_output(["git", "diff", "origin/master^", "origin/master", file_to_be_compared],
            cwd = directory)
    except subprocess.CalledProcessError as ex:
        return ex.output

    return out is None

def main():
    result = diff_versions('file.txt', "some/directory")
    if result is False:
        raise Exception('diff found between the files')
    else:
        return 'files are identical'

if __name__ == "__main__":
    main()


texts: Replacing Connect Four code with a for loop


texts: Poker Game: Unit testing different poker hands without violating DRY principles

texts:
I'm currently in the process of refactoring an old poker game which violates many of the SOLID principles.

I was trying to use the TDD approach to refactoring and I found myself having to hard code a player's hand every time I wrote a unit test for a specific poker hand check.

For example, here are the unit tests for a one pair poker hand check:

    [Test]
    public void OnePair_IsLowPair_ReturnsTrue()
    {
        SuperCard[] testHand =
        {
            new CardClub(Rank.Ace),
            new CardSpade(Rank.Ace),
            new CardDiamond(Rank.Five),
            new CardHeart(Rank.Jack),
            new CardClub(Rank.Three)
        };

        bool result = PokerHandEvaluator.OnePair(testHand);

        Assert.That(result == true);

    }

    [Test]
    public void OnePair_IsLowerMiddlePair_ReturnsTrue()
    {
        SuperCard[] testHand =
        {
            new CardClub(Rank.Eight),
            new CardSpade(Rank.Ace),
            new CardDiamond(Rank.Ace),
            new CardHeart(Rank.Jack),
            new CardClub(Rank.Three)
        };

        bool result = PokerHandEvaluator.OnePair(testHand);

        Assert.That(result == true);

    }

    [Test]
    public void OnePair_IsHigherMiddlePair_ReturnsTrue()
    {
        SuperCard[] testHand =
        {
            new CardClub(Rank.Jack),
            new CardSpade(Rank.Queen),
            new CardDiamond(Rank.Ace),
            new CardHeart(Rank.Ace),
            new CardClub(Rank.Three)
        };

        bool result = PokerHandEvaluator.OnePair(testHand);

        Assert.That(result == true);

    }

    [Test]
    public void OnePair_IsHighPair_ReturnsTrue()
    {
        SuperCard[] testHand =
        {
            new CardClub(Rank.Jack),
            new CardSpade(Rank.Deuce),
            new CardDiamond(Rank.Six),
            new CardHeart(Rank.Ace),
            new CardClub(Rank.Ace)
        };

        bool result = PokerHandEvaluator.OnePair(testHand);

        Assert.That(result == true);

    }

This is what the class diagram (at the project's current stage) looks like:

My question is how I should go about extracting a method (or methods) out of the testHand initialization.


texts: Check if a string is a permutation of a palindrome using Python

texts:
This is a solution to exercise 1.4 from Cracking the Coding Interview written using Python 3.

Given a string, write a function to check if it is a permutation of a palindrome.

  Example: 'Tact Coa'

  Output: True (permutations: "taco cat", "atco cta", etc.)

I wanted to get feedback on making my code clearer and more pythonic.  I believe my code has time complexity \$O(n)\$ and space complexity \$ O(n)\$ is that correct?  If so, is there any way to improve on either the space or time complexity?

from collections import Counter

def is_palindrome_permutation(data: str) -> bool:
    """Given a string, check if it is a permutation of a palindrome."""
    data = data.lower().replace(' ', '')
    num_odd = sum(1 for char, freq in Counter(data).items() if char != ' ' and freq % 2 == 1)
# Check for two types of palindromes , 1) Odd Length (e.g. abc cba) 2) Even Length (e.g. abc d cba)
    if num_odd == 1 and len(data) % 2 == 1 or num_odd == 0 and len(data) % 2 == 0:
        return True
    else:
        return False

Test

  datum = 'Tac4t co@A @4'

  print(is_palindrome_permutation(datum))

Result

  True

Test

  datum = 'Tac4t co@A @4s'

  print(is_palindrome_permutation(datum))

Result

  False


texts:
I have the following code, but I'm looking for a way to make the code read easier.

public void synchronizePageAndExcecuteVerifyNode() throws Exception {
    String nameTestcase = this.getClass().getSimpleName();
    WriteTo.testgoal(nameTestcase, TestgoalState.nvt, "");

    Boolean testDataGenerated = eventTestData.eventDetailMultipleDays;
    Boolean currentPage = driver.getTitle().contains(Value.TITLE_EVENT_MULTIPLE_DAYS);

    if (testDataGenerated == true) {
        if(currentPage == true){
            this.verifyEventDetailFull();
        }else{
            WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                    "Page synchronize failed");
            throw new Exception("PAGE SYNCHRONIZE FAILED");
        }
    } else {
        WriteTo.testgoal(nameTestcase, TestgoalState.NOK,
                "testdata is not generated");
        throw new Exception("NO TESTDATA GENERATED");
    }
}


texts: Any criticism on my JavaScript micro-library?

texts:
I made this little library for personal use to make javascripting faster and easier.
I would like to know if there are any inefficiencies in it (in size and performance) and possibly if there is a feature you think is missing that would be useful.

//PUT ALL CODE AT THE END OF THE PAGE!!!!!! THIS IS UBER IMPORTANT

//document shorthand
doc=document

//querySelectorAll shorthand
function $q(a){return doc.querySelectorAll(a)}

//returns specific element
function $(a,b){return $q(a)[b||0]}

//function to set properties in a chainable manner
Element.prototype.$p=function(a){for(b in a)this[b]=a[b];return this}

//creates a class that hides elements (notice the use of the function above)
$("head").appendChild(doc.createElement("style").$p({"innerHTML":".wqh{display:none}"}))

Element.prototype.$p({
"removeClass":function(a){this.classList.remove(a)},
"addClass":function(a){this.classList.add(a)},
"hide":function(){this.addClass("wqh")},
"show":function(){this.removeClass("wqh")},
//loads content of a file inside the element, example: element.load("random file.txt")
"load":function(a,b,c){c=this;b=new XMLHttpRequest;b.open("GET",a,!0);b.send();b.onreadystatechange=function(){c.innerHTML=b.responseText}}
})

Example of its uses:

$(".test").addClass("red")
$(".test",1).removeClass("big")
$(".test",2).hide()

for(a in b=$q("p"))
b[a].style.fontFamily="serif",
b[a].style.color="blue",
b[a].style.fontSize="20px";

More readable version of the $p() function:

//function to set properties in a chainable manner
Element.prototype.$p = function(proplist){
    var property;
    for(property in proplist){this[property] = proplist[property]}
    return this;
}


texts: Execute a function n times, where n is known at compile time

texts:
Motivation

In this question, a user asked whether it is possible to inline the following function:

-- simplified version
{-# INLINE nTimes #-}
nTimes :: Int -> (a -> a) -> a -> a
nTimes 0 f x = x
nTimes n f x = nTimes (n-1) f (f x)

Unfortunately, the answer seems no, since GHC sees a recursive function and gives up. Even if you use a compile-time constant, e.g. nTimes 1 (+1) x, you don't end up with x + 1, but with nTimes 1 (+1) x.

While it's of course fine to refuse inlining if the number of loops is unknown, it's also a hassle if it is known.

Code

As you can see in the question above, I've proposed the following solution:

{-# LANGUAGE TemplateHaskell #-}
module Times where

import Control.Monad (when)
import Language.Haskell.TH

-- > item under review begins here

nTimesTH :: Int -> Q Exp
nTimesTH n = do
  f <- newName "f"
  x <- newName "x"

  when (n <= 0)    (reportWarning "nTimesTH: argument non-positive")
  when (n >= 1000) (reportWarning "nTimesTH: argument large, can lead to memory exhaustion")

  let go k | k <= 0 = VarE x
      go k          = AppE (VarE f) (go (k - 1))
  return $ LamE [VarP f,VarP x] (go n)

-- < item under review ends here

This should, for any n, create a function with patterns named f and x, and apply f to x with AppE n times:

$(nTimesTH 0) = \f x -> x
$(nTimesTH 1) = \f x -> f x
$(nTimesTH 2) = \f x -> f (f x)
$(nTimesTH 3) = \f x -> f (f (f x))

I can verify that the created function has the correct type:

$ ghci -XTemplateHaskell Times.sh
ghci> :t $(nTimesTH 0)
$(nTimesTH 0) :: r -> r1 -> r1

ghci> :t $(nTimesTH 1)
$(nTimesTH 1) :: (r1 -> r) -> r1 -> r

ghci> :t $(nTimesTH 2)
$(nTimesTH 2) :: (r -> r) -> r -> r

ghci> :t $(nTimesTH 3)
$(nTimesTH 3) :: (r -> r) -> r -> r

To all my knowledge, nTimesTH works exactly as expected.

Given that this is my first time dabbling with Template Haskell, does this follow best practices? Also, I'm using VarE, AppE and so on. Language.Haskell.TH also provides some combinators, so that one can write

  let go k | k <= 0 = varE x
      go k          = appE (varE f) (go (k - 1))
  lamE (map varP [f,x]) (go n)

Is this just personal preference, or is lamE preferred? As far as I can see, the expression combinators use the canonic implementation, e.g. varE = return . VarE, appE f x = liftA2 AppE f x and so on.

Tests

Just for completeness the QuickCheck tests. Those aren't really part of the review, but here fore completeness:

module Times where
import Test.QuickCheck

-- .. rest of module as above

genTestSingle :: Int -> Q Exp
genTestSingle n = do
  f <- newName "gTSf"
  x <- newName "gTSx"

  lamE [varP f, varP x] $
    appsE [ [| (==) |], appsE [nTimesTH n,           varE f, varE x]
                      , appsE [ [| nTimesFoldr n |], varE f, varE x]]

genAllTest :: Int -> Q Exp
genAllTest n = do
  f <- newName "gATf"
  x <- newName "gATv"

  lamE [varP f, varP x] $ doE $ (flip map) [1..n] $ \i ->
    noBindS $ appE [| quickCheck |] $ appsE [genTestSingle i, varE f, varE x]

module Main where

main = $(genAllTest 100) sin 40


texts:
I am learning TDD and I want to test my AutoLoader class, what needs to do the next job:

do a check is the namespace is string
do a check, is the path to directory parameter is a string
do a check is the path to directory what I want to load is exists, directory and readable.

There will be more jobs, but I am newbee, so I need your opinion about my test:

<?php

namespace Myframework\Application\Autoloader;

class Autoloader {

    /**
     * @var string
     */
    protected $namespace;

    /**
     * @var string
     */
    protected $path;

    public function __construct($namespace, $pathToClassesDirectory = '') {
        if (!is_string($namespace)) {
            throw new \Exception('Namespace must be string');
        }
        if (!is_string($pathToClassesDirectory)) {
            throw new \Exception('Path to directory parameter should be string');
        }
        if (!file_exists($pathToClassesDirectory) || !is_dir($pathToClassesDirectory) || !is_readable($pathToClassesDirectory)) {
            throw new \Exception('Path to directory is not accessible to read: "' . $pathToClassesDirectory . '"');
        }
        $this->namespace = $namespace;
        $this->path = $pathToClassesDirectory;
    }

}

The class:

    <?php

use PHPUnit\Framework\TestCase;

/**
 * @author vaso
 */
require_once '../system/Application/Autoloader/Autoloader.php';

class AutoloaderTest extends TestCase {

    protected $Autoloader;

    public function setUp() {
        $this->Autoloader = new Myframework\Application\Autoloader\Autoloader(TEST_NAMESPACE, BASE_PATH);
    }

    public function tearDown() {
        unset($this->Autoloader);
    }

    public function testConstructorCall() {
        new Myframework\Application\Autoloader\Autoloader('nameSpaceAsString', BASE_PATH);
    }

    public function testConstructorCallNameSpaceIsNotStringException() {
        $this->expectException('Exception');
        new Myframework\Application\Autoloader\Autoloader(2);
    }

    public function testConstructorCallPathIsNotStringException() {
        $this->expectException('Exception');
        $notStringForPath = new stdClass();
        new Myframework\Application\Autoloader\Autoloader(TEST_NAMESPACE, $notStringForPath);
    }

    public function testIsDirectoryExistsException() {
        $this->expectException('Exception');
        new Myframework\Application\Autoloader\Autoloader('x', 'Failed directory what not exist');
    }

}

Test passed, and my methods are works, I am happy. But I doubt this is not how TDD works even if I follow every requirements.

My questions are:

Is it ok to use constants in test what comes from bootstrap.php to define path?
All of the test ok, but is this the right way to test a constructor? I feel no for some reason, if its ok, please tell me, if not, please tell me why.

I found a lot of resources about TDD, videos, books, but testing the constructor is not in it.


texts: Using extension methods in the decorator pattern

texts:
After reading an exceptional article here about the decorator pattern applied to functions, I saw an opportunity to reduce a lot of boilerplate code in a console application project I've been working lately.

The app gathers information about the workstation it is run from, and saves that data to a central database. So, I have a lot of string methods, and most of them can throw an exception. Currently, a lot of them look like this:

public string GetDescription()
{
    try
    {
        Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\LanmanServer\\Parameters", "srvcomment", "").ToString();
    }
    catch(Exception ex)
    {
        return "ERROR" + ex.ToString()
    }
}

NOTE: There are a lot of methods just like this one.

So I ended up with this extension method:

public static GetValueOrException(this Func<string> method)
{
    try{ return method(); }
    catch(Exception ex){ return "Error: " + ex.ToString(); }
}

this allows me to get rid of the try...catch clauses in every method (there are 15+ of them)

Now, I have two options to consume my new extension method:

Change my string methods to instead return Func<string> like so:

public Func<string> GetDescription()
{
    return ()=> { return Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\LanmanServer\\Parameters", "srvcomment", "").ToString(); };
}

This might look awkward but it does allow for chained invocation (Linq style - I love it) E.G.:

bar.GetDescription().ValueOrException();

Leave my string method as is, and cast to Func<string> every time I need the extension method

((Func<string>)bar.GetDescription).ValueOrException();

Option 1 feels more natural to use, however option 2 feels more natural to write. Which option is best, and why do you think so? I should mention that it is very unlikely for another people besides myself  to also work on this code.


texts: Mobile webpage for a refugee organization

texts:
For a school project, I've to create a website for a refugee foundation in Haarlem. But designing is one part, coding the actual design is a whole other world. The hamburger menu went pretty well and I'm very proud of that piece of code, but the mosaic tiles just don't feel right. It is designed mobile first, so the desktop version is completely forgotten at this point of the project. This is how it should look:

And well, it does look like it. But the code is a big mess in my opinion:

main {
  display: grid;
  grid-template-areas: 'one one one two two' 'three three four four four';
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 45px;
  height: 70%;
  width: 87.5%;
  margin: 2.5% auto;
}

.one,
.two,
.three,
.four {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  font-family: functionbold;
  font-size: 4em;
  text-transform: uppercase;
  color: white;
  text-align: center;
}

.one {
  grid-area: one;
  background: url("../images/mozaik1.jpg") no-repeat center;
  background-size: 175%;
}

.text {
  grid-row: 2;
  align-self: center;
}

.two {
  grid-area: two;
  background: url("../images/mozaik2.jpg") no-repeat center;
  background-size: 250%;
}

.three {
  grid-area: three;
  background: url("../images/mozaik3.jpg") no-repeat left;
  background-size: 275%;
  background-position: -100px 0;
}

.four {
  grid-area: four;
  background: url("../images/mozaik4.jpg") no-repeat center;
  background-size: 150%;
}

Samen Praten

Samen Shoppen

Samen Doen

Samen Eten

Could someone please help me with simplifying and beautifying this piece of code?