texts: Formatter for converting links in a legacy markup to markdown

texts:
This program converts legacy markup in the form seen in the tests to the resulting markdown seen in the test's respective comment.
The full program is as uploaded as a snippet, or you may see below
let tests = [
  "OneMatch$$$TwoMatch"                  // [One Match](OneMatch)[Two Match](TwoMatch)
, "OneMatch$$$TwoMatch$$$ThreeMatch"     // [One Match](OneMatch)[Two Match](TwoMatch)[Three Match](ThreeMatch)
, "E$$$scapeMatch"                       // Escape Match
, "SimpleMatch"                          // [Simple Match](SimpleMatch)
, "Prefixed$$$MatchyMatch"               // Prefixed [Matchy Match](MatchyMatch)
, "MatchMatchWith$$$Suffix"              // [Match Match With](MatchMatchWith) Suffix
, "MatchesWithPlural$$$s"                // [Matches With Plural](MatchesWithPlural)s
, "This$$$Gets$$$Escaped"                // This Gets Escaped
]

The $$$ delimits valid matches. Furthermore, a match is only valid if it is composed of two or more StartCased words.
Possible matches are checked against a regex and either formatted, or just returned:
function parseWord(word) {
  let linkRE = /\b[A-Z][a-z]+([A-Z][a-z]+)+\b/g
  let validLinks = word.match(linkRE)
  let stripped = word.replace(/\${3}/, '')

  if (validLinks) {
      return formatLinks(validLinks, stripped)
  }

  return _.startCase(stripped)
}

If we are to format the match we find the difference between the matched link and the entire found word. From there we decide whether to add the difference as a prefix or suffix to the link:
function formatLinks(matches, stripped) {
  let formatted_links = []
  for (match of matches) {
      let diff = difference(match, stripped)

      if (isSimpleLink(diff)) {
          formatted_links.push(formatAsSimpleLink(diff))
      } else if (hasPrefix(diff)) {
          formatted_links.push(formatAsPrefixedLink(diff))
      } else if (hasSuffix(diff)) {
          formatted_links.push(formatAsSuffixedLink(diff))
      }
  }

  // There might be multiple links within a word
  // in which case we join them and strip any duplicated parts
  // (which are otherwise interpreted as suffixes)
  if (formatted_links.length > 1) {
      return combineLinks(formatted_links)
  }

  // Default case
  return formatted_links[0]
}

The function, difference, is fast-diff from npm. Which is defined as such:
let result = difference('Good dog', 'Bad dog');
// [[-1, "Goo"], [1, "Ba"], [0, "d dog"]]

Here are the remaining helper functions (or you may view the snippet for the rest):
function combineLinks(links) {
  links.join('').replace(/(?<=\)).*?(?=\[)/g, '')
}

function formatAsSimpleLink(diff) {
  let link = diff[0][1]
  let text = _.startCase(link)
  return `[${text}](${link})`
}

function formatAsPrefixedLink(diff) {
  let link = diff[1][1]
  let text = _.startCase(link)
  let prefix = _.startCase(diff[0][1])
  return `${prefix} [${text}](${link})`
}

function formatAsSuffixedLink(diff) {
  let link = diff[0][1]
  let text = _.startCase(link)
  let suffix = diff[1][1]

  // don't capitalize plurals
  if (suffixIsPlural(suffix) == false) {
      suffix = _.startCase(diff[1][1])
      return `[${text}](${link}) ${suffix}`
  }

  return `[${text}](${link})${suffix}`
}

function isSimpleLink(diff) {
  return diff.length == 1
}

function hasPrefix(diff) {
  return diff[0][0] == 1 && diff[1][0] == 0
}

function hasSuffix(diff) {
  return diff[0][0] == 0 && diff[1][0] == 1
}

function suffixIsPlural(suffix) {
  return suffix.slice(-1) == 's'
}

My main concerns are:

The looping in formatLinks, which is really only useful if the word has a suffix which is also a link
The magic numbers used to check the diff, e.g., diff[0][1]
If there is a better way to tackle the problem.


texts:
I have a problem where, given N terms, the task is to find the k most frequent terms from given N terms. My code is correct, but I have a time limit 10 seconds and my code doesn't pass.

Constraints:

\$0 < N < 300000\$
\$0 < \textrm{term length} < 25\$

N = gets.to_i

if N < 300000 and N
  a=[]

  (0...N).each do |i|
    el = gets
    el_size = el.length
    if el_size < 25 and el_size
      a << el
    end
    i+=1
  end

  k = gets.to_i

  new_array = {}
  size = a.length
  count = 0

  (0..size).each do |i|
    (0..size).each do |j| count += 1 if a[i] == a[j] end
    new_array[a[i]] = count
    count = 0
  end

  s_l = new_array.to_a.sort{|a, b| (b.last > a.last) ? 1 : (b.last < a.last ? -1 : (a.first <=> b.first)) }

  i = 0
  for key, val in s_l
    puts key if i < k
    i += 1
  end
end

And how can I print only key of hash? Currently I use for key, val in hash.


texts: Input reading: two values (separated by whitespace) per line

texts:
Sometimes, I need to read two integer parameters in a single input line, separated by a whitespace.

I have these two functions that seem to do the job just fine:

#include <iostream>
#include <sstream>
#include <deque>

// Splits a string by its whitespaces and returns a deque with each item.
deque<string> split(string original) {
    deque<string> result;
    string buffer;
    stringstream stream(original);
    while (stream >> buffer) {
        result.push_back(buffer);
    }
    return result;
}

// Reads two integer parameters from a single line, separated by a whitespace
void getTwiceInput(int &a,int &b) {
    string input;
    getline(cin,input);
    deque<string> deck = split(input);
    stringstream ss;
    ss << deck[0];
    ss >> a;
    ss.clear();
    ss << deck[1];
    ss >> b;
}

So in my program I do this call:

int x,y;
getTwiceInput(x, y);

Is there an easier way to achieve this? It is a bit tiring having to type all of that just to achieve this for every programming challenge given.


texts: Excel VBA optimizing for large data base

texts:
I am new to coding and need help with a code that won't complete. I suspect it is due to the size of the data set. I tested the code using a reduced data set and it processes fine. However, my actual data set is over 210,000 rows and is expected to grow.
Is there a way to speed this up? Thank you for your assistance

Sub DupValidation()
    Dim wb As Workbook
    Dim ws1 As Worksheet

    Dim i As Long
    Dim lastrow As Long
    Dim lastrow2 As Long

    Set wb = ActiveWorkbook
    Set ws1 = wb.Worksheets("Tickets")

    lastrow = ws1.Cells(Rows.Count, 1).End(xlUp).Row

    ws1.Range("g2:g" & lastrow).ClearContents

    i = 2
    Do While i <= lastrow
        If Application.CountIf(ws1.Range(ws1.Cells(2, 2), ws1.Cells(lastrow, 2)), ws1.Cells(i, 2)) > 1 Then
            ws1.Cells(i, 7).Value = True
        End If
        i = i + 1
    Loop
End Sub


texts: Find intersection of rectangle with itself rotated

texts:
Given \$w, h, \alpha\$ for a rectangle centered at origin with width \$w\$, height \$h\$ and itself rotated by \$\alpha\$ around origin clockwise, I wrote a code to find the intersection area.

  First I find all 4 corners of original and rotated rectangle, along with lines joining them.
  Then I find intersection with axis-parallel lines using getints
  Then I take all intersections in a clockwise/anti-clockwise order and find area using the co-ordinates of the polygon thus formed.

Source: https://codeforces.com/problemset/problem/280/A

import Data.Ord
import Data.List
import Control.Monad

main :: IO ()
main = do
  [w, h, a] <- map read . words <$> getLine
  let a' = (min a (180 - a)) * pi / 180
  let pts = [(w/2, h/2), (w/2, -h/2), (-w/2,-h/2), (-w/2,h/2)] :: [(Double, Double)]
  let pts' = map (rotate a') pts
  let lines = zip pts (tail $ cycle pts)
  let lines' = zip pts' (tail $ cycle pts')
  let ints = concatMap (getints lines') lines
  print . area . uniq $ sortBy (comparing theta) ints

uniq [] = []
uniq [x] = [x]
uniq (x:y:xs)
  | x == y = uniq (x:xs)
  | otherwise = x : uniq (y:xs)

rotate a (x, y) = (x * cos a - y * sin a, x * sin a + y * cos a)

theta (x, y) = atan2 y x

getints xs y = concatMap (\x -> getints' x y) xs

getints' l'@((x1', y1'), (x2', y2')) l@((x, y), (x', y'))
  | x == x' =
    let y'' = y1' + (x - x1') / (x2' - x1') * (y2' - y1')
    in if min y y' <= y'' && y'' <= max y y' then [(x, y'')] else []
  | y == y' = map swap $ getints' (swap' l') (swap' l)
  where
    swap (a, b) = (b, a)
    swap' (p1, p2) = (swap p1, swap p2)

area ps =
  let
    xs = map fst ps
    ys = map snd ps
  in
    0.5 * abs (sum $ zipWith4 (\x y y' x' -> x * y - y' * x') xs (tail $ cycle ys) ys (tail $ cycle xs))


texts: Implement an algorithm for a room cleaning robot

texts:
I wanted to ask this question to my interview candidates, hence wanted to first give it a shot to see if this is doable in 45 mins. Here's the code that I was able to come up with in 45 minutes. Can folks please let me know if there are any logic flaws in this code?
Constraints:

The robot does not have any data of the room to start with.
The robot has to traverse the entire area of the room.
The room can have obstacles.
The robot can go front or right or left.

public interface IRobot
{
    public void TurnLeft();
    public void TurnRight();
    public bool Advance(); // This returns true if the robot is able to advance/no obstacle in that step
    public void Clean();
}

public class Node
{
    public bool Visited { get; set; }
    public bool Cleaned { get; set; }
    public Node Front { get; set; }
    public Node Left { get; set; }
    public Node Right { get; set; }
}

public class RobotManager
{
    private IRobot _robot;
    private Node _rootNode;
    private Node _currentNode;

    public RobotManager(IRobot robot)
    {
        Validator.ThrowArgumentNullIfApplicable(robot);
        this._robot = robot;
        this._rootNode = new Node();
    }

    public void Clean()
    {
        Clean(_rootNode);
    }

    private void Clean(Node currentNode)
    {
        if(currentNode.Cleaned)
        {
            return;
        }

        this._robot.Clean();
        currentNode.Cleaned = true;
        this._currentNode = currentNode;

        if(this._robot.Advance())
        {
            currentNode.Front = new Node();
            Clean(currentNode.Front);
        }

        this._robot.TurnLeft();
        if(this._robot.Advance())
        {
            currentNode.Left = new Node();
            Clean(currentNode.Left);
            this._robot.TurnRight();
        }

        this._robot.TurnRight();
        if(this._robot.Advance())
        {
            currentNode.Right = new Node();
            Clean(currentNode.Right);
            this._robot.TurnLeft();
        }

        Console.WriteLine("Finished Cleaning!");
        Reset();
    }

    // This will return the robot back to the starting point
    public void Reset()
    {
        Traverse(this._currentNode);
        this._rootNode = new Node();
    }

    private bool Traverse(Node currentNode)
    {
        if(currentNode == null || currentNode.Visited)
        {
            return false;
        }

        currentNode.Visited = true;
        if(currentNode == _rootNode)
        {
            return true;
        }

        if(currentNode.Front != null)
        {
            this._robot.Advance();
            if(Traverse(currentNode.Front))
            {
                return true;
            }
        }

        if(currentNode.Left != null)
        {
            this._robot.TurnLeft();
            this._robot.Advance();
            if(Traverse(currentNode.Left))
            {
                return true;
            }

            this._robot.TurnRight();
        }

        if(currentNode.Right != null)
        {
            this._robot.TurnRight();
            this._robot.Advance();
            if(Traverse(currentNode.Right))
            {
                return true;
            }

            this._robot.TurnLeft();
        }
    }
}
```


texts: Iterate over files and convert with a new name / directory

texts:
I'm pretty new to bash scripting.  I want a script that I can run in a directory that contains .md files, runs pandoc on them, and delivers the output to a sibling folder html, i.e. my folder structure is like this:

.
├── html
└── md

Here is what I have working, I just don't know if I'm following good practices or if there's a nicer / more readable way of doing what I'm doing.

#! /bin/bash
# run this from a folder containing markdown files
# it delivers html to the sibling html folder
if hash pandoc 2>/dev/null; then
  for file in ./*.md ; do
    echo Converting $file
    cat "$file" | pandoc -o "$(echo $file | sed 's/^./..\/html/' |  sed 's/.md$/.html/')"
  done
else
  echo "I need pandoc installed"
fi


texts:
I thought up a function that provides types with InputStream and OutputStream:

trait Format[A] {
  def read(i: TypedInput): A
  def write(o: TypedOutput, a: A)
}
trait TypedInput {
  def i: InputStream
  def reads[A](implicit f: Format[A]) = f.read(this)
}
trait TypedOutput {
  def o: OutputStream
  def writes[A](a: A)(implicit f: Format[A]) = f.write(this, a)
}
// and implicit conversions from InputStream to TypdeInput, etc

For example, given a type class of Format[A], now an InputStream can read an instance of A by i.reads[A] and i.reads(FormatOfA):

implicit object IntFormat extends Format[Int] {
  def read(i: TypedInput) = new DataInputStream(i.i).readInt
  def write(o: TypedOutput, a: Int) = new DataOutputStream(o.o).writeInt(a)
}
val i: InputStream = ???
val o: OutputStream = ???
i.reads[Int]
o.writes(3)

When I first thought up this, it looked very Scala with type classes, but now I think it's still very Java, because it just extends java.io so it looks fancy, only with type classes. Please give me some advice to implement this function's concept in more Scala way!


texts: Retrieving multiple versions of source code for a file

texts:
I have the following code that checks for three different properties. Unfortunately each call can throw up to four exceptions that I all have to catch. Can I some how make the code more readable by reducing the amount of try/catch?

public void retrieveSourceCode() {
        try {
            fileName = RestServices.getInstance().getClassName(getSourceCodeURI());
        } catch (ClientProtocolException e) {
            fileName = "not available";
            e.printStackTrace();
        } catch (IOException e) {
            fileName = "not available";
            e.printStackTrace();
        } catch (RestServicesException e) {
            fileName = "not available";
            e.printStackTrace();
        }

        if (!(fileName.endsWith(".jar") || fileName.endsWith(".svn-base"))) {
            try {
                sourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getSourceCodeURI());
            } catch (ClientProtocolException e) {
                sourceCode = "not available";
                e.printStackTrace();
            } catch (IOException e) {
                sourceCode = "not available";
                e.printStackTrace();
            } catch (RestServicesException e) {
                sourceCode = "not available";
                e.printStackTrace();
            }

            if (before == null) {
                beforeSourceCode = "no before source code available";
            } else {
                try {
                    beforeSourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getBeforeVersionURI());
                } catch (ClientProtocolException e) {
                    beforeSourceCode = "no before source code available";
                    e.printStackTrace();
                } catch (IOException e) {
                    beforeSourceCode = "no before source code available";
                    e.printStackTrace();
                } catch (RestServicesException e) {
                    beforeSourceCode = "no before source code available";
                    e.printStackTrace();
                }
            }

            if (after == null) {
                afterSourceCode = "no after source code available";
            } else {
                try {
                    afterSourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getAfterVersionURI());
                } catch (ClientProtocolException e) {
                    afterSourceCode = "no after source code available";
                    e.printStackTrace();
                } catch (IOException e) {
                    afterSourceCode = "no after source code available";
                    e.printStackTrace();
                } catch (RestServicesException e) {
                    afterSourceCode = "no after source code available";
                    e.printStackTrace();
                }
            }
        }

        getChangeSet().addAffectedFile(getFileName());

    }


texts:
I should estimate the effect of B fields on particle deflection using \$F=V \times B \times Force\$.

I have a 2D mesh with \$n_x\$ and \$n_y\$ which show the number of points in each direction. \$B\$ is the magnetic field which is a 2D mesh arrays (with dimension \$n_x \times n_y= 1600 \times 900 = 1440000\$) and \$V\$ is the velocity of particles and is a 1D array (with dimension 431605462). I also have two 1D arrays (with the same dimension as the \$V\$ array) which show the x and y coordinates of each particles. I called them grid_pro_x and grid_pro_y.

Since \$V\$ is a 1D array and \$B\$ is a 2D array I can not directly multiply \$V\$ with \$B\$. To solve this issue I created a 2D zero array for the \$V\$ and using 2 for-loops I find particles which stand in each cell of the mesh. I consider the average velocity of all particles as a velocity component of each cell. Because of the large dimensionality of the mesh, if I keep the original dimension, the code needs several days to complete the \$V\$ array since it needs to be repeated 1440000 times. As a solution, I compressed \$V\$ with an optional variable called divider. If I use divider = 10 I guess the code needs 2 days to be finished and if I use divider = 100 the code will be finished in half an hour but now the precision of the results reduces significantly.

You can see the code in the following.

nx,ny= 1600, 900

xmin = -30.0e-6
xmax =  50.0e-6

ymin = -45.0e-6
ymax = 45.0e-6

#### create a 2D  velocity array

divider = 100
m_p= 1.6726219e-27   #  (kg unit)  proton mass

nx_new = nx/divider
ny_new = ny/divider

Vx = np.zeros((ny_new, nx_new))
Vy = np.zeros((ny_new, nx_new))

res_x = (xmax - xmin)/nx_new   # resolution in x direction
res_y = (ymax - ymin)/ny_new   # resolution in y direction

  #   Find corresponding indices

for i in range( 0,ny_new ):
  for j in range(  0,nx_new):

    xx = i*res_x
    yy = j*res_y

##### all particles with different Px confined in a specific cell

    Px_pro_lim = Px_pro[(grid_pro_x >=  xx ) & (grid_pro_x < xx+res_x ) & (grid_pro_y >=  yy ) & (grid_pro_y < yy+res_y ) ]

    Vx[i,j] = np.mean(Px_pro_lim)/m_p
#print 'Vx[i,j]= ' ,Vx[i,j]


texts: Find the longest sequence of increasing numbers in an array

texts:
I have the following task: to find the largest sequence of increasing numbers in an array.

I'll give you an example : 2 3 4 1 50 2 3 4 5 will return the sequence of 2 3 4 5 - that is the largest sequence of increasing numbers in the given array.
Another one is : 5 -1 10 20 3 4 which will return -1 10 20.

If there are two equal sequences -for example 4 5 1 2 -1 which has the sequences  4 5 and 1 2 the first sequence will be returned.

Below is my method

public static List<Integer> findLongestIncreasingSequence(int[] numbersToBeProcessed) {

        List<Integer> longestIncreasingSequence = new ArrayList<Integer>();
        List<Integer> currentNumbersSequence = new ArrayList<Integer>();

        for (int i = 0; i < numbersToBeProcessed.length; i++) {

            int currentNumber = numbersToBeProcessed[i];
            int nextNumber = 0;

            // checks if it is not the last number in the array
            if (i != numbersToBeProcessed.length - 1) {
                nextNumber = numbersToBeProcessed[i + 1];
            }
            currentNumbersSequence.add(currentNumber);
            //checks if the current sequence ends here(the next number is smaller or equal)
            //or if the array ends
            if (currentNumber >= nextNumber || i == numbersToBeProcessed.length - 1) {
                // checks if the current sequence is bigger
                if (currentNumbersSequence.size() > longestIncreasingSequence.size()) {
                    longestIncreasingSequence.clear();
                    longestIncreasingSequence.addAll(currentNumbersSequence);
                }
                //clear the current sequence so it can start all over again
                currentNumbersSequence.clear();
            }
        }

        return longestIncreasingSequence;
    }

Any feedback received on this method is more than welcome. The thing I dislike the most is the check I make for the last element in order to avoid ArrayIndexOutOfBounds exception.


texts:
I've had to make several functions to turn some structures into strings. I am a still green when it comes C so I am unsure if I am doing this a very awkward way. The system I am coding for does not have snprintf, I know that would be far more elegant, however I cannot use it.
Any advice?

int device_to_string(char* const asString, pDevice dev, size_t maxLength)
{
  char* ipAsString;
  size_t actualLength;
  struct in_addr addr;

  if (dev == NULL)
  {
    return NULL_ERROR;
  }

  addr.s_addr = dev->ip;
  ipAsString = inet_ntoa(addr);

  actualLength = strlen("name=")  + strlen(dev->name) +
                 strlen("&ip=")   + strlen(ipAsString) +
                 strlen("&mac=")  + strlen(dev->mac)  +
                 strlen("&type=") + strlen(dev->type) + 1;

  if (actualLength > maxLength)
  {
    return SIZE_ERROR;
  }

  strncat(asString, "name=",    strlen("name="));
  strncat(asString, dev->name,  strlen(dev->name));
  strncat(asString, "&ip=",     strlen("&ip="));
  strncat(asString, ipAsString, strlen(ipAsString));
  strncat(asString, "&mac=",    strlen("&mac="));
  strncat(asString, dev->mac,   strlen(dev->mac));
  strncat(asString, "&type=",   strlen("&type="));
  strncat(asString, dev->type,  strlen(dev->type));

  asString[actualLength] = '\0';

  return NO_ERROR;
}


texts: Format an Unsigned Byte to a Three ASCII Digits

texts:
I'm working on a game for the Atari VCS and have been dusting off my 30+ year old skills in writing MOS 6502 assembly language.

The VCS runs at 1.19 MHz and is based on a MOS 6507 chip with some custom logic and 128 bytes only of RAM.

Outline of Problem

The game needs to display a value as 3 ASCII digits, but I'm working in full range signed and unsigned bytes, rather than BCD, so I now have the problem of converting from a full range byte to ASCII digits.

What I have so Far

I have been able to put the following together, and it appears to work. I'd welcome any tips for making it smaller, faster etc.

Currently the program is estimated to run in around 114+ cycles, just counting the instruction cycle counts with no branches taken.

;
; FormatUnsigned.asm
;
; 6502 routine to format an unsigned byte into a space
; followed by 2 decimal digits if < 100, or 3 decimal
; digits if >= 100.
;

        seg.u Variables
        org $80

char1   .byte                   ; output chars
char2   .byte
char3   .byte
Temp    .byte                   ; temp

        seg Code
        org $f000

TestFormat
        lda #211                ; sample value
        jsr FormatUnsigned      ; format
        brk                     ; halt

; A = value to format unsigned
FormatUnsigned:
        ldy #$20                ; default hundreds digit
        sty char1               ; is a space
; calculate char1
        ldy #$30                ; '0'
        sec                     ; set carry for sub loop
Sub100
        sbc #100
        iny                     ; y = '1', '2'
        bcs Sub100              ; loop whilst carry is not borrowed
        adc #100                ; add 100 back
        dey                     ; and take back the inc to y
        cpy #$30                ; if y is '0', just leave the space in there
        beq SkipHundreds
        sty char1               ; save '1' or '2' into char1
SkipHundreds
; format value < 100 into BCD
        tay                     ; save a in y
        lsr
        lsr
        lsr
        lsr
        and #$F                 ; get high nybble
        tax                     ; into x for indexing
        lda highNybble,x
        sta Temp                ; save in temp

        tya                     ; get value - 100s back
        and #$0f                ; low nybble
        tay                     ; low nybble in y
        cmp #$0a                ; <10?
        bcc NoSub10

        sbc #$0a                ; subtract 10
        tay                     ; save in y
        clc
        lda #$10                ; Add '10' to bcd saved value
        adc Temp
        sta Temp
        tya
NoSub10
        sed                     ; decimal mode
        adc Temp                ; add bcd value to 0-9 in a
        sta Temp                ; save bcd value
        cld                     ; leave decimal mode

Write2ndChar
        lsr                     ; get high nybble
        lsr
        lsr
        lsr
        and #$0f
        adc #$30
        sta char2               ; save 2nd character

Write3rdChar
        lda Temp
        and #$0f                ; get low nybble
        adc #$30
        sta char3               ; save 3rd character
        rts

highNybble
        .byte $00
        .byte $16
        .byte $32
        .byte $48
        .byte $64
        .byte $80
        .byte $96

The program works correctly for tested inputs, producing an output of $32 $31 $31 for the decimal value 211.


texts:
This is a pseudo-follow up to Kotlin Data Class Wildcard: taking in advice from that question I came upon a better but quite different solution to the same problem.

The problem: fuzzy matching AST nodes. All regular properties should be checked for equality normally (via ==), but allowing any absent value to match a real value and recursing the fuzzy match down the Node hierarchy. The second requirement is that this does not require anything extra within the Nodes themselves as this would be prohibitive towards adding new nodes and the fuzzy match is purely the domain of testing.

The reason for creating this is that the structure of a parsed AST can be very complex and in order to make writing tests easier, I want to be able to say "I don't care about this part of the parsed AST", and just test a portion of it.

NodeMatching.kt

package nafi.grammar

import nafi.grammar.ast.Node
import nafi.grammar.ast.Position
import kotlin.reflect.memberProperties

infix fun Node.matches(that: Node): Boolean {
    if (this.javaClass != that.javaClass)
        return false
    else return this.javaClass.kotlin.memberProperties
            .map { it.get(this) matches it.get(that) }
            .fold(true, Boolean::and)
}

private infix fun Position.matches(that: Position) =
        this.start == that.start &&
                (this.end == that.end || this.end == null || that.end == null)

private infix fun <T : Collection<*>> T.matches(that: T): Boolean {
    if (this.size != that.size) return false
    else return this.indices
            .map { this.elementAt(it) matches that.elementAt(it) }
            .fold(true, Boolean::and)
}

private infix fun Any?.matches(that: Any?): Boolean = when {
    this == null || that == null                   -> true
    this is Node && that is Node                   -> this matches that
    this is Position && that is Position           -> this matches that
    this is Collection<*> && that is Collection<*> -> this matches that
    else                                           -> this == that
}

ASTMatcherTest.kt

package nafi.grammar

import nafi.grammar.ast.ConstantDefinition
import nafi.grammar.ast.IntegerLiteral
import nafi.grammar.ast.NafiFile
import nafi.grammar.ast.Position
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals

class ASTMatcherTest {
    fun testCompile(code: String, ast: NafiFile, expectedMatch: Boolean) {
        val parsed = NafiParserFacade.parse(code)
        assertEquals(expectedMatch, ast matches parsed,
                     "expected $ast, got $parsed, should ${if (!expectedMatch) "not " else ""}match"
        )
    }

    @Test fun passNoPosition() = testCompile(
            "constant id = 5",
            NafiFile(ConstantDefinition("id", IntegerLiteral("5"))),
            true
    )

    @Test fun failBadPosition() = testCompile(
            "constant id = 5",
            NafiFile(ConstantDefinition("id", IntegerLiteral("5", Position(10, 14)))),
            false
    )

    @Test fun passGoodPosition() = testCompile(
            "constant id = 5",
            NafiFile(ConstantDefinition("id", IntegerLiteral("5", Position(1, 14, 1, 15)), Position(1, 0))),
            true
    )
}

Because Kotlin extensions are resolved statically, NodeMatching.kt includes a definition of matches for two Any?s and does a manual virtual dispatch to the appropriate matches or ==.

Key Points:

Position.matches and <T : Collection<*>>.matches can be inline, but should they be?
This requires data which is non-nullable in application logic to be nullable to allow fuzzy matching. Is there a way around that?
Any kotlin-isms that would make the code more readable or kotlin-abuses that are making the code less readable

The minimal AST Model that I'm using for testing can be found on GitHub along with the rest of the project. The project is a Maven project and you can run the tests with maven test.


texts: Sort array of objects with hierarchy by hierarchy and name

texts:
I have an array of nested objects:

[
    {_id:1, parent:0, name:'Z'},
    {_id:4, parent:0, name:'A'},
    {_id:2, parent:1, name:'H'},
    {_id:8, parent:2, name:'G'},
    {_id:5, parent:4, name:'M'},
    {_id:6, parent:4, name:'N'},
    {_id:3, parent:1, name:'Z'},
    {_id:7, parent:2, name:'L'}
]

I need to sort them in the way for nodes at same level will be sorted by alphabetic order (asc/desc configurable) and all child nodes should be after their parent and before their parent's sibling node also sorted by alphabetic order.

For example, if sorted by asc, the output should be

[
    { _id: 4, parent: 0, name: 'A' },
    { _id: 5, parent: 4, name: 'M' },
    { _id: 6, parent: 4, name: 'N' },
    { _id: 1, parent: 0, name: 'Z' },
    { _id: 2, parent: 1, name: 'H' },
    { _id: 8, parent: 2, name: 'G' },
    { _id: 7, parent: 2, name: 'L' },
    { _id: 3, parent: 1, name: 'Z' }
]

In the output, 4 is before 1 because A < Z. 5 and 6 are sorted alphabetically under 4 and before 1. Similar case for 8 and 7 under 2 and before 3.

and if desc, the output should be:

[
    { _id: 1, parent: 0, name: 'Z' },
    { _id: 3, parent: 1, name: 'Z' },
    { _id: 2, parent: 1, name: 'H' },
    { _id: 7, parent: 2, name: 'L' },
    { _id: 8, parent: 2, name: 'G' },
    { _id: 4, parent: 0, name: 'A' },
    { _id: 6, parent: 4, name: 'N' },
    { _id: 5, parent: 4, name: 'M' }
]

I tried to implement a function as below.

function sortByHierarchyAndName(arr, sort) {
    var i = 0;
        j = 0;
        t = 0;
        parentFound = false;
        x = arr.length;
        arr2 = [];

    //Sort by parent asc first
    arr = arr.sort(function(a, b) {
        if(a.parent < b.parent) return -1;
        if(a.parent > b.parent) return 1;
        return 0;
    });

    for(; i < x; i += 1) {
        t = arr2.length;
        if(t === 0)  arr2.push(arr[i]);
        else if(arr[i].parent === 0) {
            for(j = 0; j < t; j += 1) {
                if(sort === -1) {
                    if(arr[i].name >= arr2[j].name) arr2.splice(j, 0, arr[i]);
                } else {
                    if(arr[i].name <= arr2[j].name) arr2.splice(j, 0, arr[i]);
                }
            }
            if(arr2.length === t) arr2.push(arr[i]);
        }
        else {
            parentFound = false;
            for(j = 0; j < t; j += 1) {
                if(arr[i].parent === arr2[j]._id) {
                    if(j === t - 1) {
                        arr2.push(arr[i]);
                    }
                    parentFound = true;
                } else if(arr[i].parent === arr2[j].parent) {
                    if(sort === -1) {
                        if(j === t - 1) arr2.push(arr[i]);
                        else if(arr[i].name >= arr2[j].name) {
                            arr2.splice(j, 0, arr[i]);
                            j = t;
                        }
                    } else {
                        if(j === t - 1) arr2.push(arr[i]);
                        else if(arr[i].name <= arr2[j].name) {
                            arr2.splice(j, 0, arr[i]);
                            j = t;
                        }
                    }
                } else if(arr[i].parent > arr2[j].parent && parentFound) {
                    arr2.splice(j, 0, arr[i]);
                    j = t;
                }
            }
        }
    }
    return arr2;
}

Assuming array.sort() take f(n) amount of time when sorting by parent asc for an array of length n, I'm doing some performance analysis for the implementation as below.

  Best case: \$f(n) + x \times n + y \times \sum (\frac{1...n}{2})\times n\$

  Worst case: \$f(n) + x \times n + y \times \sum (1...n)\times n\$

  x - factor in processing any given element in arr.

  y - factor in processing any given element in arr against any element in arr2.

As you can see, in both case, the duration of execution will grow exponentially as n grows, so I'm wondering if I can do something to improve this.


texts: Ensure multiple steps work/saving multiple models via a service

texts:
I just thought of something new re: saving multiple objects in Rails (though Rails is not necessary).

Objectives:

Create an author and a tomato, but both of those must be valid.
If invalid creation, then return an error object.
Not raise an ActiveRecord if I can (slow). (Is this something that I am even supposed to think about or am I overkilling this?)
Make it easy to add steps/add steps in front or in the back.

That is just something I thought of. I just made creating authors and tomatoes methods that are sequentially called and checked if they are valid? or not.

I'm not sure what design pattern this is because the alternative is multiple if statements. If there is a formal gem or better way then I'd appreciate suggestions:

class AuthorAndTomatoSave
  def call
    steps.map do |step|
      result = step.call

      # If error, return
      return result unless result.valid?
    end

    # hypothetical case where we want to return the author.
    # (this is also why create_author is memoized)
    create_author
  end

  private

  def steps
    [ proc { create_author }, proc { create_tomato } ]
  end

  def create_author
    @created_author ||= Author.create(author_params)
  end

  def create_tomato
    Tomoto.create(tomato_params)
  end
end


texts:
In a txt file there are IDs and next to them there are their neighbours like this:

1  1
1  2
1  3
2  1
2  4
2  8
3  5

Using AVL trees I store the IDs in one AVL tree and for every ID in this AVL
I make another AVL tree in which I store its neighbours.In the end I make another txt file that in every line has an ID , its number of neighbours and then its neighbours.Using the above example the output txt is :

1 3 1 2 3
2 2 1 4 8
3 1 5

I managed to make it work but the problem is that when I have many IDs the program gets very slow because I suspect there are too many IDs in the first AVL
tree to search insert and balance everytime.Is there any shortcut to make it faster?
Some of the functions I used :

Node* AVLTree::search(Node *node, int ID)
{
    if(node == NULL)
    {
        return NULL;
    }
    if(node->ID == ID)
    {
        return node;
    }
    else if(node->ID < ID)
    {
        return search(node->right, ID);
    }
    else
    {
        return search(node->left, ID);
    }
}

void AVLTree::balance(Node *&node)
{
    if (node == NULL)
    {
        return;
    }
    int height_diff = heightDifference(node);
    if (height_diff > 1)
    {
        if( heightDifference(node->left) > 0)
        {
            node = left_rotation(node);
        }
        else
        {
            node = left_right_rotation(node);
        }
    }
    else if (height_diff < -1)
    {
        if (heightDifference(node->right) > 0)
        {
            node = right_left_rotation(node);
        }
        else
        {
            node = right_rotation(node);
        }
    }
    balance(node->left);
    balance(node->right);
}

Node* AVLTree::insert(Node *node, int ID)
{
    if(node == NULL)
    {
        node = newNode(ID);
        size++;
        return node;
    }
    else if(node->ID > ID)
    {
        node->left = insert(node->left, ID);
        balance(node);
    }
    else if(node->ID < ID)
    {
        node->right = insert(node->right, ID);
        balance(node);
    }
    return node;
}

int AVLTree::height(Node *node)
{
    if (node != NULL)
    {
        int leftHeight = height(node->left);
        int rightHeight = height(node->right);
        int maxHeight = max(leftHeight, rightHeight);
        return maxHeight + 1;
    }
    else
    {
        return 0;
    }
}

int AVLTree::heightDifference(Node *node)
{
    int leftHeight = height(node->left);
    int rightHeight = height(node->right);
    return leftHeight - rightHeight;
}


texts:
I want to check for a condition in a guarded wait() loop with a user-specified total timeout, similar to how LinkedBlockingQueue.poll() works.

For example collection can be appended to by different threads, but only when the collection contains a value equating to myItem within timeout, should the loop terminate successfully. If the user-specified timeout elapses, it should throw.

This is my current best approach:

long startTime = System.currentTimeMillis();
synchronized (collection) {
    while (!collection.contains(myItem)) {
        long remaining = System.currentTimeMillis() - startTime - timeout;
        if (remaining < 0)
            throw new TimeoutException();

        collection.wait(remaining);
    }
}

The problem here is that System.currentTimeMillis() (or System.nanoTime()) is called inside a synchronized context. IntelliJ's warning states:

  While not necessarily representing a problem, such calls cause an expensive context switch, and are best kept out of synchronized contexts, if possible.

I wonder how much impact this 'expensive context switch' will have in practice, with Oracle JVM 8?

This is one alternative I came up with, but I don't like this as the actual timeout becomes ⌊timeout/10⌋*10 + delta. and the error will probably be much worse than the context switch.

synchronized (collection) {
    int loops = 0;
    while (!collection.contains(myItem)) {
        if(loops++ > timeout / 10)
            throw new TimeoutException();

        collection.wait(10);
    }
}


texts:
I am trying to implement a thread-safe deque in C++.
ThreadSafeDeque will be used by a FileLogger class.
When threads call the log() function of FileLogger the messages will be push_back()ed to ThreadSafeDeque and return almost immediately. In a separate thread the FileLogger will pop_front() messages and write them to a file in its own pace.
Am I doing things correctly and efficient below?

#pragma once
#include <deque>
#include <mutex>
template<class T>
class ThreadSafeDeque {
public:
    void pop_front_waiting(T &t) {
        // unique_lock can be unlocked, lock_guard can not
        std::unique_lock<std::mutex> lock{ mutex }; // locks
        while(deque.empty()) {
            condition.wait(lock); // unlocks, sleeps and relocks when woken up
        }
        t = deque.front();
        deque.pop_front();
    } // unlocks as goes out of scope

    void push_back(const T &t) {
        std::unique_lock<std::mutex> lock{ mutex };
        deque.push_back(t);
        lock.unlock();
        condition.notify_one(); // wakes up pop_front_waiting
    }
private:
    std::deque<T>               deque;
    std::mutex                  mutex;
    std::condition_variable condition;
};


texts: Random positioning and movement of a rabbit on a table

texts:
I was inspired by this:

  If you would put a rabbit randomly on a circular table with radius r=
  1 meter and it moves 1 meter in a random direction, what is the
  chance it won't fall off?

I decided to develop a program to manually test this scenario. My code will run as many tests as you want with (hopefully) more tests resulting in a correct answer. I know a bit of C++, but have decided to learn Python recently.

My code does the following:

Initialises a random starting within a circle with radius 1
Moves 1 unit in a random direction
Updates the pass/fail rate depending on if the movement resulted in a position within the original circle

import math
import random

class RandPoint:
    x = 0
    y = 0

    def __init__(self):
        self.x = random.uniform(-1,1)
        self.y = random.uniform(-1,1)

    def move(self):
        angle = random.uniform(0, 2 * math.pi)
        self.x+=math.cos(angle)
        self.y+=math.sin(angle)

    def check(self):
        return math.sqrt(math.pow(self.x,2)+math.pow(self.y,2)) < 1

passed = 0.0
num = int(raw_input("How many trials would you like? \n"))

for value in range (1,num):
    startingpoint = RandPoint()

    while not(startingpoint.check()):
        startingpoint = RandPoint()

    startingpoint.move()
    passed += int(startingpoint.check())

print (str(num) + " trys, " + str(passed) + " passes, " +      str((passed/num)*100) + "%")


texts:
I'm very new to Go, and am trying to get some experience by re-writing some of my Python code in Go.  Below is a function that takes an IP address (ipv4) in integer form and returns the string version. From 572779703 to 34.35.236.183 for example.

func int2ip(num int) (string) {
    result   := [4]int{}
    for i, n := range []uint{24, 16, 8, 0} {
        result[i] = (num >> n) & 255
    }
    return fmt.Sprintf("%d.%d.%d.%d", result[0], result[1], result[2], result[3])
}

I'm not only curious if there is a more straightforward or concise way to do this with Go, but am very curious if there is a way to use the []result array in Sprintf() without having to type out every index.

Something similar to:

fmt.Sprintf("%d.%d.%d.%d", result)


texts:
A day ago I have asked a question on here about Preventing email injection. I had some feedback and worked on it, and below is the latest update.

Could anyone please share their opinion?  Is it secure enough?  Is there a way to short-cut the code?

<?php
   session_start();

   if ($_SERVER['REQUEST_METHOD'] == 'POST'){
      ob_start();

      if(isset(
         $_REQUEST['name'],
         $_REQUEST['email'],
         $_REQUEST['message'],
         $_REQUEST['number'],
         $_REQUEST['date'],
         $_REQUEST['select'],
         $_REQUEST['radio'],
         $_REQUEST['checkbox'],
         $_REQUEST['token']
      )){
      if($_SESSION['token'] != $_POST['token']){
         $response = "0";
      }else{
         $_SESSION['token'] = "";
         $name = $_REQUEST['name'];
         $email = $_REQUEST['email'];
         $message = $_REQUEST['message'];
         $number = $_REQUEST['number'];
         $date = $_REQUEST['date'];
         $select = $_REQUEST['select'];
         $radio = $_REQUEST['radio'];
         $checkbox = $_REQUEST['checkbox'];

         $spam_pattern = "/[\r\n]|Content-Type:|Bcc:|Cc:/i";
            switch (true){
            case !filter_var($email, FILTER_VALIDATE_EMAIL):
                  $response = "Invalid Email Address!";
            break;
                case !preg_match($spam_pattern, $name):
                case !preg_match($spam_pattern, $number):
                case !preg_match($spam_pattern, $date):
                case !preg_match($spam_pattern, $select):
                case !preg_match($spam_pattern, $radio):
                case !preg_match($spam_pattern, $checkbox):
                case !preg_match($spam_pattern, $message):
                  $response = "Invalid Request!";
            break;
                default:
                    $to = "";
                    $subject = "New Message From: $name";
                    $message = "Name: $name

                                   number: $number

                                   date: $date

                                   select: $select

                                   radio: $radio

                                   checkbox: $checkbox

                                   Email: $email

                                   Message: $message";

                    $headers  = 'MIME-Version: 1.0' . "\r\n";
                    $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
                    $headers .= 'From: '.$email . "\r\n";

                    if(mail($to, $subject, $message, $headers)){
                        $response = "
Success! Your submission has been sent.
";
                    }else{
                        $response = "
Error! There was a problem with sending.
";
                    }
            break;
               }
            }
         }
         else {
            $response = "Error";
         }
      ob_flush();
   }
?>


texts: Parsing date strings, inferring the year such that the date is not in the future

texts:
I got this program that I am working on and in it, I got a section that has a try statement and two error except statements.

try:
    ...
    if ...: raise SyntaxError
except SyntaxError:
    ...
except ValueError:
    ...

The thing is that the SyntaxErrors are technically ValueErrors, but the errors occur for different reasons, therefore need different code to solve/get around the problem. So in order to prevent the code in all the "excepts" from being executed, I had to separate/make the type of Errors different. Is it okay to do that even though the SyntaxErrors are techincally ValueErrors, that I label them as SyntaxErrors? Or is there a method in solving this problem?

Here is the code of the program:

from datetime import datetime

today = datetime(2019, 1, 1).date()
this_year = 2019
last_year = this_year - 1

text = ["Dec 31 ", "@@@@@@@@@@@@@@@@@@@@@Dec 31 "]

for line in text:
    date_str = line
    try:
        date = datetime.strptime(date_str + str(this_year), "%b %d %Y").date()
        if date > today: raise SyntaxError
        print("+", date)
    except SyntaxError:
        date = datetime.strptime(date_str + str(last_year), "%b %d %Y").date()
        print("-", date)
    except ValueError:
        print("abnormality")
        continue


texts:
I have a system of 49 equations and 49 unknowns (\$x_{1},...,x_{49}\$). All equations have the following form.

\$x_{s}\sum_{r=1}^{R}\sum_{t=1}^{T}a_{s,t}b_{rs,t}=\sum_{r=1}^{R}\sum_{t=1}^{T}a_{r,t}b_{sr,t}x_{r}\$

where \$s = 1,...,49\$ with \$S = R = 50\$ and \$T = 30\$. The \$a\$'s, the \$b\$'s and \$x_{50}\$ are known parameters. Since all equations have the same form, I believe that vectorizing the problem is possible. I appreciate any suggestions of how to do this.

The code below solves a smaller system with \$S=R=T=3\$. The code runs. I describe how the parameters are arranged beneath the code.

    %% Define parameters
        T = 3; % Number of types (T)
        S = 3; % Number of senders (S)
        R = S; % Number of receivers (R), equals the number of senders
        A = [.1 .1 .1   % Columns are senders (S), rows are types (T)
             .3 .3 .6
             .6 .6 .3];
        B1 = [.9 .0 .1
              .5 .1 .2
              .8 .2 .1];
        B2 = [.0 .7 .2
              .2 .9 .0
              .1 .8 .1];
        B3 = [.1 .3 .7
              .3 .0 .8
              .1 .0 .8];
        B = zeros(T,R,S); % Initialize
        B(:,1,:) = B1;    % Pages of B are receivers
        B(:,2,:) = B2;    % Rows of B are types
        B(:,3,:) = B3;    % Columns of B are senders

        % Starting values
        x0 = [36 26];
        % Call functions
        F = fsolve(@(x) myfun1(x,A,B),x0);

    %% Define Functions
        function F = myfun1(x,A,B)
        F(1) =   x(1)*(sum(A(:,1).*B(:,2,1))  +  sum(A(:,1).*B(:,3,1))) ...
              -  x(2)*(sum(A(:,2).*B(:,1,2))) - (sum(A(:,3).*B(:,1,3)));
        F(2) =   x(2)*(sum(A(:,2).*B(:,1,2))  +  sum(A(:,2).*B(:,3,2))) ...
              -  x(1)*(sum(A(:,1).*B(:,2,1))) - (sum(A(:,3).*B(:,2,3)));
        end

Is it possible to avoid the "sum"? Maybe by rearranging the
parameters?
Is it possible to vectorize the function itself to avoid writing F(1), F(2), ... , F(49)? I know it is possible, but for this particular problem I have difficulties understanding how to do it.

A visualization of the B array:
In the example, the parameters are arranged as shown below.

\$A:\$
\begin{pmatrix} a_{1,1} & a_{2,1} & a_{3,1}\\ a_{1,2} & a_{2,2} & a_{3,2}\\ a_{1,3} & a_{2,3} & a_{3,3} \end{pmatrix}

\$B1:\$
\begin{pmatrix} b_{11,1} & b_{12,1} & b_{13,1}\\ b_{21,1} & b_{22,1} & b_{23,1}\\ b_{31,1} & b_{32,1} & b_{33,1} \end{pmatrix}

\$B2:\$
\begin{pmatrix} b_{11,2} & b_{12,2} & b_{13,2}\\ b_{21,2} & b_{22,2} & b_{23,2}\\ b_{31,2} & b_{32,2} & b_{33,2} \end{pmatrix}

\$B3:\$
\begin{pmatrix} b_{11,3} & b_{12,3} & b_{13,3}\\ b_{21,3} & b_{22,3} & b_{23,3}\\ b_{31,3} & b_{32,3} & b_{33,3} \end{pmatrix}


texts: Sum two integers, unless they are the same, in which case return double their sum

texts:
I was doing a simple problem on codingbat and testing out my python. The problem was:

  Given two int values, return their sum. Unless the two values are the same, then return double their sum.

sum_double(1, 2) → 3
sum_double(3, 2) → 5
sum_double(2, 2) → 8

My solution was:

def sum_double(a, b):
  if a is b:
    return 2 * (a + b)
  else:
    return a+b

and it worked just fine. However, when I checked the solution the answer they had was:

def sum_double(a, b):
  # Store the sum in a local variable
  sum = a + b

  # Double it if a and b are the same
  if a == b:
    sum = sum * 2
  return sum

But this seems to Java-y to me. Am I right to believe that my code is more pythonic? Or was their answer a better way to write code in python?


texts: Handling errors with minimal repetition when using Find function

texts:
I have a function that essentially searches out a value in a table by looking through the column headers and row headers to locate a data point. The function takes the sheet name, the column header name, and row header name as arguments, and I have an error handler set up if any one of the methods performed with those variables fails. However, each handler is very similar, so there is much repetition. Is there a more clear way to have all errors handled uniquely but not to have to re-write Exit Function and other such things?

Function getDataPoint(rowItem As String, searchCol As Integer, colItem As String, searchRow As Integer, shtName As String) As Variant

    Dim rowNum As Integer, colNum As Integer
    Dim rowNumRng As Range, colNumRng As Range

    'Find worksheet to search
    On Error GoTo shtNotFound:
    With ThisWorkbook.Sheets(shtName)

        'Find rowNum where rowItem appears in searchCol
        On Error GoTo rowNotFound:
        Set rowNumRng = .Columns(searchCol).Find(What:=rowItem, _
            After:=.Cells(1, searchCol), _
            LookIn:=xlValues, _
            LookAt:=xlWhole, _
            SearchOrder:=xlByColumns, _
            SearchDirection:=xlNext, _
            MatchCase:=True)

        rowNum = rowNumRng.Row

        'Find colNum where colItem appears in searchRow
        On Error GoTo colNotFound:
        Set colNumRng = .Rows(searchRow).Find(What:=colItem, _
            After:=.Cells(searchRow, 1), _
            LookIn:=xlValues, _
            LookAt:=xlWhole, _
            SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, _
            MatchCase:=True)

        colNum = colNumRng.Column

        getDataPoint = .Cells(rowNum, colNum).Value

    End With
    On Error GoTo 0
    Exit Function

 shtNotFound:
    Debug.Print "Sheet not found"
    getDataPoint = "NOT FOUND"
    Exit Function
 rowNotFound:
    Debug.Print "Row item not found"
    getDataPoint = "NOT FOUND"
    Exit Function
 colNotFound:
    Debug.Print "Column item not found"
    getDataPoint = "NOT FOUND"
    Exit Function

End Function


texts:
I have written bash script to query database and check server details.

Please let me know if the script is as per best standards:

if [ -z "$1" -o -z "$2" ]
then
  echo "FAIL : Put username and password"
else
  fulltoken=`curl -s --insecure -H "Content-Type: application/json" -X POST -d "{\"username\":\"$1\",\"password\":\"$2\"}" https://apiurl`
  echo $fulltoken | grep -q authToken > /dev/null 2>&1
  if [ $? -eq 0 ]
  then
    token=`echo $fulltoken | awk -F':' '{print $8}' | awk -F',' '{print $1}' | sed 's/"//g'`
    hostname=`uname -n | awk -F'.' '{print $1}'`
    serverdetails=`curl -s --insecure -H "Content-Type: application/json" -H "Authorization: $token" -X GET https://apiurl`
    echo $serverdetails | grep -iq "applnId"
    if [ $? -eq 0 ]
    then
      exactserverdetails=`echo $serverdetails`
      appInId=`echo $exactserverdetails | sed 's/,/\n/g' | grep "applnId" | awk -F':' '{print $2}'`

        if [ -n $appInId ] && [ $appInId != "null" ]
        then
            echo "PASS"
        else
            echo "FAIL"
        fi
        echo $exactserverdetails | sed 's/,/\n/g' | grep "environment_Name" | awk -F':' '{print $2}' | grep -q -e "Dev"
        if [ $? -eq 0 ]
        then
            echo "PASS"
        else
            echo "FAIL"
        fi
    else
        echo "sorry server is not present"
    fi
  else
      echo "all good"
  fi
fi


texts:
This is my first cut at separating the data access layer out of my very old spaghetti codebase.

I have tried to keep this as simple as possible, it is for a small project, so I am not really interested in learning Spring or Hibernate or other framework, and I don't mind writing a bit of SQL.

I basically have a 1-to-1 relation of database table to business object.

This is the Data Access Layer

package dataaccesslayer;

import dbutils.handlers.IgnoreUnderscoreBeanHandler;
import dbutils.handlers.IgnoreUnderscoreBeanListHandler;
import racemanager.businessobjects.Progression;
import org.apache.commons.dbutils.QueryRunner;
import shared.SLDbHelper;

import java.sql.SQLException;
import java.util.List;

public class DalProgression {

    private static final String SQL_SELECT_ONE =
            "   SELECT * "
                    + "   FROM progressions "
                    + "  WHERE id=? ";

    private static final String SQL_SELECT_ALL =
            "   SELECT * "
                    + "   FROM progressions "
                    + "  ORDER BY name ASC ";

    public static Progression selectOne(int id) {
        QueryRunner qr;
        Progression progression;

        try {
            qr = new QueryRunner(SLDbHelper.getInstance().getDataSource());
            progression = qr.query(SQL_SELECT_ONE, new IgnoreUnderscoreBeanHandler<Progression>(Progression.class), id);
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }

        return progression;
    }

    public static List<Progression> selectAll() {
        QueryRunner qr;
        List<Progression> progressions;

        try {
            qr = new QueryRunner(SLDbHelper.getInstance().getDataSource());
            progressions = qr.query(SQL_SELECT_ALL, new IgnoreUnderscoreBeanListHandler<Progression>(Progression.class));
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }

        return progressions;
    }

}

This is the related Business Object

package businessobjects;

import java.util.Date;

public class Progression {

    private int id;
    private String name;
    private Date modified;
    private Date created;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getModified() {
        return modified;
    }

    public void setModified(Date modified) {
        this.modified = modified;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

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

}

Usage example

int id = 10;
Progression p = DalProgression.selectOne(id);

List<Progressions> pList = DalProgression.selectAll();

Fire away and shoot holes in my code, so I can improve it.
One thing I am not sure about is when I do joins should I have a separate business object for the result, and as such as corresponding data access layer class to perform those queries?


texts:
In my CodeIgniter project I have a Login controller that load this view:

         Mis solicitudes

The controller: soporte, function: callSupport

public function callSupport($index = null, $order = null){
    $session_data = $this->session->userdata('session_user');
    $data['solicitud']  = $this->helpdesk_model->getRequest($session_data['usuario'], $index, $order);
    $data['categories'] = $this->helpdesk_model->getCategories();
    $this->load->view('modules/help_desk/supports', $data);
}

With jQuery I call the controller and render in a page content that is a
 element:

$(".sub-menu .menu-item, .module-item").click(function(event) {
    $(".page-content").load($(this).data('target'));
    $("title").text( $( this ).text() );
});

In the view 'modules/help_desk/supports':

    Estado
    Prioridad
    Responsable

    <?php foreach ($solicitud as $key => $value) { ?>

        <span class="label label-sm <?= $value['label']?> "><?= ucfirst($value['status']) ?>
        <span class="badge <?= $value['class']?> "><?= $value['priority'] ?>
        <?= $value['name'].' '.$value['last_name'] ?>

    <?php  } ?>

As you can see, in the first  a put an anchor tag calls another controller with jQuery similar than before. Please be critical, very severe with me.


texts:
This is a script I wrote to find the n biggest files in a given directory (recursively):

import heapq
import os, os.path
import sys
import operator

def file_sizes(directory):
    for path, _, filenames in os.walk(directory):
        for name in filenames:
            full_path = os.path.join(path, name)
            yield full_path, os.path.getsize(full_path)

num_files, directory = sys.argv[1:]
num_files = int(num_files)

big_files = heapq.nlargest(
        num_files, file_sizes(directory), key=operator.itemgetter(1))
print(*("{}\t{:>}".format(*b) for b in big_files))

It can be run as, eg: bigfiles.py 5 ~.

Ignoring the complete lack of error handling, is there any obvious way to make this clearer, or at least more succinct? I am thinking about, eg, using namedtuples in file_sizes, but is there also any way to implement file_sizes in terms of a generator expression? (I'm thinking probably not without having two calls to os.path, but I'd love to be proven wrong :-)


texts: Crawler for scraping and approving friend requests in Facebook

texts:
I've made a Facebook scraper using VBA in combination with selenium which is able to parse the name from friend request list.

It is necessary to do one thing manually, though. After running this script, when Facebook page opens up, there will be a notification popping up mentioning "Allow" or "Block". Wait a little while to get the buffering done and then Just click on "Allow". That's it.

There is a javascript function within this script to handle scrolling the webpage.

Here is the working code which I have tried to make accurately:

Sub Facebook_Crawler()

Dim driver As New WebDriver
Dim posts As Object, post As Object

With driver
    .Start "chrome", "https://www.facebook.com"
    .get "/login.php?login_attempt=1&lwv=111"

    .FindElementByXPath("//*[@id='email']").SendKeys ("someEmail") --Fill in the email
    .FindElementByXPath("//*[@id='pass']").SendKeys ("password") --Fill in the password
    .FindElementByXPath("//*[@id='loginbutton']").Click
    .Wait 800
    .FindElementByXPath("//a[@id='findFriendsNav']").Click
    .Wait 500
End With

For x = 0 To 50
    driver.ExecuteScript "window.scrollTo(0, document.body.scrollHeight);"
    driver.Wait 500
Next x

Set posts = driver.FindElementsByXPath("//div[contains(@class,'friendBrowserNameTitle')]/a")

For Each post In posts
    i = i + 1
    Cells(i, 1) = post.Text
Next post

End Sub


texts:
I'm still pretty new to Ruby, and am really enjoying the language. I came across this method in my code base and realized that it could be cleaned up:

def friend_all_followers(friends)
  client.followers.each do |follower|
    if not friends.include?(follower.screen_name)
      friend = Friend.new(:screen_name => follower.screen_name)
      client.friendship_create(friend.screen_name, true)
      friend.save
    end
  end
end

So I took the above and changed it to this:

def friend_all_followers(friends)
  followers = client.followers.reject { |f| friends.include?(f) }
  followers.each do |follower|
    friend = Friend.new(:screen_name => follower.screen_name)
    client.friendship_create(friend.screen_name, true)
    friend.save
  end
end

One less level of nesting, and cleaner than the first method. But I look at this method and can't help but think there's still more to be done. Any ideas?

As some background Friend is an ActiveRecord class, client is a wrapper around a Twitter API, client.followers returns an array of follower objects - the objects I believe are just hashes, but I'm not 100% certain at the moment - and friends is a string array of screen_names.


texts:
I'm starting with Elixir and as exercise I wrote the Berlin Clock kata:

The clock is made up of 5 rows.
On the very top of the clock is a lamp that blinks to show the seconds. It turns on for one second, then off for one second, and so on.
The next 2 rows represent the hours. The upper most of these rows represents 5 hour blocks and is made up of 4 red lamps. The second row represents 1 hour blocks and is also made up of 4 red lamps.
The final two rows represent the minutes. The upper most row repesents 5 minute blocks and is made up of 11 lamps- every 3rd lamp red but the rest yellow. The second row represents 1 minute blocks and is made up of 4 yellow lamps.

Here's a picture:

The full code is available here.

import Integer, only: :macros

defmodule BerlinClock do
    def parse (time) do

        [h, m, s] = String.split(time, ":")
            |> Enum.map fn n -> Integer.parse(n)
            |> elem(0) end

        seconds = get_seconds(s)
        single_minutes = get_single_minutes(m)
        fives_minutes = get_fives_minutes(m)
        single_hours = get_single_hours(h)
        fives_hours = get_fives_hours(h)

        [seconds, fives_hours, single_hours, fives_minutes, single_minutes]
    end

    def get_fives_hours(h) do
        number_of_r = div(h, 5)
        String.ljust(String.duplicate("R", number_of_r), 4, ?O)
    end

    def get_single_hours(h) do
        number_of_r = rem(h, 5)
        String.ljust(String.duplicate("R", number_of_r), 4, ?O)
    end

    def get_fives_minutes(m) do
        number_of_y = div(m, 5)
        String.ljust(create_fives_minutes(number_of_y), 11, ?O)
    end

    def create_fives_minutes(1) do
        "Y"
    end

    def create_fives_minutes(n) when n < 1 do
        ""
    end

    def create_fives_minutes(n) when n > 1 do
        if rem(n,3) == 0 do
            light = "R"
        else
            light = "Y"
        end
        [create_fives_minutes(n-1), light ] |> Enum.join
    end

    def get_single_minutes(m) do
        number_of_y = rem(m, 5)
        String.ljust(String.duplicate("Y", number_of_y), 4, ?O)
    end

    def get_seconds(s) do
        cond do
            s |> even? -> "Y"
            s |> odd?  -> "O"
        end
    end
end


texts: Cythonized version of FDCT (fast discrete cosine transform) function, ported from Java


texts:
The below algorithm is supposed to take a list of input IPs/networks and a list of IPs/networks to exclude, and return a list of networks that don't include any of the IPs/networks to exclude...
Please review it and provide me with some feedback!
import ipaddress
from ipaddress import IPv4Network

def recurse_exclude(supernet_list, exclude_list):
    # For some reason, this only works if we force the generators into lists
    for supernet in list(supernet_list):
        for exclude in exclude_list:
            try:
                excluded_list = recurse_exclude(list(supernet.address_exclude(exclude)), exclude_list)
            except ValueError:
                # Ignore when the IP/net to exclude was not in the supernet
                continue
            else:
                return list(excluded_list)
    return supernet_list

supernet_list = [IPv4Network('1.1.0.0/24')]
output = recurse_exclude(supernet_list, exclude_list=[IPv4Network('1.1.0.0/25'),IPv4Network('1.1.0.128/26')])


texts:
I'm pretty confident in this code but I want to be sure I haven't missed anything to do with optimization or error handling. The program takes input in the form of {number} {operator} {number} and prints the result. If the input is invalid it prints nothing.

Example input: 1.0 + 2.0
Output: 3

#include <iostream>
#include <string>
#include <stdexcept>
#include <regex>

double calculate(const double a, const char op, const double b)
{
    switch (op)
    {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            if (b == 0.0)
                throw std::invalid_argument {"Divide by zero"};
            return a / b;
        default:
            throw std::invalid_argument {{op}};
    }
}

int main()
{
    const std::regex valid_input {
        "([0-9]*\\.?[0-9]*) ([\\+\\-\\*\\/]) ([0-9]*\\.?[0-9]*)"};

    std::string line;
    std::smatch terms;

    double a;
    double b;
    char op;

    while (std::getline(std::cin, line))
    {
        if (!std::regex_match(line, terms, valid_input))
            continue;

        a = std::stod(terms[1]);
        b = std::stod(terms[3]);
        op = terms[2].str().front();

        std::cout << calculate(a, op, b) << '\n';
    }
}


texts: Demonstration of the Largest Square Submatrix

texts:
Challenge

  Using the C++ language, have the function MaximalSquare(strArr) take the strArr parameter being passed which will be a 2D matrix of 0 and 1's, and determine the area of the largest square submatrix that contains all 1's. A square submatrix is one of equal width and height, and your program should return the area of the largest submatrix that contains only 1's. For example: if strArr is ["10100", "10111", "11111", "10010"] then this looks like the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

  For the input above, you can see the bolded 1's create the largest square submatrix of size 2x2, so your program should return the area which is 4. You can assume the input will not be empty.

  Sample Test Cases

Input:"0111", "1111", "1111", "1111"
Output:9

Input:"0111", "1101", "0111"
Output:1

How can I make improvements to my code? Is there any STL that I might not know of that might make the code simpler and/or efficient?

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

 bool check_Same_Length(std::vector< std::vector<int> > maximalSquareInput)
{
    bool state;

    size_t length = maximalSquareInput[0].size();

    for (int i = 0; i < maximalSquareInput.size(); ++i)
    {
        if (length == maximalSquareInput[i].size())
        {
            state = true;
        }
        else
        {
            state = false;

            return state;
        }
    }

    return state;
}

bool only_1_And_0(std::vector< std::vector<int> > maximalSquareInput)
{
    for (int i = 0; i < maximalSquareInput.size(); ++i)
    {
        if (!(std::all_of(maximalSquareInput[i].begin(), maximalSquareInput[i].end(),
                          [] (int digit) { return digit == 1 || digit == 0; })))
        {
            return false;
        }
    }

    return true;
}

int findBiggestElement(std::vector< std::vector<int> > maximalSquareOutput)
{
    int biggestElement = 0;

    for (int i = 0; i < maximalSquareOutput.size(); ++i)
    {
        auto itr = std::max_element(maximalSquareOutput[i].begin(), maximalSquareOutput[i].end());

        if (*itr > biggestElement)
        {
            biggestElement = *itr;
        }
    }

    return biggestElement;
}

std::string findLargestSubmatrix(const std::vector< std::vector<int> > maximalSquareInput)
{
    std::vector< std::vector<int> > maximalSquareOutput (maximalSquareInput.size(), std::vector<int>(maximalSquareInput[0].size()) );

    if(check_Same_Length(maximalSquareInput) && only_1_And_0(maximalSquareInput))
    {
        for (int row = 0; row < maximalSquareInput.size(); ++row)
        {
            for (int column = 0; column < maximalSquareInput[row].size(); ++column)
            {
                if (row == 0 || column == 0 || maximalSquareInput[row][column] == 0)
                {
                    maximalSquareOutput[row][column] = maximalSquareInput[row][column];
                }
                else
                {
                    int minElement = std::min({maximalSquareOutput[row-1][column], maximalSquareOutput[row-1][column-1], maximalSquareOutput[row][column-1]});

                    maximalSquareOutput[row][column] = maximalSquareInput[row][column] + minElement;
                }
            }
        }
    }

    unsigned long long int biggestElement = findBiggestElement(maximalSquareOutput);

    return std::to_string(biggestElement * biggestElement);
}


texts:
Recently I've attended an interview, where I faced the below question:

  Question: "There is an sorted array. You need to find all the missing numbers. Write the complete code, without using any generics
  or inbuilt function or binary operators. First and last terms will be
  given. Array will be sorted. Array always starts with zero."

  Example:

Input:
int array[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };

Output:
Missing number(s): 5, 16, 17, 19, 22.

  If its single missing term, we can calculate the required total using
  summation formula, and find the difference between the actual total.
  Which gives the missing term.

Since there are multiple values missing, I came up with below approach.

Code:

public class MissingNumber {

    public static int count = 0;
    public static int position = 0;
    public static boolean flag = false;

    public static void main(String[] args) {

        int a[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };

        findMissingNumbers(a, position);

    }

    private static void findMissingNumbers(int a[], int position) {

        if (position == a.length - 1)
            return;

        for (; position < a[a.length - 1]; position++) {

            if ((a[position] - count) != position) {
                System.out.println("Missing Number: " + (position + count));
                flag = true;
                count++;
                break;
            }
        }

        if (flag) {
            flag = false;
            findMissingNumbers(a, position);
        }
    }

}

Output:

Missing Number: 5
Missing Number: 16
Missing Number: 17
Missing Number: 19
Missing Number: 22

This gives the required solution. But, is the code fine or can this be done with a better approach?


texts:
This is my first attemp with Lua.
I decided to create this class, because it have lots of "tweaks" and "tricks".
I want to know if I did it as best practices Lua ways.
My Lua version is 5.4.1
require "math"

Complex = {
    IMAGINARY_CHAR = "i"
}

function Complex:new(r, i)
    o = {
        r = r,
        i = i
    }

    setmetatable(o, self)

    self.__index = self

    return o
end

function Complex:__newindex(r, i)
end

function Complex:__unm()
    return Complex:new(
        -self.r,
        -self.i
    )
end

function Complex:__add(other)
    if type(other) == "number" then
        return Complex:new(
            self.r + other,
            self.i
        )
    else
        return Complex:new(
            self.r + other.r,
            self.i + other.i
        )
    end
end

function Complex:__sub(other)
    return self:__add(- other);
end

function Complex:__mul(other)
    if type(other) == "number" then
        return Complex:new(
            self.r * other,
            self.i * other
        )
    else
        return Complex:new(
            self.r * other.r - self.i * other.i,
            self.i * other.r + self.r * other.i
        )
    end
end

function Complex:__eq(other)
    return
        self.r == other.r and
        self.i == other.i
end

function Complex:__lt(other)
    -- incorrect but for sorting
    if self.r == other.r then
        return self.i < other.i
    else
        return self.r < other.r
    end
end

function Complex:tostring(i)
    if type(i) ~= "string" then
        i = "i"
    end

    if self.r == 0 and self.i == 0 then
        return "( 0 )"
    elseif self.i == 0 then
        return "( " .. self.r .. " )"
--  elseif self.r == 0 then
--      return "( " .. i .. self.i .. " )"
    else
        return "( " .. self.r .. " + " .. i .. self.i .. " )"
    end
end

function Complex:__tostring(i)
    return self:tostring(self.IMAGINARY_CHAR)
end

function Complex:abs2()
    return self.r * self.r + self.i * self.i
end

function Complex:abs()
    return math.sqrt(self:abs2())
end

-- ===================================================================

Complex.IMAGINARY_CHAR = "j" -- Electrical notation

x = Complex:new(0, 10)
y = Complex:new(-5, 5)

print(x)
print(y)

print(x:abs())
print(y:abs())

print(x + y)
print(x - y)

print(x + 12)
print(x - 12)

print(x == y)
print(x ~= y)

print(x ~= x)
print(x ~= x)

print(x < y)
print(x > y)

print(x <= y)
print(x >= y)


texts:
Learning to code with python this is what i came up with. But looking at the code i am sure there are ways to improve. I would really appreciate a constructive review and some guidelines.

from itertools import cycle

game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]

player = [1, 2]

current_player = cycle(player)

def diagonal_win():
    if game[0][0] == game[1][1] == game[2][2] != 0:
        print('Winner')

    elif game[0][2] == game[1][1] == game[2][0] != 0:
        print('Winner')

def horizontal_win():
    for row in game:
        if row.count(row[0]) == len(row) and row[0] != 0:
            print('Winner')

def vertical_win():
    for col in range(len(game)):
        see = []
        for row in game:
            see.append(row[col])
        if see.count(see[0]) == len(see) and see[0] != 0:
            print('Winner')

def pick_player(current_player):
    if current_player == 1:
        p1rinput = input('Player 1 Row: ')
        p1cinput = input('Player 1 Column: ')
        if p1rinput.isdigit() and p1cinput.isdigit():
            p1rinput = int(p1rinput)
            p1cinput = int(p1cinput)
            print('Player 1: ')
            if game[p1rinput - 1][p1cinput - 1] == 0:
                game[p1rinput - 1][p1cinput - 1] = 1
            else:
                print('You cheated !!!Skipping turn...')
            return p1rinput, p1cinput

    if current_player == 2:
        p2rinput = input('Player 2 row: ')
        p2cinput = input('Player 2 column: ')
        if p2cinput.isdigit() and p2rinput.isdigit():
            p2cinput = int(p2cinput)
            p2rinput = int(p2rinput)
            print('Player 2: ')

            if game[p2rinput - 1][p2cinput - 1] == 0:
                game[p2rinput - 1][p2cinput - 1] = 2
            else:
                print('You cheated !!!Skipping turn...')

            return p2rinput, p2cinput

def gameplay():
    for items in game:
        print(items)
    while True:
        if vertical_win():
            break
        elif horizontal_win():
            break
        elif diagonal_win():
            break

        else:
            pick_player(next(cycle(current_player)))
            for items in game:
                print(items)

gameplay()


texts: Determining if a sentence is a palindrome

texts:
The biggest problem I see in checking palindromes on the Internet is when the user inputs a palindrome sentence or phrase and the program returns a wrong output. So for me, I tried to optimize palindrome checking by accepting sentences as input.

import java.io.*;

public class PalindromeCheck{

  public static void main(String[] args){

    BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
      try{

        System.out.print("Enter a sentence: ");
          String sentence = dataIn.readLine();
          PalCheck(sentence);

      }catch(IOException e){

        e.printStackTrace();
        System.err.println(e);

      }
    }

  public static void PalCheck(String s){

    String end = "";
    String result = s.replaceAll(" ", "");
     for ( int i = result.length() - 1; i >= 0; i-- )
       end = end + result.charAt(i);

        if (result.equalsIgnoreCase(end))
           System.out.println( result + " is a palindrome.");
        else
           System.out.println(result + " is not a palindrome.");

  }

}


texts: Returning the path to PHP pages for a layout and a view, if they exist

texts:
I have these two functions.

function layout($layout) {
    $layout = Config::get('path/layouts') . '/' . $layout . '.layout.php';
    if (!file_exists($layout)) {
        throw new CoreException($layout . ' layout is not found');
    }
    return $layout;
}

function page($page) {
    $page = Config::get('path/pages') . '/' . $page. '.view.php';
    if (!file_exists($page)) {
        throw new CoreException($page . ' page is not found');
    }
    return $page;
}

Is there a way to avoid repeated parts?


texts: How to differentiate web fonts font-face font-weights?

texts:
What do you guys think:

OPTION #1 (same font-face name and change font-weight)

@font-face {
  font-family: ProximaNova;
  src: url('/fonts/ProximaNova-Regular.ttf');
  font-weight: normal;  // THIS IS NORMAL
  font-style: normal;
}
@font-face {
  font-family: ProximaNova;
  src: url('/fonts/ProximaNova-Semibold.ttf');
  font-weight: bold;   // THIS IS SEMI-BOLD
  font-style: normal;
}
@font-face {
  font-family: ProximaNova;
  src: url('/fonts/ProximaNova-Bold.ttf');
  font-weight: 900;   // THIS IS BOLD
  font-style: normal;
}

Then all my elements would use the font-family: ProximaNova and I would control the weight with the font-weight property, using bold and 900 values.

OPTION #2 (change the font-face name itself to control weight):

@font-face {
  font-family: ProximaNova;
  src: url('/fonts/ProximaNova.ttf');
  font-weight: normal;  // ALWAYS NORMAL
  font-style: normal;
}
@font-face {
  font-family: ProximaNovaSemiBold;   // THIS IS SEMIBOLD
  src: url('/fonts/ProximaNova-Semibold.ttf');
  font-weight: normal;  // ALWAYS NORMAL
  font-style: normal;
}
@font-face {
  font-family: ProximaNovaBold;       // THIS IS BOLD
  src: url('/fonts/ProximaNova-Bold.ttf');
  font-weight: normal;  // ALWAYS NORMAL
  font-style: normal;
}

Then I would control the weight by selecting different font-family names, like ProximaNova, ProximaNovaSemiBold and ProximaNovaBold and the font-weight would always be normal.

What would you go for?


texts: Make a git repository read-only over ssh depending on the key used

texts:
I want a git repository, accessible over ssh, to be read-only when used with certain keys. With other keys access to the full system is okay.

Here is my solution.

git-readonlyshell:

if echo "$2" | egrep -q ^git-upload-pack; then
  sh -c "$2"
else
  echo Error: read only access 1>&2
fi

.ssh/authorized_keys:

command="./git-readonlyshell -c \"$SSH_ORIGINAL_COMMAND\"" ...

Thoughts?

Any scenario in which this would break?


texts: Bash script to generate and change Java keystore passwords

texts:
This is the first Bash script I've written, so I'm looking for feedback on best practices, conventions, things like that.

This script makes a few assumptions

There is a java keystore stored at ~/.keystore
There is an alias for an entry in that keystore with a value of test
Both the keystore and entry share the same initial password
That shared password is test

After that, for both the keystore and key entry, it pulls a number of bytes from /dev/urandom, Base64 encodes them, and sets that as the password.

#!/bin/bash

keystore_file=~/.keystore
config_file=~/.keystore.config
alias_name=test
initial_password=test

generate_password() {
    local password_length=$1
    local password="$(dd if=/dev/urandom bs=$password_length count=1 | base64 -w 0)"
    echo $password
}

set_keystore_password() {
    local password_length=80
    local password=$(generate_password $password_length)
    keytool -storepasswd -keystore $keystore_file -storepass $initial_password -new $password
    echo $password >> $config_file
    echo $password
}

set_key_password() {
    local keystore_password=$1
    local password_length=80
    local password=$(generate_password $password_length)
    keytool -keypasswd -keystore $keystore_file -storepass $keystore_password -alias $alias_name -keypass $initial_password -new $password
    echo $password >> $config_file
}

initialize_keystore() {
    if [ -f $config_file ]
    then
        rm $config_file
        touch $config_file
    fi

    local keystore_password=$(set_keystore_password)
    set_key_password $keystore_password
}

initialize_keystore


texts: Pattern for storing object of varying type

texts:
I have a situation where I need to store fields of differing types of some data structures along with some similar metadata (The application takes data from one of many sources, some data possibly coming from more than one source, and then does stuff with it).

The solution I came up with was to create a class that would hold each piece of data which I could then add to each object. The DataParam object can be loaded with any data type that's determined when it's first constructed. When we get or set it later, those methods are passed a class type similar to what we are getting or setting. Since we always check against the value we originally "typed" our object with, we can never accidentally set it to some other type of value (and mess everything up).

The reason these are all generic methods and the entire class isn't a generic is because I need to store DataParam in a container and that wouldn't be possible if the class itself was a generic (I can't store a DataParam<String>, and a DataParam<int> in one container).

public class DataParam
{
    public String name
    public boolean wasUpdated
    private String type
    private boolean isArray
    private Object data;

    public <T> DataParam(String name, Class<T> typeClass)
    {
        this.name = name;
        type = typeClass.getName();
        isArray = typeClass.isArray();
        data = null;
        wasUpdate = false;
    }
    public <T> T get(Class<T> typeClass)
    {
        if(type.equals(typeClass.getName()) && isArray == typeClass.isArray())
            return typeClass.cast(data);
        else
            return null;
    }
    public <T> T set(T obj, Class<T> typeClass)
    {
        if(type.equals(typeClass.getName()) && isArray == typeClass.isArray())
            data = (Object) obj;
    }
    public String doSomething()
    {
        //An example of doing different things based on type
        switch(type)
        {
        case "java.lang.String":
            if(isArray)
                return TakesAStringArray(get(String[].class));
            else
                return TakesAString(get(String.class));
        break;
        case "java.lang.Integer":
            return TakesAnInteger(get(Integer.class));
        break;
        case "myPackage.DataParam":
            return TakesADataParam(get(myPackage.DataParam.class));
        break;
        //default: Do nothing
    }
}
public DataObj
{
    protected HashMap<String,DataParam> fields;
    //Other functions
}
public SpecificObj extends DataObj
{
    public SpecificObj()
    {
        fields.add(new DataParam("name", String.class));
        fields.add(new DataParam("obj", myPackage.DataParam.class));
        fields.add(new DataParam("count", Integer.class));
    }
}

My questions are, is there anything blatantly obviously wrong with this, like I'm gonna screw myself over later? Is there a better way that I should consider?

This should be type safe, right? (I'm checking the class every time I do anything with that piece of data, but it just seems weird that I have to do it myself versus like, the compiler raising an error that I'm doing it wrong).


texts:
This is quite a simple function, but I just wanted some opinions on it, like is this the correct way to run a function and check if an element exists or not?

const button = document.querySelector('.js-brand-video--thumbnail')
const iframe = document.querySelector('.js-brand-video--iframe')

function playVideo () {
  if (button) {
    button.classList.add('video-poster--hidden')
    iframe.src = iframe.getAttribute('data-src')
  }
}

if (button)
  button.addEventListener('click', playVideo, false)


texts: Custom login system (PDO, sanitizing, hash)

texts:
I have made a custom login form for my site, with the help of PDO (until now I used simple MySQL connection and sanitizing), and it looks like this:

session_name('NEWCOOKIE');
session_start();

require_once "config.php";

$member_username = $_POST['username'];
$member_password = $_POST['password'];
    $crypt_pass = crypt($member_password,"somesalt");

try{
    $dbh = new PDO('mysql:host=localhost;dbname='.DB_NAME, DB_USERNAME, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
    echo "Fatal error.";
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}

$sth = $dbh->prepare("SELECT * FROM ".DB_PREFIX."_users WHERE username = :user AND password = :pass");
$sth->bindParam(':user', $member_username);
$sth->bindParam(':pass', $crypt_pass);
$sth->execute();
$total = $sth->rowCount();
$row = $sth->fetch();

if($total > 0){
    if($row['activated']){
        $_SESSION["user_username"] = $member_username;
        $_SESSION["user_logedIn"] = true;
        $_SESSION["user_id"] = $row['user_id'];
        $_SESSION["timeout"] = time();
        header("location: index.php");
    }
    else{
        echo "ACCOUNT NOT ACTIVE";
    }
}
else{
    echo "WRONG PASSWORD OR USERNAME";
}

Is this safe? I know that nothing is 100% safe, but I have a small number of users (around 200-300), and 1000 visitors a month, so I don't expect very "professional" attacks and programming experts.

My questions are:

As you can see, I don't use sanitizing at all.  I thought that PDO will do that part of the job, or I am wrong?
I hope that crypting of password is good (with no MD5 or SHA, is crypt() recommended)?
File config.php contains username and pass of my database. Should I protect it somehow, what permissions to set?
Any other (serious) problem with this code?


texts: Google Maps API - reading locations from file and displaying markers on map

texts:
I'm working with Google Maps and want to read in location objects into the map. I'm loading them in from a .csv file and create Shelter objects for each location that I save in an ArrayList. To actually add them to the map I iterate through this ArrayList and create marker objects with each object's data. Each actual Marker object created is also saved into another ArrayList so that I can reference them later (show/hide them on map when wanted). I feel like I'm doing something wrong. I included the relevant methods below.

private ArrayList<ShelterObject> shelterObjects;
private ArrayList<Marker> shelterMarkers;

// Generates the Shelter objects from the csv file and adds them to the  ArrayList.
private void generateShelterObjects()
{
    shelterObjects = new ArrayList<>();

    Log.i("SHELTER_TEST", "METHOD generateShelterObjects() STARTED");

    InputStream is = getResources().openRawResource(R.raw.shelters_csv_file);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(is, Charset.forName("UTF-8")));
    String line = "";

    try {
        while ((line = reader.readLine()) != null) {
            // Split the line into different tokens (using the comma as a separator).
            String[] tokens = line.split(",");

            String address = tokens[0];
            double latitude = Double.parseDouble(tokens[1]);
            double longitude = Double.parseDouble(tokens[2]);
            int numberOfOccupants = Integer.parseInt(tokens[3]);

            ShelterObject object = new ShelterObject(address, latitude, longitude, numberOfOccupants);
            shelterObjects.add(object);

        }

    } catch (IOException e1) {
        Log.e("MapsActivity2", "Error" + line, e1);
        e1.printStackTrace();
    }
    Log.i("SHELTER_TEST", "The size of the arraylist after reading in objects: " + shelterObjects.size());
}

// Iterates through the ArrayList of Shelter objects and adds a marker with data from that object to the map. The markers are saved in another ArrayList so they can be referenced later.
private void addShelterMarkersToMap()
{
    shelterMarkers = new ArrayList<>();

    for (ShelterObject obj : shelterObjects) {
        LatLng latLng = new LatLng(obj.getLatitude(), obj.getLongitude());
        Marker marker = mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .title(obj.getAddress())
                .snippet("Antal platser: " + obj.getNumberOfOccupants()));
        shelterMarkers.add(marker);
    }
}


texts:
I am trying to solve this question: MaxCounters.

Solving it is straightforward, but solving it fast enough is proving very difficult. How can I improve the performance of this code? At the moment it is too slow for the large_random_2 and extreme_large tests.

function solution(N, A) {
    const M = A.length;
    let max = 0;
    let counters = new Array(N);

    if (M <= 0) {
        return -1;
    }

    // set counters to 0
    for (let i = 0; i < N; i++) {
        counters[i] = 0;
    }

    for (let K = 0; K < M; K += 1) {
        if (A[K] === N + 1) {
            // set counters to last maximum
            for (let j = 0; j < N; j++) {
                counters[j] = max;
            }
        } else if (A[K] > 0 && A[K] <= N) {
            // add one to counter
            counters[A[K] - 1] = counters[A[K] - 1] + 1;
            // update maximum
            if (counters[A[K] - 1] > max) {
                max = counters[A[K] - 1];
            }
        }
    }

    return counters;
}


texts: Keep main content scrollable but not the body

texts:
For a template such as:

I'm using the following approach

Get the height of the viewport via javascript (Let's say 500px)
Deduct the header and footer height from it (Let's say header and footer are 50px each. So the end result will be 400px)
Apply the end result as height of the main content div via javascript
Use overflow-y:scroll property on the main content div via CSS

This works as expected but I was hoping there might be a better way to achieve the same. I'm thinking only via CSS, if possible.

The code I'm using is:

<!-- javascript -->
var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var to_apply_height = height - 50 -50; // header and footer height
document.getElementById('main_content').style.height = to_apply_height+'px';

<!-- css -->
#main_content{
overflow-y:scroll;
}


texts: Delete the characters of one string from another string

texts:
I've got an interview coming up for which the following is a prospective question:

  Given 2 strings, for instance:

  John Lennon
  Paul ON

  delete every character from string 1 which corresponds with any
  character in string 2 (case exclusive).

  So following the anticipated manipulations, the output in our case
  would be:

    Jhe

I've devised the following program for the same:

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.printf("Enter 2 strings%n");
    String s1,s2,s3;
    s1=br.readLine();
    s2=br.readLine();
    s3="[";
    for(int j=0;j<s2.length();j++)
    {
       s3+=Character.toLowerCase(s2.charAt(j));
       s3+=Character.toUpperCase(s2.charAt(j));
    }
    s3+="]";
    Pattern p = Pattern.compile(s3);
    Matcher m = p.matcher(s1);
    int[] a = new int[10];
    int k=0;
    while(m.find())
    {
        a[k]=m.start();
        k++;
    }
    int j=0;
    for(int i=0;i<k;i++)
    {
        System.out.print(s1.substring(j, a[i]));
        j=a[i]+1;
    }
    System.out.print(s1.substring(j));

This works seamlessly, but my predicament is that these folks don't want you to just get a bloody veracious output, they want a highly optimized output i.e. spatial and temporal requirements as to your program should to be as minimum as can be. And mine is nowhere near the epitome of the optimal solution

If anybody feels that they can alter my code or come up with something better that'd be optimal, I'd be much obliged!


texts: Returning JSON depending on the route_id

texts:
I have a controller that has a purpose of returning json depending on the route_id being passed from the route (Using laravel). There's a point in my code where I resorted to using a double nested foreach loop in order to iterate the values I want to be stored into an array. Everything works fine, but I feel like the code is messy. Any tips?

public function getRoute($id)
{
    $route = Route_log::find($id);
    $allWayPoints = explode(";", $route->route_order);
    $firstWaypoint = array_shift($allWayPoints); //get first waypoint

    foreach($allWayPoints as $allWayPoint)
        {
            $allOrdersInWaypoint = Transaction::where('waypoint_id', "=", $allWayPoint)->where('type', "=", "DD")->get()->lists('order_id');
            $allOrders[] = array($allOrdersInWaypoint);
        }
  ///**THIS PART**
    foreach($allOrders as $allOrder)
    {
        foreach($allOrder as $aO)
        {
            foreach($aO as $a)
            {
                $otherOrders = Order::find($a);

                if(isset($otherOrders))
                {
                $getOtherOrders[] = array(
                                            'id'             => $otherOrders->id,
                                            'tracking_id'    => $otherOrders->tracking_id,
                                            'shipper_ref_no' => $otherOrders->shipper_ref_no);
                }
            }
        }
    }

    //get all transactions within the first way point
    $ordersInWaypoint = array();
    $ordersInWaypoint = Transaction::where('waypoint_id', "=", $firstWaypoint)->where('type', "=", "PP")->get()->lists('order_id');

    //get order id, tracking_id, and shipper ref no and store into an array
    foreach($ordersInWaypoint as $ordersInWaypoints)
        {
            $order = Order::find($ordersInWaypoints);

            //this array stores id, trackingId, and shipper_ref_no per order
            $getOrder[] = array(
                                'id'             => $order->id,
                                'tracking_id'    => $order->tracking_id,
                                'shipper_ref_no' => $order->shipper_ref_no);
        }

    $json = (array('first_waypoint' => $getOrder, 'remaining_waypoints' => $getOtherOrders));

    return $json;
}

}

To show an example array inside $allOrders:

 array (size=20)
   0 =>
     array (size=1)
      0 =>
         array (size=2)
           0 => int 491
           1 => int 494
   1 =>
     array (size=1)
       0 =>
         array (size=0)
           empty
   2 =>
     array (size=1)
       0 =>
         array (size=1)
           0 => int 498
   3 =>
     array (size=1)
       0 =>
         array (size=2)
           0 => int 487
           1 => int 493
   4 =>
     array (size=1)
       0 =>
         array (size=1)
           0 => int 503
   5 =>
     array (size=1)
       0 =>
         array (size=1)
           0 => int 480
   6 =>
     array (size=1)
       0 =>
         array (size=1)
           0 => int 476
   7 =>
     array (size=1)
       0 =>
         array (size=1)
           0 => int 482
   8 =>
     array (size=1)
       0 =>
         array (size=1)
           0 => int 515


texts: Leaflet map distance from the onclick marker

texts:
Here is the part of working code:

  function SelectPoints(lat,lon){
var dist = document.getElementById("miles").value;

xy = [lat,lon];  //center point of circle

var theRadius = parseInt(dist) * 1609.34  //1609.34 meters in a mile
//dist is a string so it's convered to an Interger.

selPts.length =0;  //Reset the array if selecting new points

  job.eachLayer(function (layer) {
    // Lat, long of current point as it loops through.
    layer_lat_long = layer.getLatLng();

    // Distance from our circle marker To current point in meters
    distance_from_centerPoint = layer_lat_long.distanceTo(xy);

    // See if meters is within radius, add the to array
    if (distance_from_centerPoint <= theRadius && $('#cf').is(":checked")) {
     selPts.push(layer.feature);
}
})

    job2.eachLayer(function (layer) {
    // Lat, long of current point as it loops through.
    layer_lat_long = layer.getLatLng();

    // Distance from our circle marker To current point in meters
    distance_from_centerPoint = layer_lat_long.distanceTo(xy);

    // See if meters is within radius, add the to array
    if (distance_from_centerPoint <= theRadius && $('#vm').is(":checked")) {
     selPts.push(layer.feature);
}
})

job3.eachLayer(function (layer) {
    // Lat, long of current point as it loops through.
    layer_lat_long = layer.getLatLng();

    // Distance from our circle marker To current point in meters
    distance_from_centerPoint = layer_lat_long.distanceTo(xy);

    // See if meters is within radius, add the to array
    if (distance_from_centerPoint <= theRadius && $('#bt').is(":checked")) {
     selPts.push(layer.feature);
}
})

but it looks like it's going to be repeatable over next few layers. So far is only 3 layers job, job2 and job3, what doesn't look bad, but I am worried about the future.

Does anyone knows how to make this code a bit shorter?

Thanks & Regards,