text:
\chapter{Tree}

\section{Binary Tree}
\subsection{Basic Operations}
\runinhead{Get parent ref.} To get a parent reference (implicitly), \textit{return the Node} of the current recursion function to its parent to maintain the path. Sample code:
\begin{java}
Node deleteMin(Node x) {
    if (x.left == null) return x.right;
    x.left = deleteMin(x.left);
    return x;
}
\end{java}

\runinhead{Max depth.} DFS solution
\begin{python}
def fathom(self, root, depth):
    if not root: return depth
    else: return max(self.fathom(root.left, depth+1),
                     self.fathom(root.right, depth+1))
\end{python}

\runinhead{Min depth.} Definition of min depth, lowest depth of leaf node.

Notice, that the additional checking is necessary.
\begin{python}
def fathom(self, root, depth):
    if not root:
        return depth
    elif root.right and not root.left:
        return self.fathom(root.right, depth+1)
    elif root.left and not root.right:
        return self.fathom(root.left, depth+1)
    else:
        return min(self.fathom(root.left, depth+1),
                   self.fathom(root.right, depth+1))
\end{python}

\runinhead{Height.} The height of a node is the number of edges from the node to the deepest leaf.

\begin{python}
def dfs(self, node):
    if not node:
        return -1  # leaves index start from 0

    height = 1 + max(
        self.dfs(node.left),
        self.dfs(node.right)
    )

    # do something

    return height
\end{python}

Application: leaf by leaf traversal.
\begin{python}
def dfs(self, node, leaves):
    if not node:
        return -1  # leaves index start from 0

    height = 1 + max(
        self.dfs(node.left, leaves),
        self.dfs(node.right, leaves)
    )
    if height >= len(leaves):
        leaves.append([])  # grow

    leaves[height].append(node.val)
    return height
\end{python}
\runinhead{Construct path from root to a target.} To search a node in binary tree (not necessarily BST), use dfs:
\begin{python}
def dfs(self, root, t, path, found):
    # post-call check
    if not root: return
    if found[0]: return

    path.append(root)
    if root == t:
        found[0] = True

    self.dfs(root.left, t, path, found)
    self.dfs(root.right, t, path, found)
    if not found[0]:
        path.pop()  # 1 pop() corresponds to 1 append()
\end{python}
The \pyinline{found} is a wrapper for boolean to keep it referenced by all calling stack.

\runinhead{Lowest common ancestor.} Method 1: In BST, the searching is straightforward. In normal binary tree, construct the path from root to $node_1$ and $node_2$ respectively, and \textbf{diff} the two paths. Time complexity: $O(\lg n)$, space complexity: $O(\lg n)$.

Method 2: If the parent pointer is provided, it is possible to reduce the space complexity to $O(1)$, by using two pointers:
\begin{python}
def find_LCA(n1, n2):
    if not n1 or not n2:
        return None

    d1, d2 = depth(n1), depth(n2)
    if d2 < d1:
        return find_LCA(n2, n1)  # swap

    # move to the same depth
    for _ in xrange(d2-d1):
        n2 = n2.parent

    while n1 and not n1 == n2:
        n1 = n1.parent
        n2 = n2.parent

    return n1
\end{python}

\runinhead{Find all paths.} Find all paths from root to leafs. For every currently visiting node, add itself to path; search left, search right and pop itself. Record current result when reaching the leaf.
\begin{python}
def dfs(self, cur, path, ret):
    if not cur: return

    path.append(cur)
    if not cur.left and not cur.right:
        ret.append("->".join(map(repr, path)))

    self.dfs(cur.left, path, ret)
    self.dfs(cur.right, path, ret)
    path.pop()
\end{python}

\runinhead{Leftmost node.} Find the leftmost node.
\begin{python}
def leftmost(self, cur, l):
    """
    :param l: offset from center 0, negative means left side.
    """
    if not cur: return l
    return min(self.leftmost(cur.left, l-1),
               self.leftmost(cur.right, l+1))
\end{python}

Rightmost node can be similarly found.

\runinhead{Diameter of a tree (graph).} The diameter of a tree $\equiv$ longest path in the tree.

Core clues:
\begin{enumerate}
\item Start from any vertex, bfs to reach the farthest leaf.
\item Start from this leaf node, bfs to reach the other farthest leaf.
\end{enumerate}
\begin{python}
_, _, last = self.bfs(0, V)
level, pi, last = self.bfs(last, V)

def bfs(self, s, V):
    # bfs
    visited = [False for _ in xrange(len(V))]
    pi = [-1 for _ in xrange(len(V))]
    last = s
    level = 0
    q = [s]
    while q:
        l = len(q)
        for i in xrange(l):
            cur = q[i]
            last = cur
            visited[cur] = True
            for nbr in V[cur]:
                if not visited[nbr]:
                    pi[nbr] = cur
                    q.append(nbr)

        q = q[l:]
        level += 1

    return level, pi, last
\end{python}

, where $V$ is the vertices of graph $G$.

\newpag
\subsection{Morris Traversal}
Traversal with O(1) space. \footnote{\href{http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html}{ref}}
Three ways of traversal: in-order, pre-order, post-order.
Time complexity $O(3n).$ - find \pyinline{pre} twice, \pyinline{cur} traverse once.
\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[height=1.2in]{morris_time}}
\caption{Morris traversal time complexity}
\label{fig:morrisTime}
\end{figure}

Core:
\begin{enumerate}
\item Threading from \textbf{in-order} predecessor to \pyinline{cur}.
\item In-order consumes the \pyinline{cur} when going right, pre-order when going left, post-order consumes the left subtree path when going right.
\end{enumerate}

\end{enumerate}
\subsubsection{In-order}
Assign the current node's in-order predecessor's right child to itself (threading). Two ptr \pyinline{cur}, \pyinline{pre}.

Process:
\begin{enumerate}
\item If no left, \textit{consume} \pyinline{cur}, go right
\item If left, find in-order predecessor \pyinline{pre}
\begin{enumerate}
\item If no thread (i.e. no \pyinline{pre} right child), assign it to \pyinline{cur}; go left
\item If thread, \textit{consume} \pyinline{cur}, go right. ($\equiv$ no left).
\end{enumerate}
\end{enumerate}

\begin{figure*}[!htb]
\centering
\subfloat{\includegraphics[height=2.45in]{morris_inorder}}
\caption{Morris in-order traversal}
\label{fig:morrisInorder}
\end{figure*}
\newpag
Code:
\begin{python}
def morris_inorder(self, root):
    cur = root
    while cur:
        if not cur.left:
            self.consume(cur)
            cur = cur.right
        else:  6
            pre = cur.left
            while pre.right and pre.right != cur:
                pre = pre.right

            if not pre.right:
                 6  pre.right = cur
                cur = cur.left
            else:
                pre.right = None
                self.consume(cur)
                cur = cur.right
\end{python}
\subsubsection{Pre-order}
Similar to in-order. Pre-order consume the current node when setting the thread rather than removing the thread as in in-order.

Process:
\begin{enumerate}
\item If no left, \textit{consume} \pyinline{cur}, go right
\item If left, find in-order predecessor \pyinline{pre}
\begin{enumerate}
\item If no thread (i.e. no \pyinline{pre} right child), assign it to \pyinline{cur}; \textit{consume} \pyinline{cur}, go left
\item If thread, go right. ($\equiv$ no left, but no \textit{consume}, since consume before).
\end{enumerate}
\end{enumerate}
Code:
\begin{python}
def morris_preorder(self, root):
    cur = root
    while cur:
        if not cur.left:
            self.consume(cur)
            cur = cur.right
        else:
            pre = cur.left
            while pre.right and pre.right != cur:
                pre = pre.right

            if not pre.right:
                pre.right = cur
                self.consume(cur)
                cur = cur.left
            else:
                pre.right = None
                cur = cur.right
\end{python}
\subsubsection{Post-order}
More tedious but solvable. The process is also similar to in-order.

Process:
\begin{enumerate}
\item Set a temporary var \pyinline{dummy.left = root}
\item If no left, go right
\item If left, find the in-order predecessor \pyinline{pre} in left tree
\begin{enumerate}
\item If no thread, set \pyinline{right = cur} thread; go left.
\item If thread,  set \pyinline{right = None}, reversely \textit{consume} the path from \pyinline{cur.left} to \pyinline{pre}; go right.
\end{enumerate}
\end{enumerate}
\begin{figure*}[!htb]
\centering
\subfloat{\includegraphics[height=2.8in]{morris_postorder}}
\caption{Morris post-order traversal}
\label{fig:morrisInorder}
\end{figure*}
Code:
\begin{python}
def morris_postorder(self, root):
    dummy = TreeNode(0)
    dummy.left = root
    cur = dummy
    while cur:
        if not cur.left:
            cur = cur.right
        else:
            pre = cur.left
            while pre.right and pre.right != cur:
                pre = pre.right

            if not pre.right:
                pre.right = cur
                cur = cur.left
            else:
                pre.right = None
                self.consume_path(cur.left, pre)
                cur = cur.right

def _reverse(self, fr, to):
    """Like reversing linked list"""
    if fr == to: return
    cur = fr
    nxt = cur.right
    while cur and nxt and cur != to:
        nxt.right, cur, nxt = cur, nxt, nxt.right

def consume_path(self, fr, to):
    self._reverse(fr, to)

    cur = to
    self.consume(cur)
    while cur != fr:
        cur = cur.right
        self.consume(cur)

    self._reverse(to, fr)
\end{python}

\section{Binary Search Tree (BST)}
\runinhead{Array and BST.}Given either the \textbf{preorder} or \textbf{postorder} (but not inorder) traversal of a BST containing N distinct keys, it is possible to reconstruct the shape of the BST.
\subsection{Property} $\forall$ node, the node value is larger than the largest value in its left subtree; and is smaller than the smallest value in the righhht subtree:
$$
\max(node.left) \leq node.val \leq \min(node.right)
$$

Leftmost node is the smallest node of the tree; rightmost node is the largest node of the tree.

Find such info takes $O(n\lg n)$ for all subtrees; and we can cache such info into the following data structure to achieve $O(n)$.

\begin{python}
class BSTInfo(object):
    def __init__(self, sz, lo, hi):
        self.sz = sz
        self.lo = lo
        self.hi = hi
\end{python}
\subsection{Rank}
\runinhead{Calculates rank.}
\begin{enumerate}
\item When inserting:
  \begin{enumerate}
  \item insert to an existing node: \pyinline{node.cnt_this += 1}
  \item insert to left subtree: \pyinline{node.cnt_left += 1}
  \item insert to right subtree: do nothing.
\end{enumerate}
\item When querying rank:
  \begin{enumerate}
  \item query equals current node: \pyinline{return node.cnt_left}
  \item query goes to \textbf{left} node: \pyinline{return rank(node.left, val)};
  \item query goes to \textbf{right} node: \pyinline{return node.cnt_left} \pyinline{+ node.cnt_this + rank(node.right, val)}
  \end{enumerate}
Notice that the \pyinline{rank} calculates a val's rank in a subtree.
\end{enumerate}

\runinhead{Count of smaller number before itself.} Given an array $A$. For each element $A_i$ in the array, count the number of element before this element $A_i$ is smaller than it and return count number array. Average $O(n \log n)$
\\
Clues:
\begin{enumerate}
\item Put $A[:i+1]$ into a BST; so as to count the rank of $A[i]$ in the BST
\end{enumerate}
Codes:
\begin{python}
class Node(object):
  def __init__(self, val):
    """Records the left subtree size"""
    self.val = val
    self.cnt_left = 0
    self.cnt_this = 0
    self.left, self.right = None, None

class BST(object):
  def __init__(self):
    self.root = None

  def insert(self, root, val):
    """
    :return: subtree's root after insertion
    """
    if not root:
      root = Node(val)

    if root.val == val:
      root.cnt_this += 1
    elif val < root.val:
      root.cnt_left += 1
      root.left = self.insert(root.left, val)
    else:
      root.right = self.insert(root.right, val)

    return root

  def rank(self, root, val):
    """
    Rank in the root's subtree
    :return: number of items smaller than val
    """
    if not root:
      return 0
    if root.val < val:
      return (root.cnt_this+root.cnt_left+
              self.rank(root.right, val))
    elif root.val == val:
      return root.cnt_left
    else:
      return self.rank(root.left, val)

class Solution(object):
  def countOfSmallerNumberII(self, A):
    tree = BST()
    ret = []
    for a in A:
      tree.root = tree.insert(tree.root, a)
      ret.append(tree.rank(tree.root, a))

    return ret
\end{python}
Notice: if worst case $O(n \log n)$ is required, need to use Red-Back Tree - Section \ref{rbtree}. However, there is a more elegant way using Segment Tree - Section \ref{segmentTreeInversionCount}.

\subsection{Range search}
\runinhead{1-d range count}
\begin{java}
int size(Key lo, Key hi) {
    if (contains(hi)) return rank(hi)-rank(lo)+1;
    else              return rank(hi)-rank(lo);
}
\end{java}

\runinhead{Closest value} Find the value in BST that is closet to the \pyinline{target}.
\\
Clues:
\begin{enumerate}
\item Find the value just $\leq$ the target.
\item Find the value just $\geq$ the target.
\end{enumerate}
\
\\
Code for finding either the lower value or higher value:
\begin{python}
def find(self, root, target, ret, lower=True):
  """ret: result container"""
  if not root: return

  if root.val == target:
    ret[0] = root.val
    return

  if root.val < target:
    if lower:
      ret[0] = max(ret[0], root.val)

    self.find(root.right, target, ret, lower)
  else:
    if not lower:
      ret[0] = min(ret[0], root.val)

    self.find(root.left, target, ret, lower)
\end{python}

\runinhead{Closet values} Find $k$ values in BST that are closet to the \pyinline{target}.
\\\\
Clues:
\begin{enumerate}
\item Find the predecessors $\triangleq \{node | node.value \leq target\}$. Store in the stack.
\item Find the successors $\triangleq \{node | node.value \geq target\}$. Store in the stack.
\item Merge the predecessors and successors as in merge in MergeSort to get the $k$ values.
\end{enumerate}
\
\\
Code for finding the predecessors:
\begin{python}
def predecessors(self, root, target, stk):
  if not root: return

  self.predecessors(root.left, target, stk)
  if root.val <= target:
    stk.append(root.val)
    self.predecessors(root.right, target, stk)
\end{python}

\section{Binary Index Tree (BIT)}\label{BIT}
\subsection{Introduction}
Compared to Segment Tree \ref{section:segmentTree}, BIT is shorter and more elegant. BIT can do most of things that Segment Tree can do and it is easier to code. BIT updates and queries $$i\rightarrow prefixSum$$ in $O(\log n)$ time; however, Segment Tree can but BIT cannot query $$prefixSum \rightarrow i$$
\subsection{Implementation}
Given an array $A$ of length $n $ starting from $1$. prefix sum $s[i]\triangleq A_1+...+A_i$. BIT uses binary to maintain the array of prefix sum for querying and updating. For $i$-th node in the BIT,
$$
N[i]=A_{j+1}+...+A_i
$$
, where $j=i-lowbit(i)$, i.e. set $i$'s lowest bit 1 to 0. $lowbit(i)$ can be defined as \pyinline{return i & -i}, using 2's complement. Notice that the summation ends with $A_i$ since easier to \pyinline{set}.

For the range, we use $(j, i]$ here instead of $[j, i)$ since more elegant for \pyinline{get(i)} and \pyinline{set(i)}
\\\\
Clues:
\begin{enumerate}
\item Binary
\item Low bit
\item BIT uses array index starting from \textbf{1}, because 0 doesn't have $lowbit$. 0 is the dummy root.
\end{enumerate}
\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[height=1.1in]{BITget}}
\caption{Binary Indexed Tree \textit{get} Operation}
\label{fig:LABEL}
\end{figure}

\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[height=1.05in]{BIT}}
\caption{Binary Indexed Tree \textit{set} Operation}
\label{fig:LABEL}
\end{figure}

Time complexity, longest update is along the leftmost branch, which takes $O(\log_2 n)$ (e.g. 1, 10, 100, 1000, 10000); longest query is along a branch starting with node with all 1's (e.g. 1111, 1110, 1100, 1000), which also takes $O(\log_2 n)$.

Code:
\begin{python}
class BIT(object):
    def __init__(self, n):
        """
        BIT uses index starting from 1
        0 is the dummy root
        """
        self.N = [0 for _ in xrange(n+1)]

    def lowbit(self, i):
        return i & -i

    def get(self, i):
        ret = 0
        while i > 0:
            ret += self.N[i]
            i -= self.lowbit(i)

        return ret

    def set(self, i, val):
        while i < len(self.N):
            self.N[i] += val
            i += self.lowbit(i)
\end{python}

\section{Segment Tree}\label{section:segmentTree}
\subsection{Introduction}
Segment Tree is specially built for \textit{range queries}.

The structure of Segment Tree is a binary tree which each node has two attributes start and end denote an segment/interval.

Notice that by practice, the interval is normally $[start, end)$ but sometimes it can be $[start, end]$, which depends on the question definition.

Structure:
\begin{lstlisting}[columns=flexible]
# a Count Segment Tree
                     [0, 4, count=3]
                     /             \
          [0,2,count=1]             [2,4,count=2]
          /         \               /            \
   [0,1,count=1] [1,2,count=0] [2,3,count=1], [3,4,count=1]
\end{lstlisting}
Variants:
\begin{enumerate}
\item Sum Segment Tree.
\item Min/Max Segment Tree.
\item Count Segment Tree.
\end{enumerate}

For a Maximum Segment Tree, which each node has an extra value max to store the maximum value in this node's interval.

\subsection{Operations}
Segment Tree does a decent job for range queries.
\\
Components in Segment Tree operations:
\begin{enumerate}
\item Build
\item Query
\item Modify
\item Search
\end{enumerate}
Notice:
\begin{enumerate}
\item Only build need to change the start and end recursively.
\item Pre-check is preferred in recursive calls.
\end{enumerate}
Code: Notice the code has abstracted out segment tree functions of sum, min/max or count, by abstracting the subtree combine function to \pyinline{lambda}.
\begin{python}
DEFAULT = 0
f = lambda x, y: x+y

class Node(object):
    def __init__(self, start, end, val):
        self.lo, self.hi, self.val = lo, hi, val
        self.left, self.right = None, None

class SegmentTree(object):
    def __init__(self, A):
        self.A = A
        self.root = self.build_tree(0, len(self.A))

    def build_tree(self, lo, hi):
        """
        Bottom-up build
        segment: [lo, hi)
        Either check lo==hi-1 or have root.right
        only if have root.left
        """
        if lo >= hi:   return None
        if lo == hi-1: return Node(lo, hi, self.A[lo])

        left  = self.build_tree(lo, (lo+hi)/2)
        right = self.build_tree((lo+hi)/2, hi)

        val = DEFAULT
        if left:  val = f(val, left.val)
        if right: val = f(val, right.val)
        root = Node(lo, hi, val)
        root.left  = left
        root.right = right

        return root

    def query(self, root, lo, hi):
        """
        Post-checking
        :type root: Node
        """
        if not root:
            return DEFAULT

        if lo <= root.lo and hi >= root.hi:
            return root.val

        if lo >= root.hi or  hi <= root.hi:
            return DEFAULT

        l = self.query(root.left,  lo, hi)
        r = self.query(root.right, lo, hi)
        return f(l, r)

    def modify(self, root, idx, val):
        """
        :type root: Node
        """
        if not root or idx < root.lo or idx >= root.hi:
            return

        if idx == root.lo and idx == root.hi-1:
            root.val = val
            self.A[idx] = val
            return

        self.modify(root.left,  idx, val)
        self.modify(root.right, idx, val)

        val = DEFAULT
        if root.left:  val = f(val, root.left.val)
        if root.right: val = f(val, root.right.val)

        root.val = val
\end{python}
The above code abstracts out segment tree function using \pyinline{lambda}. For a concrete example, see Count Segment Tree \ref{inversionReconstruct}.

\newpage
\section{Trie}
\subsection{Basic}
Trie is aka radix tree, prefix tree.
\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[scale=.30]{trie.jpg}}
\caption{Trie}
\label{fig:trie}
\end{figure}
\runinhead{Notice:}
\begin{enumerate}
\item Children are stored in HashMap rather than ArrayList.
\item \pyinline{self.word} to stores the word and indicates whether a word ends at the current
node.
\end{enumerate}
Codes:
\begin{python}
class TrieNode(object):
    def __init__(self, char):
        self.char = char
        self.word = None
        self.children = {}  # map from char to TrieNode

class Trie(object):
    def __init__(self):
        self.root = TrieNode(None)

    def add(self, word):
        word = word.lower()
        cur = self.root
        for c in word:
            if c not in cur.children:
                cur.children[c] = TrieNode(c)
            cur = cur.children[c]

        cur.word = word
\end{python}

\subsection{Advanced}
Implicit storage of word in TrieNode:
\begin{enumerate}
\item Implicitly stores the current word.
\item Implicitly stores the current char.
\item When insert new word, do not override the existing TrieNode. A flag to indicate
whether there is a word ending here.
\end{enumerate}
\newpage
Code:
\begin{python}
class TrieNode:
    def __init__(self):
        """Implicit storage"""
        self.ended = False
        self.children = {}

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        cur = self.root
        for w in word:
            if w not in cur.children:   # not override
                cur.children[w] = TrieNode()

            cur = cur.children[w]

        cur.ended = True

    def search(self, word):
        cur = self.root
        for w in word:
            if w in cur.children:
                cur = cur.children[w]
            else:
                return False

        if not cur.ended:  # not ended here
            return False

        return True

    def startsWith(self, prefix):
        cur = self.root
        for w in prefix:
            if w in cur.children:
                cur = cur.children[w]
            else:
                return False

        return True
\end{python}
\subsection{Extensions}
\runinhead{Search for multiple words} Search for combination of words e.g. ``unitedstates''. Add threads between tails and the root; thus enable the search for multi-word combinations. Figure - \ref{fig:trie2}
\begin{figure}[!hbt]
\centering
\subfloat{\includegraphics[scale=.55]{trie2.png}}
\caption{Trie with threads from ending point to root}
\label{fig:trie2}
\end{figure}
\subsection{Applications}
\begin{enumerate}
\item Word search in matrix.
\item Word look up in dictionary.
\end{enumerate}


text:
from unittest import TestCase
from wsgiref.util import setup_testing_defaults

from mock import Mock, patch, call

from . import FakeIdentityProvider, FakeBackend
from cleaver import Cleaver, SplitMiddleware
from cleaver.compat import urlencode, PY3

class TestMiddleware(TestCase):

    def setUp(self):
        self._resp = {}

    @property
    def app(self):
        def a(environ, start_response):
            response_headers = [('Content-type', 'text/plain')]
            start_response('200 OK', response_headers)
            return ['Hello world!\n']
        return a

    def _make_request(self, environ=None, postdata=None, **kw):
        environ = environ or {}
        setup_testing_defaults(environ)

        if postdata is not None:
            environ['REQUEST_METHOD'] = 'POST'
            if PY3:
                postdata = bytes(postdata, 'UTF-8')  # pragma: nocover
            environ['CONTENT_LENGTH'] = str(len(postdata))
            environ['wsgi.input'].write(postdata)
            environ['wsgi.input'].seek(0)

        def start_response(status, response_headers, exc_info=None):
            self._resp['status'] = status

        SplitMiddleware(self.app, lambda environ: 'ryan', FakeBackend(), **kw)(
            environ,
            start_response
        )
        return environ

    def test_invalid_identity(self):
        self.assertRaises(
            RuntimeError,
            SplitMiddleware,
            self.app,
            None,
            FakeIdentityProvider()
        )

    def test_invalid_backend(self):
        self.assertRaises(
            RuntimeError,
            SplitMiddleware,
            self.app,
            FakeIdentityProvider(),
            None
        )

    def test_cleaver_in_environ(self):
        environ = self._make_request()
        assert 'cleaver' in environ
        assert isinstance(environ['cleaver'], Cleaver)
        assert callable(environ['cleaver'])

    def test_custom_environ_key(self):
        environ = self._make_request(environ_key='xyz')
        assert 'cleaver' not in environ
        assert 'xyz' in environ
        assert isinstance(environ['xyz'], Cleaver)
        assert callable(environ['xyz'])

    def test_cleaver_override_disabled(self):
        environ = self._make_request({
            'QUERY_STRING': urlencode({
                'cleaver:show_promo': 'False'
            })
        })

        assert environ['QUERY_STRING'] == urlencode({
            'cleaver:show_promo': 'False'
        })
        assert 'cleaver.override' not in environ

    def test_cleaver_override_variable_consumption(self):
        environ = self._make_request({
            'QUERY_STRING': urlencode({
                'cleaver:show_promo': 'False'
            })
        }, allow_override=True)

        assert environ['QUERY_STRING'] == ''
        assert environ['cleaver.override'] == {
            'show_promo': 'False'
        }

    def test_cleaver_override_variable_consumption_with_colons(self):
        environ = self._make_request({
            'QUERY_STRING': urlencode({
                'cleaver:a:b': 'Yes'
            })
        }, allow_override=True)

        assert environ['QUERY_STRING'] == ''
        assert environ['cleaver.override'] == {
            'a:b': 'Yes'
        }

    def test_cleaver_override_with_multiple_variable_consumption(self):
        environ = self._make_request({
            'QUERY_STRING': urlencode({
                'cleaver:show_promo': 'False',
                'cleaver:Button Size': 'large'
            })
        }, allow_override=True)

        assert environ['QUERY_STRING'] == ''
        assert environ['cleaver.override'] == {
            'show_promo': 'False',
            'Button Size': 'large'
        }

    def test_cleaver_override_with_mixed_query_args(self):
        environ = self._make_request({
            'QUERY_STRING': urlencode({
                'cleaver:show_promo': 'False',
                'article': 25,
                'cleaver:Button Size': 'large'
            })
        }, allow_override=True)

        assert environ['QUERY_STRING'] == 'article=25'
        assert environ['cleaver.override'] == {
            'show_promo': 'False',
            'Button Size': 'large'
        }

    @patch.object(FakeBackend, 'mark_human')
    @patch.object(FakeBackend, 'all_experiments', lambda *args: [])
    def test_human_callback(self, mark_human):
        self._make_request({
            'PATH_INFO': '/__cleaver_human_verification__'
        }, postdata='x=1&y=2&z=3', count_humans_only=True)
        assert self._resp['status'] == '204 No Content'

        mark_human.assert_called_with('ryan')

    @patch.object(FakeBackend, 'mark_human')
    @patch.object(FakeBackend, 'mark_participant')
    @patch.object(FakeBackend, 'get_variant')
    @patch.object(FakeBackend, 'all_experiments')
    def test_callback_with_new_participants(self, all_experiments,
                                            get_variant, mark_participant,
                                            mark_human):

        first = Mock()
        first.name = 'show_promo'
        second = Mock()
        second.name = 'color'
        all_experiments.return_value = [
            first, second
        ]

        get_variant.side_effect = ['True', 'blue']

        self._make_request({
            'PATH_INFO': '/__cleaver_human_verification__'
        }, postdata='x=1&y=2&z=3', count_humans_only=True)
        assert self._resp['status'] == '204 No Content'

        mark_human.assert_called_with('ryan')
        get_variant.assert_has_calls([
            call('ryan', 'show_promo'),
            call('ryan', 'color'),
        ])
        mark_participant.assert_has_calls([
            call('show_promo', 'True'),
            call('color', 'blue'),
        ])

    def test_missing_input(self):
        self._make_request({
            'PATH_INFO': '/__cleaver_human_verification__'
        }, postdata='', count_humans_only=True)
        assert self._resp['status'] == '401 Unauthorized'

    def test_deformed_input(self):
        self._make_request({
            'PATH_INFO': '/__cleaver_human_verification__'
        }, postdata='rtoanrt98arst0larst', count_humans_only=True)
        assert self._resp['status'] == '401 Unauthorized'

    def test_missing_arguments(self):
        self._make_request({
            'PATH_INFO': '/__cleaver_human_verification__'
        }, postdata='x=5', count_humans_only=True)
        assert self._resp['status'] == '401 Unauthorized'

    def test_non_integer_arguments(self):
        self._make_request({
            'PATH_INFO': '/__cleaver_human_verification__'
        }, postdata='x=5&y=10&z=dog', count_humans_only=True)
        assert self._resp['status'] == '401 Unauthorized'

    def test_bad_math(self):
        self._make_request({
            'PATH_INFO': '/__cleaver_human_verification__'
        }, postdata='x=5&y=10&z=250', count_humans_only=True)
        assert self._resp['status'] == '401 Unauthorized'

redpajama_set_name: RedPajamaGithub


text:
using System;
//•	Write a method that returns the last digit of given integer as an English word.
class EnglishDigit
{
    static void Main()
    {
        Console.Write("Please enter an integer: ");
        int number = int.Parse(Console.ReadLine());
        string result = LastDigitAsWord(number);
        Console.WriteLine(result);

    }

    private static string LastDigitAsWord(int number)
    {
        int index = number % 10;
        string[] arrayWithnumbers = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
        string result = arrayWithnumbers[index];
        return result;

    }
}


text:
/**
 * Created by GuoJunjun on 25.12.14. JunjunGuo.com
 */

/**
 * check if client from China
 */
//function clientlocationplugin() {
//    return jQuery.getScript('http://www.geoplugin.net/javascript.gp', function () {
//        var country = geoplugin_countryName();
//        var zone = geoplugin_region();
//        var district = geoplugin_city();
//        console.log("Your location is: " + country + ", " + zone + ", " + district);
//    })();
//}
console.log("Your location: " + geoplugin_countryName());
/**
 *  * shuffle the list and return a photo addressed list
 * @param list
 * @returns {Array}
 */
function shuffleList(list) { // shuffle nrlist and return a list with objects ready for slides
    var copy = [], n = list.length, index;
    var bgimgaddress;
    if (geoplugin_countryName() == "China") {
        bgimgaddress = './2015/images/bg/';
    } else {
        bgimgaddress = 'http://static.panoramio.com/photos/large/';
    }
    while (n) {
        index = Math.floor(Math.random() * (n--));
//        var overlay = 'url(".2015/css/images/overlay-black.svg"),'
        copy.push(bgimgaddress + list[index] + '.jpg');
        list.splice(index, 1);
    }
    return copy;
}

/**
 * add the image to #header as background image
 * @param theImg
 */
function addImage(theImg) {
    document.getElementById("header").style.backgroundImage = "url('" + theImg + "')";
}
var listh = [			//  Images id numbers for header
    77233663,
    105836333,
    109199045,
    109172199,
    92464442,
    92464435,
    107909681,
    51569735,
    108930464,
    109049207,
    109100961,
    106419102,
    51569745,
    78491829,
    49428516,
    43143230,
    106397984
];
function slideShow() {
    var counter = 0; // to keep track of current slide
    var slides = shuffleList(listh); // a collection of all of the slides

    var showImage = function () {
// calculates the actual index of the element to show
        var theImage = Math.abs(counter % slides.length);
        addImage(slides[theImage]);
    };

// add click events to prev & next buttons
    $('.nextslide').on('click', function () {
        document.getElementById('header').scrollIntoView()
        counter++;
        showImage();
    });
    $('.prevslide').on('click', function () {
        document.getElementById('header').scrollIntoView()
        counter--;
        showImage();
    });
    // logo click
    $('#logo').on('click', function () {
        document.getElementById('header').scrollIntoView()
        counter = Math.floor(Math.random() * slides.length);
        showImage();
    });

    showImage();
}

//run the script:

//run slide show
slideShow();

/**
 * Fly down
 */
$(".b0").animate({ "top": "+=350px", opacity: 1}, 1500);

// fly up
var list = [".b1",
            ".b2",
            ".b3",
            ".b4"];

for (i = 0; i < list.length; i++) {
    $(list[i]).animate({ "top": "-=450px", opacity: 1}, 2000 + i * 500, function () {
//            $(list[i]).animate({opacity: 1});
    });
}

$(".prevslide").animate({ "left": "-=500px", opacity: 1}, 2000);

$(".nextslide").animate({ "right": "-=500px", opacity: 1}, 2000);

//
var listf = [			//  Images id numbers for footer
    106397977,
    101153731,
    77835780,
    100920022,
    42462727,
    55717739,
    77835786,
    100920020
];
function changeBCP() {

    var bcgslides = shuffleList(listf); // a collection of all of the bcgslides

    var changepic = function () {

        var theimg = bcgslides[Math.floor(Math.random() * bcgslides.length)];

        document.getElementById("footer").style.backgroundImage =
            "url('./2015/css/images/overlay-black.svg'), url('" + theimg + "')";
    };

// add click events to prev & next buttons
    $('#changebcp').on('click', function () {
        document.getElementById('footer').scrollIntoView()
        changepic();
    });

    changepic();
}

changeBCP();

//Magnific Popup ------------->
// Inline popups
$('#inline-popups').magnificPopup({
                                      delegate: 'a',
                                      removalDelay: 500, //delay removal by X to allow out-animation
                                      callbacks: {
                                          beforeOpen: function () {
                                              this.st.mainClass = this.st.el.attr('data-effect');
                                          }
                                      },
                                      midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
                                  });


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2015 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<resources>
    <!-- The color of the ripple effect on clickable elements. -->
    <attr name="rippleColor" format="color"/>
    <!-- The top or bottom inset of a drawable. -->
    <attr name="verticalInset" format="reference|dimension"/>

    <declare-styleable name="ButtonCompat">
        <!-- The color of the button background. -->
        <attr name="buttonColor" format="color"/>
        <!-- The color of the button text. This attribute will override the text color set in
             android:textAppearance. -->
        <attr name="buttonTextColor" format="reference"/>
        <attr name="rippleColor"/>
        <attr name="borderColor" format="color"/>
        <attr name="borderWidth" format="reference|dimension"/>
        <!-- Whether the button is elevated. -->
        <attr name="buttonRaised" format="boolean"/>
        <!-- The vertical inset of the button background drawable. -->
        <attr name="verticalInset"/>

        <!--  The ripple corner radius of ripple effect. If not specified,
          @dimen/button_compat_corner_radius is default. -->
        <attr name="rippleCornerRadiusTopStart" format="reference|dimension" />
        <attr name="rippleCornerRadiusTopEnd" format="reference|dimension" />
        <attr name="rippleCornerRadiusBottomStart" format="reference|dimension" />
        <attr name="rippleCornerRadiusBottomEnd" format="reference|dimension" />
    </declare-styleable>

    <!-- The attributes prefixed with 'global' are used to control the button, link and URL colors
         throughout the app and are defined in the activity theme. This enables us to apply
         dynamic colors to the mentioned UI elements. These attributes may not be set in some
         contexts, e.g. WebView, so the code dealing with them should handle their absence. -->
    <attr name="globalFilledButtonBgColor" format="color"/>
    <attr name="globalFilledButtonTextColor" format="reference"/>
    <attr name="globalTextButtonTextColor" format="reference"/>
    <attr name="globalTextButtonRippleColor" format="color"/>
    <attr name="globalOutlinedButtonBorderColor" format="color"/>
    <attr name="globalLinkTextColor" format="color"/>
    <attr name="globalClickableSpanColor" format="color"/>

    <declare-styleable name="TextViewWithLeading">
        <attr name="leading" format="reference|dimension"/>
    </declare-styleable>

    <declare-styleable name="AsyncViewStub">
        <!-- Supply an identifier for the layout resource to inflate when the AsyncViewStub
             becomes visible or when forced to do so. The layout resource must be a
             valid reference to a layout. -->
        <attr name="layout" format="reference" />
    </declare-styleable>
</resources>


text:
A simple, framework agnostic, PHP implementation of a wrapper for the [Instagram API](http://instagram.com/developer/).

##Installation

Install the package via composer:

```json
{
	"require": {
		"spanky/instagram": "dev-master"
	}
}
```
and require the Composer autoloader in your PHP files:

```php
	require 'vendor/autoload.php';
```

###Laravel Installation

If you want to use this package with Laravel 4, you can make use of the included service provider and facades to take care of the bootstrapping code.

First, add the service provider to the ```providers``` array in ```app/config/app.php```:

```php
'providers' => array(
	...
	'Spanky\Instagram\Laravel\InstagramServiceProvider',
);
```

Next, publish the configuration file from the package to your project via the command line:

```
php artisan config:publish spanky/instagram
```

You should now see the config file at ```app/config/packages/spanky/instagram/config.php```, where you can enter in your details.

Once you've entered in your app details in the config file, you can now access the ```Spanky\Instagram\Factory``` class with the ```Instagram``` alias.

##Usage

###Authentication

The package follows the server side flow for authentication, [described here](http://instagram.com/developer/authentication/). To setup authentication in your app, follow these steps:

- [Register a Instagram client](http://instagram.com/developer/clients/register), making note of the credentials that are generated.

- Next, create an instance of ```Spanky\Instagram\Authorizor``` by calling the ```authorizor()``` method (passing the configuration details in, if not using Laravel) on an instance of ```Spanky\Instagram\Factory```, and call the ```getAuthorizeUrl()``` to return the Instagram
authorization URL. Redirect your users to this URL via PHP, or other means.

```php
<?php

use Spanky\Instagram\Factory as Instagram;

$config = array(

	'client_id' 	=> 'YOUR_CLIENT_ID',
	'client_secret'	=> 'YOUR_CLIENT_SECRET',
	'redirect_uri'	=> 'YOUR_REDIRECT_URL'
);

$authorize_url = Instagram::authorizor($config)->getAuthorizeUrl();

header("Location:{$authorize_url}");

```

- Upon authorizing, the user will be redirected back to the URL you specified when you registered the client, along with a ```code``` parameter in the query string. You need to pass this code to the ```getAccessToken()``` method on the ```Spanky\Instagram\Authorizor``` class to retrieve the access token.

```php
<?php

use Spanky\Instagram\Factory as Instagram;

$config = array(

	'client_id' 	=> 'YOUR_CLIENT_ID',
	'client_secret'	=> 'YOUR_CLIENT_SECRET',
	'redirect_uri'	=> 'YOUR_REDIRECT_URL'
);

$token = Instagram::authorizor($config)->getAccessToken($_GET['code']);
```

-  Once you have this access token, you can store it (in the session, in a database, etc) and retrieve it for authenticating API requests.

```php
$_SESSION['instagram_access_token'] = $token;

header("Location:index.php");
// Redirect somewhere
```

###API Usage

Once you are in posession of an access token, you must set this on the instance of
the ```Spanky\Instagram\Instagram``` class, before you can make any requests.

```php
<?php

use Spanky\Instagram\Factory as Instagram;

$instagram = Instagram::api();
$instagram->setAccessToken($_SESSION['instagram_access_token']);

```

###Getting the authorized user

```php
$user = $instagram->getAuthorizedUser();
// will return an instance of Spanky\Instagram\Entities\AuthorizedUser

echo $user->username; // the username of the authorized user
echo $user->profile_picture; // their profile picture
echo $user->mediaCount(); // the number of photos/videos they've uploaded
```

###Getting a user by their id

```php
$user = $instagram->getUser(1010);
// will return an instance of Spanky\Instagram\Entities\User
```

### Getting the users who follow a user

```php
$followers = $user->followers();
// returns an instance of Spanky\Instagram\Collections\UserCollection

foreach($followers as $follower)
{
	// $follower is an instance of Spanky\Instagram\Entities\User
	echo $follower->username;
}

if ($followers->hasMoreItems())
{
	// If the user has more followers (results are paginated)
	$next_max_id = $followers->nextPageMaxId();
	// Get the next max id for the next request

	$moreFollowers = $user->followers(array('max_id' => $next_max_id));
	// Get the next round by passing in the max id
}
```
To be continued...


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Archive for posts dated 'April 2009' | Lee Kelleher - Umbraco Consultant</title>
	<meta name="description" content="The personal website of Lee Kelleher; Umbraco Consultant">
	<meta name="keywords" content="leekelleher,kelleher,umbraco,asp.net,c#,csharp,xslt,mvc,mvp">
	<meta name="generator" content="Wyam">
	<meta name="twitter:card" content="summary">
	<meta name="twitter:site" content="@leekelleher">
	<meta name="twitter:url" property="og:url" content="https://leekelleher.com/2009/04/">
	<meta name="twitter:title" property="og:title" content="Archive for posts dated 'April 2009'">
	<meta name="twitter:description" property="og:description" content="The personal website of Lee Kelleher; Umbraco Consultant">
	<meta name="twitter:image" property="og:image" content="https://leekelleher.com/assets/img/nxnw_300x300.jpg">
	<link rel="alternate" href="https://leekelleher.com/feed/" type="application/rss+xml">
	<link rel="canonical" href="https://leekelleher.com/2009/04/">
	<link rel="pingback" href="https://webmention.io/leekelleher.com/xmlrpc">
	<link rel="webmention" href="https://webmention.io/leekelleher.com/webmention">
	<link rel="stylesheet" href="/assets/css/style.css">

Lee Kelleher

About

Now

Contact

Archive for posts dated 'April 2009'

April 2009

Umbraco Package – User Control File Tree

				Posted on <time datetime="2009-04-15T00:46+01:00">15/04/2009</time>.
				Estimated read time:  2 minutes (309 words)

A few months ago, Tim Geyssens (aka Umbraco rockstar) released a package that gave you access to the *.config files in the /config/ folder. This has been a lifesaver in those few times where I have only had web-access to an Umbraco install and needed to tweak some config settings. Recently I found myself in the same situation, but this time I needed to quickly update a few text changes to an ASCX user-control. Due…

Tags: ASCX, ASP.NET, Developer, Umbraco, User Controls

Integrating ELMAH with Umbraco

				Posted on <time datetime="2009-04-23T22:13+01:00">23/04/2009</time>.
				Estimated read time:  5 minutes (667 words)

Update: For the latest details on how to integrate ELMAH with Umbraco, please read the article over on the Our Umbraco wiki. I have a few Umbraco projects that have a lot of custom .NET code, mostly in they are in the form of user-controls and XSLT extensions.  As far as I'm aware Umbraco doesn't have an extendable mechanism for exception handling and sending out notification emails, (there is the umbraco.BusinessLogic.Log, which writes to the…

Tags: ASP.NET, ELMAH, Error Handling, Exception, Umbraco

Year archive

				2020

							January

				2019

							January

							February

							April

							August

				2018

							January

							August

							November

							December

				2016

							March

							May

							June

							July

							August

							September

							October

				2014

							March

							May

							November

				2013

							September

							October

							November

							December

				2012

							February

				2011

							January

							June

							July

							September

							October

				2010

							January

							April

							May

							August

				2009

							January

							February

							April

							June

							July

							September

							October

							November

				2008

							January

							February

							March

							April

							May

							June

							July

							August

							November

							December

				2007

							January

							February

							March

							April

							May

							June

							November

							December

				2006

							March

							April

							June

							October

							November

							December

Tag archive

View a weighted tag cloud and a listing of all tags.

For any feedback, comments or questions, feel free to ask me via my contact page, on Twitter, or on GitHub.

Be notified of new posts, subscribe to my RSS feed.

All content by Lee Kelleher (© 2006-2021) and licensed under Creative Commons. All code snippets are licensed under the MIT license.

This website is statically generated using Wyam. All code and content for this blog is available as open source on GitHub.


text:
<?php
// connect to database \\
include('inlcudes/connect.php');
// secure input \\
include('inlcudes/secureInput.php');
// password encryption \\
include('inlcudes/salt.php');
// validate functions \\
include('inlcudes/validate.php');
// database querys \\
include('inlcudes/query.php');

session_start();
// form validation
if (!empty($_POST['loginSubmit'])) {

	// validation is false
	$issetLoginEmail = false;
	$issetLoginPassword = false;

	// control email input field if its not empty
	if(!empty($_POST['email'])){

		// secure input emial
		$loginEmail = secureInput($_POST['email']);

		// start session email
		$_SESSION['email'] = $loginEmail;

		// control if its a valid email
		if(validateEmail($loginEmail) == true){

			// refresh sesion email
			$_SESSION['email'] = $loginEmail;

			// control email if it exist in database
			if(controlDatabase('users', 'email', $loginEmail) == true){

				// email validation is true
				$issetLoginEmail = true;

				// refresh session email
				$_SESSION['email'] = $loginEmail;

				// login email error null
				$loginErrorEmail = NULL;
			}
			else{
				$loginErrorEmail = "The email you enterd doesn't exist in database.";
			}
		}
		else{
			$loginErrorEmail = "It's not a correct email address";
		}
	}
	else{
		$loginErrorEmail = "This field is required.";
	}

	// control password input field if its not empty
	if(!empty($_POST['password'])){

		// secure input password
		$loginPassword = secureInput($_POST['password']);

		// password validation is true
		$issetLoginPassword = true;

		// login password error null
		$loginErrorPassword = NULL;
	}
	else{
		$loginErrorPassword = "This field is required.";
	}

	// control if validte is complete
	if($issetLoginPassword == true && $issetLoginEmail == true){
		// encrypt password
		$loginPasswordEncrypt = passwordBLowfishCrypt($loginPassword);
		// get password from database
		$dbPassword = getPassword('users', 'email', $loginEmail);

		// control if it's te correct password
		if(confirmPassword($loginPasswordEncrypt, $dbPassword) == true){

			// get user data from database
			$userData = getUserData('users', $loginEmail, $loginPasswordEncrypt);

			// set error null
			$loginErrorPassword = NULL;

			// session with data from user
			$_SESSION['userId'] = $userData['userId'];
			$_SESSION['firstName'] = $userData['firstName'];
			$_SESSION['surName'] = $userData['surName'];
			$_SESSION['email'] = $userData['email'];

			// change page to welcome.php
			header('Location: index.php');

			// exit page
			exit;
		}
		else{
			$loginErrorPassword = "The password you entered is incorrect.";
		}
	}
};
?>

<!doctype html>

<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css"/>
<title>Login</title>

Login fanpage studio ghibli

    <form method="post">
      Email:
      <input type="email" name="email" value="<?php echo $_SESSION['email']; ?>" />
      <?php echo $loginErrorEmail ?>
      Password:
      <input type="password" name="password"/>
      <?php echo $loginErrorPassword ?>
      <input class="submitButton" type="submit" name="loginSubmit" value="Login"/>
    </form>
    Register


text:
import os
from _exception import http_404, http_302
from _utils import fetch_and_parse_index, ensure_python_dir

class FileHandler(object):
    def __init__(self, pypi_base_url, http_get_fn, parse_index_fn):
        self.pypi_base_url = pypi_base_url
        self.http_get_fn = http_get_fn
        self.parse_index_fn = parse_index_fn

    def _is_checksum_file(self, filename):
        return filename.lower().endswith(('.md5', '.sha1'))

    def _handle_checksum(self, checksum_filename, index_rows, response):
        filename_base, ext = os.path.splitext(checksum_filename)
        ext_no_dot = ext[1:].lower()
        _ensure_file_in_index(filename=filename_base, index_rows=index_rows)
        checksums = index_rows[filename_base].checksums

        return _get_checksum(
            checksums=checksums,
            checksum_ext=ext_no_dot,
            response_headers=response.headers)

    def _redirect_to_download_url(self, filename, index_rows):
        _ensure_file_in_index(filename=filename, index_rows=index_rows)
        download_url = index_rows[filename].download_url
        raise http_302(download_url)

    @ensure_python_dir
    def handle(self, path, request, response):
        py, package_name, filename = path

        index_url = '{}/{}/'.format(self.pypi_base_url, package_name)

        index_rows = fetch_and_parse_index(
            http_get_fn=self.http_get_fn,
            parse_index_fn=self.parse_index_fn,
            pypi_base_url=self.pypi_base_url,
            index_url=index_url,
            package_path=package_name)

        if self._is_checksum_file(filename=filename):
            return self._handle_checksum(
                checksum_filename=filename,
                index_rows=index_rows,
                response=response)

        self._redirect_to_download_url(
            filename=filename,
            index_rows=index_rows)

def _ensure_file_in_index(filename, index_rows):
    if filename not in index_rows:
        raise http_404('File "{}" does not exist'.format(filename))

def _get_checksum(checksums, checksum_ext, response_headers):
    checksum = getattr(checksums, checksum_ext)

    if not checksum:
        raise http_404('Checksum not available')

    response_headers['Content-Type'] = 'application/x-checksum'

    return checksum


text:
def appendsums(sum_tree):
	new_tree = sum_tree[:]
	for num in range(25):
		summ = new_tree[-1] + new_tree[-2] + new_tree[-3]
		new_tree.append(summ)
	return new_tree
lists = [0,1,2]
a = lists[1]
lists[1] = 4
print a, lists

###Question 10
class BankAccount:
    """ Class definition modeling the behavior of a simple bank account """

    def __init__(self, initial_balance):
        """Creates an account with the given balance."""
        self.initial_balance = initial_balance
        self.fees = 0

    def deposit(self, amount):
        """Deposits the amount into the account."""
        self.initial_balance += amount

    def withdraw(self, amount):
        """
        Withdraws the amount from the account.  Each withdrawal resulting in a
        negative balance also deducts a penalty fee of 5 dollars from the balance.
        """
        self.initial_balance = self.initial_balance - amount
        if self.initial_balance < 0:
        	self.fees += 5
        	self.initial_balance -=5

    def get_balance(self):
        """Returns the current balance in the account."""
        return self.initial_balance

    def get_fees(self):
        """Returns the total fees ever deducted from the account."""
        return self.fees

my_account = BankAccount(10)
my_account.withdraw(5)
my_account.deposit(10)
my_account.withdraw(5)
my_account.withdraw(15)
my_account.deposit(20)
my_account.withdraw(5)
my_account.deposit(10)
my_account.deposit(20)
my_account.withdraw(15)
my_account.deposit(30)
my_account.withdraw(10)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(50)
my_account.deposit(30)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(5)
my_account.deposit(20)
my_account.withdraw(15)
my_account.deposit(10)
my_account.deposit(30)
my_account.withdraw(25)
my_account.withdraw(5)
my_account.deposit(10)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(10)
my_account.withdraw(15)
my_account.deposit(10)
my_account.deposit(30)
my_account.withdraw(25)
my_account.withdraw(10)
my_account.deposit(20)
my_account.deposit(10)
my_account.withdraw(5)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(5)
my_account.withdraw(15)
my_account.deposit(10)
my_account.withdraw(5)
print my_account.get_balance(), my_account.get_fees()


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Rodriguésia 18:30. 1945

#### Original name
null

### Remarks
null


text:
layout: post
date: 2015-12-27
title: "Modern Trousseau Tanner Sleeveless Chapel Train Mermaid/Trumpet"
category: Modern Trousseau
tags: [Modern Trousseau,Modern Trousseau ,Mermaid/Trumpet,Sweetheart,Chapel Train,Sleeveless]
---
### Modern Trousseau Tanner
Just **$449.99**
###   Sleeveless Chapel Train Mermaid/Trumpet

BRANDS	Modern Trousseau

Silhouette	Mermaid/Trumpet

Neckline	Sweetheart

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/modern-trousseau/46615-modern-trousseau-tanner.html](https://www.readybrides.com/en/modern-trousseau/46615-modern-trousseau-tanner.html)


text:
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  self.fixture_path = File.expand_path('../fixtures', __FILE__)
  self.fixtures :all
end

class ActionDispatch::IntegrationTest
  self.fixture_path = File.expand_path('../fixtures', __FILE__)
end


text:
class HttpRouter
  class Request
    attr_accessor :path, :params, :rack_request, :extra_env, :continue, :passed_with, :called
    attr_reader :acceptable_methods
    alias_method :rack, :rack_request
    alias_method :called?, :called

    def initialize(path, rack_request)
      @rack_request = rack_request
      @path = URI::DEFAULT_PARSER.unescape(path).split(/\//)
      @path.shift if @path.first == ''
      @path.push('') if path[-1] == ?/
      @extra_env = {}
      @params = []
      @acceptable_methods = Set.new
    end

    def joined_path
      @path * '/'
    end

    def to_s
      "request path, #{path.inspect}"
    end

    def path_finished?
      @path.size == 0 or @path.size == 1 && @path.first == ''
    end
  end
end


text:
package ru.job4j.bombergame;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Class is monster in the game.
 *
 * @since 16/10/2017
 * @version 1
 */
public class Monster extends Character {

    public Monster(Board board, int y, int x, String name) {
        super(board, y, x, name);
    }

    @Override
    public void run() {
        try {
            // захватываем первую позицию
            position.lock();

            while(!Thread.currentThread().isInterrupted()) {

                // выбираем случайное направление
                move(Direction.values()[(int)(Math.random()*4)]);

                // скорость чудовищ = один шаг в 0,5 сек.
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            logger.info("Thread " + name + " was interrupted! ");
        }
    }

    @Override
    protected boolean move(int y, int x) throws InterruptedException {
        boolean result = false;
        ReentrantLock oldPosition = position;
        position = board.getPosition(y, x);

        if(position != null) {
            result = position.tryLock();

            // если не удалось получить lock, то...
            if (!result) {

                //...проверяем не была ли занята позиция героем, если была - игра оканчивается:
                if (board.getHeroPosition() == position) {
                    System.out.println(name + " trapped hero!");
                    board.endGame();
                    return result;
                }

                // ...возвращаемся на исходную позицию и спим 5 сек.
                position = oldPosition;
                Thread.sleep(5000);
            } else {
                // если удалось получить lock, то освобождаем прежнюю позицию
                oldPosition.unlock();
            }
        } else {
            // если позиции не существует (== null), то возвращаемся на исходную позицию
            position = oldPosition;
        }

        return result;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Windows.Media;

namespace CsDebugScript.UI.ResultVisualizers
{
    /// <summary>
    /// Helper (base) class for visualizing custom resulting objects.
    /// Usually one would inherit <see cref="CustomObjectResultVisualizer"/> class
    /// and override <see cref="ResultVisualizer.ExpandedChildren"/> and <see cref="ResultVisualizer.GetValue"/>
    /// to implement custom object visualizers.
    /// </summary>
    internal class CustomObjectResultVisualizer : ObjectResultVisualizer
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomObjectResultVisualizer"/> class.
        /// </summary>
        /// <param name="result">Resulting object that should be visualized.</param>
        /// <param name="resultType">Type of the resulting object that should be visualized.</param>
        /// <param name="name">Name of the variable / property.</param>
        /// <param name="image">Image that represents icon of the variable / property</param>
        /// <param name="interactiveResultVisualizer">Interactive result visualizer that can be used for creating UI elements.</param>
        public CustomObjectResultVisualizer(object result, Type resultType, string name, ImageSource image, InteractiveResultVisualizer interactiveResultVisualizer)
            : base(result, resultType, name, image, interactiveResultVisualizer)
        {
        }

        /// <summary>
        /// Checks if this item has child elements and should be expandable.
        /// </summary>
        public override bool IsExpandable
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Gets the child elements in groups.
        /// Since inherited classes would override ExpandedChildren, we need to return them into [Public] group.
        /// </summary>
        public override IEnumerable<Tuple<string, IEnumerable<IResultVisualizer>>> Children
        {
            get
            {
                bool publicsReturned = false;

                foreach (Tuple<string, IEnumerable<IResultVisualizer>> children in base.Children)
                {
                    yield return children;
                    if (!publicsReturned && children.Item1 == "[Expanded]")
                    {
                        publicsReturned = true;
                        yield return Tuple.Create("[Public]", base.ExpandedChildren);
                    }
                }
            }
        }
    }
}


text:
<?php

use yii\helpers\Html;
//use yii\widgets\ActiveForm;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\user\UserGroup */
/* @var $form yii\widgets\ActiveForm */

$model->status = true;//给个默认值
?>

        <?php $form = ActiveForm::begin(); ?>

        <?= $form->field($model, 'name', ['inputOptions' => ['placeholder'=>$model->getAttributeLabel('name')]])->textInput(['maxlength' => true]) ?>

        <?= $form->field($model, 'description', ['inputOptions' => ['placeholder'=>$model->getAttributeLabel('description')]])->textarea(['rows' => 3]) ?>

        <?= $form->field($model, 'sort', ['inputOptions' => ['placeholder'=>$model->getAttributeLabel('sort')]])->input('number') ?>

        <?= $form->field($model, 'status')->checkbox(['value'=>true]) ?>

            <?= Html::submitButton($model->isNewRecord ? Yii::t('common', 'Create') : Yii::t('common', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

        <?php ActiveForm::end(); ?>


text:
/**
 * @license Use of this source code is governed by an MIT-style license that
 * can be found in the LICENSE file at https://github.com/cartant/rxjs-tslint-rules
 */
/*tslint:disable:no-use-before-declare*/

import * as Lint from "tslint";
import * as tsutils from "tsutils";
import * as ts from "typescript";
import { couldBeType, isReferenceType } from "../support/util";

export class Rule extends Lint.Rules.TypedRule {
  public static metadata: Lint.IRuleMetadata = {
    description: "Disallows unsafe first/take usage in effects and epics.",
    options: {
      properties: {
        observable: {
          oneOf: [
            { type: "string" },
            { type: "array", items: { type: "string" } },
          ],
        },
      },
      type: "object",
    },
    optionsDescription: Lint.Utils.dedent`
      An optional object with an optional \`observable\` property.
      The property can be specifed as a regular expression string or as an array of words and is used to identify the action observables from which effects and epics are composed.`,
    requiresTypeInfo: true,
    ruleName: "rxjs-no-unsafe-first",
    type: "functionality",
    typescriptOnly: true,
  };

  public static FAILURE_STRING =
    "Unsafe first usage in effects and epics is forbidden";

  public applyWithProgram(
    sourceFile: ts.SourceFile,
    program: ts.Program
  ): Lint.RuleFailure[] {
    return this.applyWithWalker(
      new Walker(sourceFile, this.getOptions(), program)
    );
  }
}

export class Walker extends Lint.ProgramAwareRuleWalker {
  public static METHODS_REGEXP = /(ofType|pipe)/;
  public static DEFAULT_OBSERVABLE = String.raw`action(s|\$)?`;

  private observableRegExp: RegExp;

  constructor(
    sourceFile: ts.SourceFile,
    rawOptions: Lint.IOptions,
    program: ts.Program
  ) {
    super(sourceFile, rawOptions, program);

    const [options] = this.getOptions();
    if (options && (options.allow || options.disallow)) {
      this.observableRegExp = new RegExp(
        options.observable || Walker.DEFAULT_OBSERVABLE,
        "i"
      );
    } else {
      this.observableRegExp = new RegExp(Walker.DEFAULT_OBSERVABLE, "i");
    }
  }

  protected visitCallExpression(node: ts.CallExpression): void {
    const { expression: propertyAccessExpression } = node;
    if (tsutils.isPropertyAccessExpression(propertyAccessExpression)) {
      const { expression: observableExpression } = propertyAccessExpression;
      let observableIdentifier:
        | ts.Identifier
        | ts.PrivateIdentifier
        | undefined = undefined;
      if (tsutils.isIdentifier(observableExpression)) {
        observableIdentifier = observableExpression;
      } else if (tsutils.isPropertyAccessExpression(observableExpression)) {
        observableIdentifier = observableExpression.name;
      }

      if (
        observableIdentifier &&
        this.observableRegExp.test(observableIdentifier.getText())
      ) {
        const propertyName = propertyAccessExpression.name.getText();
        const typeChecker = this.getTypeChecker();
        const type = typeChecker.getTypeAtLocation(observableExpression);

        if (
          isReferenceType(type) &&
          Walker.METHODS_REGEXP.test(propertyName) &&
          couldBeType(type.target, "Observable")
        ) {
          switch (propertyName) {
            case "ofType":
              this.walkPatchedTypes(node);
              break;
            case "pipe":
              this.walkPipedTypes(node);
              break;
            default:
              break;
          }
        }
      }
    }

    super.visitCallExpression(node);
  }

  private walkPatchedOperators(node: ts.Node): void {
    let name: ts.Identifier | ts.PrivateIdentifier | undefined = undefined;
    for (let parent = node.parent; parent; parent = parent.parent) {
      if (tsutils.isCallExpression(parent)) {
        if (name) {
          switch (name.getText()) {
            case "first":
              this.addFailureAtNode(name, Rule.FAILURE_STRING);
              break;
            case "take":
              this.addFailureAtNode(name, Rule.FAILURE_STRING);
              break;
            case "pipe":
              this.walkPipedOperators(parent);
              break;
            default:
              break;
          }
        }
      } else if (tsutils.isPropertyAccessExpression(parent)) {
        name = parent.name;
      } else {
        break;
      }
    }
  }

  private walkPatchedTypes(node: ts.CallExpression): void {
    this.walkPatchedOperators(node);
  }

  private walkPipedOperators(node: ts.CallExpression): void {
    node.arguments.forEach((arg) => {
      if (tsutils.isCallExpression(arg)) {
        const { expression } = arg;
        if (
          tsutils.isIdentifier(expression) &&
          (expression.getText() === "first" || expression.getText() === "take")
        ) {
          this.addFailureAtNode(expression, Rule.FAILURE_STRING);
        }
      }
    });
  }

  private walkPipedTypes(node: ts.CallExpression): void {
    node.arguments.forEach((arg) => {
      if (tsutils.isCallExpression(arg)) {
        const { expression } = arg;
        if (
          tsutils.isIdentifier(expression) &&
          expression.getText() === "ofType"
        ) {
          this.walkPipedOperators(node);
        }
      }
    });
  }
}


text:
module.exports = {
    ApiPrefix: "/@settings/api/v1"
}


text:
// Original - Christopher Lloyd <cjwl@objc.net>

#import <AppKit/Win32DeviceContextWindow.h>

@implementation Win32DeviceContextWindow

// defined in NSGraphicsStyle_uxtheme.m
HANDLE openThemeData(HWND window,LPCWSTR classList);
void closeThemeData(HANDLE theme);

-initWithWindowHandle:(HWND)handle {
   [super initWithDC:GetDC(handle)];
   if (handle)
   {
      _handle=handle;
      _theme[uxthBUTTON]   =openThemeData(handle, L"BUTTON");
      _theme[uxthCOMBOBOX] =openThemeData(handle, L"COMBOBOX");
      _theme[uxthEDIT]     =openThemeData(handle, L"EDIT");
      _theme[uxthHEADER]   =openThemeData(handle, L"HEADER");
      _theme[uxthMENU]     =openThemeData(handle, L"MENU");
      _theme[uxthPROGRESS] =openThemeData(handle, L"PROGRESS");
      _theme[uxthSCROLLBAR]=openThemeData(handle, L"SCROLLBAR");
      _theme[uxthSPIN]     =openThemeData(handle, L"SPIN");
      _theme[uxthTAB]      =openThemeData(handle, L"TAB");
      _theme[uxthTRACKBAR] =openThemeData(handle, L"TRACKBAR");
      _theme[uxthTREEVIEW] =openThemeData(handle, L"TREEVIEW");
   }
   return self;
}

-(void)dealloc {
   int i;
   for (i=0;i<uxthNumClasses;i++)
      if (_theme[i])
         closeThemeData(_theme[i]);
   ReleaseDC(_handle,_dc);
   [super dealloc];
}

-(HWND)windowHandle {
   return _handle;
}

-(HANDLE)theme:(int)uxthClassId {
   return _theme[uxthClassId];
}

-(Win32DeviceContextWindow *)windowDeviceContext {
   return self;
}

@end


text:
@implementation Utilities

+(NSString *)localePath:(NSString *)fileName
{
	NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
	NSString *localeProj = [language stringByAppendingPathExtension:@"lproj"];
	NSString *localePath = [self bundlePath:localeProj];
	return [localePath stringByAppendingPathComponent:fileName];
}

+(NSString *)bundlePath:(NSString *)fileName
{
	return [[[VAppInfo sharedInstance] bundlePath] stringByAppendingPathComponent:fileName];
}

+(NSString *)documentsPath:(NSString *)fileName
{
	return [[[VAppInfo sharedInstance] docmentsPath] stringByAppendingPathComponent:fileName];
}

+(NSString *)cachesPath:(NSString *)fileName
{
    return [[[VAppInfo sharedInstance] cachesPath] stringByAppendingPathComponent:fileName];
}

+(NSString *)cachesPathWithCString:(const char *)fileName
{
    NSString *nsfile = [[NSString alloc] initWithCString:fileName
                                                 encoding:NSUTF8StringEncoding];
    return [self cachesPath:nsfile];
}

+(NSString *)preferencesPath:(NSString *)fileName
{
    return [[[VAppInfo sharedInstance] preferencesPath] stringByAppendingPathComponent:fileName];
}

+(BOOL)fileIsExist:(NSString*)file
{
    return [[NSFileManager defaultManager] fileExistsAtPath:file];
}

+(NSString *)getDirPathCreateIfNeed:(NSString*)dirPath
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    if ( ![fileManager fileExistsAtPath:dirPath] ) {
        [fileManager createDirectoryAtPath:dirPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:NULL];
    }

    return dirPath;
}

+(NSString *)getFilePathCreateIfNeed:(NSString*)dirPath file:(NSString*)fileName
{
    return [[Utilities getDirPathCreateIfNeed:dirPath]
            stringByAppendingPathComponent:fileName];
}

+(NSString *)getMD5FilePathCreateIfNeed:(NSString*)dirPath file:(NSString*)fileName
{
    return [self getFilePathCreateIfNeed:dirPath
                                    file:[self MD5StringWithKey:fileName]];
}

+(NSString *)MD5StringWithKey:(NSString*)key
{
    const char *str = [key UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *md5str = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"
                        "%02x%02x%02x%02x%02x%02x",
                        r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                        r[10], r[11], r[12], r[13], r[14], r[15]];
    return md5str;
}

+(NSString *)diskSizeToHumanString:(unsigned long long)bytes
{
    char buff[128] = { 0 };
    NSString *nsRet = nil;

    long G = bytes / kBytesPerG;
    long M = (bytes - G * kBytesPerG) / kBytesPerM;
    long K = (bytes - G * kBytesPerG - M * kBytesPerM) / kBytesPerK;
    long B = bytes - G * kBytesPerG - M * kBytesPerM - K * kBytesPerK;

    if ( G > 0 )
        snprintf(buff, sizeof(buff), "%.2fGB", (double)bytes / kBytesPerG);
    else if ( M > 0 )
        snprintf(buff, sizeof(buff), "%ldMB", M + 1);
    else if ( K > 0 )
        snprintf(buff, sizeof(buff), "%ldKB", K + 1);
    else
        snprintf(buff, sizeof(buff), "%ldB", B);

    nsRet = [[NSString alloc] initWithCString:buff
                                      encoding:NSUTF8StringEncoding];

    return nsRet;
}

+(NSString *)timeToHumanString:(unsigned long)ms
{
    unsigned long seconds, h, m, s;
    char buff[128] = { 0 };
    NSString *nsRet = nil;

    seconds = ms / 1000;
    h = seconds / 3600;
    m = (seconds - h * 3600) / 60;
    s = seconds - h * 3600 - m * 60;
    snprintf(buff, sizeof(buff), "%02ld:%02ld:%02ld", h, m, s);
    nsRet = [[NSString alloc] initWithCString:buff
                                      encoding:NSUTF8StringEncoding];

    return nsRet;
}

+(NSString *)getNowTimeForHumanString
{
    NSDate *now = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];
	[formatter setDateFormat:@"HH:mm"];
    NSString *nsNow = [formatter stringFromDate:now];

    return nsNow;
}

+(NSString *)dateTimeToHumanString:(NSDate*)date
{
    if ( date == nil ) return nil;

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    NSString *ns = [formatter stringFromDate:date];

    return ns;
}

+(NSString *)getBatteryLevelForHumanString
{
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    float battLvl = [[UIDevice currentDevice] batteryLevel];
    char buff[32] = { 0 };
    NSString *nsRet = nil;

    snprintf(buff, sizeof(buff), "%d%%", (int)(battLvl * 100));
    nsRet = [[NSString alloc] initWithCString:buff
                                      encoding:NSUTF8StringEncoding];

    return nsRet;
}

+(NSString *)percentageToHumanString:(float)percentage
{
    char buff[16] = { 0 };
    NSString *nsRet = nil;

    snprintf(buff, sizeof(buff), "%d%%", (int)(percentage * 100));
    nsRet = [[NSString alloc] initWithCString:buff
                                      encoding:NSUTF8StringEncoding];

    return nsRet;
}

+(BOOL)isLocalMedia:(NSURL*)url
{
    static NSString * const local = @"/";
    static NSString * const local2 = @"file://localhost/";
    static NSString * const iPod = @"ipod-library://";
    static NSString * const camera = @"assets-library://";

    NSString * urlStr = [url absoluteString];
    if ( [urlStr hasPrefix:local] ) return YES;
    if ( [urlStr hasPrefix:local2] ) return YES;
    if ( [urlStr hasPrefix:iPod] ) return YES;
    if ( [urlStr hasPrefix:camera] ) return YES;

    return NO;
}

+(BOOL)isIPodOrCameraFile:(NSURL*)url
{
    static NSString * const iPod = @"ipod-library://";
    static NSString * const camera = @"assets-library://";

    NSString * urlStr = [url absoluteString];
    if ( [urlStr hasPrefix:iPod] ) return YES;
    if ( [urlStr hasPrefix:camera] ) return YES;

    return NO;
}

+(void)removeFileInSharingLibrary:(NSURL*)fileURL
{
    if ( ![fileURL isFileURL] ) {
        return;
    }
    NSFileManager *fileMg = [[NSFileManager alloc] init];
    [fileMg removeItemAtPath:[fileURL path] error:nil];
}

+(BOOL)file:(NSString *)file isExpirationWithSeconds:(int)secs
{
    if (!file || ![[NSFileManager defaultManager] fileExistsAtPath:file])
		return YES;
    NSDate *exp = [NSDate dateWithTimeIntervalSinceNow:-secs];
	NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:file error:nil];
	if ([[[attrs fileModificationDate] laterDate:exp] isEqualToDate:exp]) {
		return YES;
    }
	return NO;
}

+(BOOL)systemVersionIsHighOrEqualToIt:(NSString*)minSystemVersion
{
	NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
	if ( [systemVersion compare:minSystemVersion options:NSNumericSearch] != NSOrderedAscending ) {
        return YES;
    }
    return NO;
}

+(BOOL)systemVersionIsEqualToIt:(NSString*)version
{
	NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
	if ( [systemVersion compare:version options:NSNumericSearch] == NSOrderedSame ) {
        return YES;
    }
    return NO;
}

+(BOOL)isFirstTimeTouchHere:(NSString *)str
{
	assert(str != nil && ![str isEqualToString:@""]);
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:str] == nil) {
		[defaults setObject:str forKey:str];
		[defaults synchronize];
        return YES;
    }
    return NO;
}

+(UIColor*)colorR:(int)r G:(int)g B:(int)b A:(int)a
{
	return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a/255.0];
}

+(UIColor*)colorWithRed:(int)r withGreen:(int)g withBlue:(int)b
{
	return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0];
}

+(UIColor*)colorWithHexNumber:(unsigned long)colorHex
{
    return [UIColor colorWithRed:((colorHex & 0xFF000000) >> 24)/255.0
                           green:((colorHex & 0x00FF0000) >> 16)/255.0
                            blue:((colorHex & 0x0000FF00) >> 8) /255.0
                           alpha:((colorHex & 0x000000FF))      /255.0];
}

+(unsigned long)colorHexNumberWithUIColor:(UIColor *)color
{
	CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 1.0;
	const CGFloat *components = CGColorGetComponents(color.CGColor);
	size_t num = CGColorGetNumberOfComponents(color.CGColor);
	if (num == 4) {
		red = components[0];
		green = components[1];
		blue = components[2];
		alpha = components[3];
	} else if (num == 3) {
		red = components[0];
		green = components[1];
		blue = components[2];
	}

	int r = (int)(red * 255)   & 0xFF;
	int g = (int)(green * 255) & 0xFF;
	int b = (int)(blue * 255)  & 0xFF;
	int a = (int)(alpha * 255) & 0xFF;
	unsigned long rgba = r<<24 | g<<16 | b<< 8 | a;

	return rgba;
}

+(float)getCurSystemVolume
{
    return [[MPMusicPlayerController applicationMusicPlayer] volume];
}

+(float)getCurSystemBright
{
    if ( [[UIScreen mainScreen] respondsToSelector:@selector(brightness)] ) {
        return [UIScreen mainScreen].brightness;
    }
    return 1.0;
}

+(void)setCurSystemVolume:(float)volume
{
    [[MPMusicPlayerController applicationMusicPlayer] setVolume:volume];
}

+(void)setCurSystemBright:(float)bright
{
    if ( [[UIScreen mainScreen] respondsToSelector:@selector(brightness)] ) {
        [[UIScreen mainScreen] setBrightness:bright];
    }
}

+(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    if ( ! [[NSFileManager defaultManager] fileExistsAtPath:[URL path]] ) return YES;

    BOOL success = YES;
    if ( [self systemVersionIsHighOrEqualToIt:@"5.1"] ) {
        NSError *error = nil;
        success = [URL setResourceValue:[NSNumber numberWithBool:YES]
                                 forKey:NSURLIsExcludedFromBackupKey
                                  error:&error];
    } else if ( [self systemVersionIsEqualToIt:@"5.0.1"] ) {
        const char *filePath = [[URL path] fileSystemRepresentation];
        const char *attrName = "com.apple.MobileBackup";
        u_int8_t attrValue = 1;
        int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
        success = (result == 0);
    }

    return success;
}

+(void)showErrorView:(NSString *)sError withReason:(NSString *)sReason
{
	if (!sError) sError = @"Unknown Error";
	if (!sReason) sReason = @"Unknown Reason!";

	NSDictionary *errorDict = [NSDictionary dictionaryWithObjectsAndKeys:
							   sError, NSLocalizedDescriptionKey,
							   sReason, NSLocalizedFailureReasonErrorKey,
							   nil];
	NSError *error = [NSError errorWithDomain:@"VPlayer" code:0 userInfo:errorDict];

	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription]
														message:[error localizedFailureReason]
													   delegate:nil
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
	[alertView show];
}

#pragma mark - debug utilities

+(BOOL)saveYUV420PDataToFile:(NSString*)filename
                       withY:(uint8_t*)y
                       withU:(uint8_t*)u
                       withV:(uint8_t*)v
                withLinesize:(int[3])linesize
                       withW:(int)w
                       withH:(int)h
{
#define kDebugYUV420PDirPath [[VAppInfo sharedInstance] homePath]

    size_t ret;
    FILE *pYUV = NULL;
    NSString *savefile = [self getFilePathCreateIfNeed:kDebugYUV420PDirPath file:filename];

    pYUV = fopen([savefile cStringUsingEncoding:NSUTF8StringEncoding], "w");
    if ( pYUV == NULL ) return NO;

    ret = fwrite(&w, 1, sizeof(int), pYUV);
    ret = fwrite(&h, 1, sizeof(int), pYUV);

    ret = fwrite(y, 1, sizeof(uint8_t)*w*h, pYUV);
    ret = fwrite(u, 1, sizeof(uint8_t)*(w/2)*(h/2), pYUV);
    ret = fwrite(v, 1, sizeof(uint8_t)*(w/2)*(h/2), pYUV);
    assert(ret == (w/2)*(h/2));

    fclose(pYUV);

    return YES;

#undef kDebugYUV420PDirPath
}

@end


text:
package no.notanumber.sosql;

public class DatabaseColumn {

    public static final String UNDEFINED = "UNDEFINED";

    public final String columnName;

    public final String table;
    public final String joinedTo;
    public final ColumnType type;
    public final Class<?> clazz;
    public final int length;

    public DatabaseColumn(String columnName, Class<?> clazz, String table) {
        this(columnName, clazz, table, 50);
    }

    public DatabaseColumn(String columnName, Class<?> clazz, String table, int length) {
        this.columnName = columnName;
        this.clazz = clazz;
        this.table = table;
        type = ColumnType.Field;
        this.joinedTo = null;
        this.length = length;
    }

    public DatabaseColumn(String columnName, Class<?> clazz, String table, ColumnType type) {
        this.columnName = columnName;
        this.clazz = clazz;
        this.table = table;
        this.type = type;
        this.joinedTo = null;
        this.length = 50;
    }

    public DatabaseColumn(String columnName, Class<?> clazz, String table, ColumnType type, String joinedTo) {
        this.columnName = columnName;
        this.clazz = clazz;
        this.table = table;
        this.type = type;
        this.joinedTo = joinedTo;
        this.length = 50;
    }

}


text:
Major

### Version Introduced
4.5.1

### Version Reverted
4.6

### Source Analyzer Status
Available

### Change Description
MSBuild 12.0 tools (included in Visual Studio 2013) changed MSBuild file
locations, causing older Entity Framework targets files to be invalid. The
result is that `EntityDeploySplit` and `EntityClean` tasks fail because they are
unable to find `Microsoft.Data.Entity.Build.Tasks.dll`. Note that this break is
because of a toolset (MSBuild/VS) change, not because of a .NET Framework
change. It will only occur when upgrading developer tools, not when merely
upgrading the .NET Framework.

- [ ] Quirked
- [x] Build-time break

### Recommended Action
Entity Framework targets files are fixed to work with the new MSBuild layout beginning in the .NET Framework 4.6. Upgrading to that version of the Framework will fix this issue. Alternatively, [this workaround](https://stackoverflow.com/a/24249247/131944) can be used to patch the targets files directly.

### Affected APIs
* Not detectable via API analysis

### Category
Entity Framework

[More information](https://stackoverflow.com/questions/20400054/entitydeploysplit-error-microsoft-data-entity-build-tasks-dll-missing/24249247#24249247)

<!-- breaking change id: 109 -->


text:
module Problem32 where

import Data.Char
import Data.List

digits :: Int -> [Int]
digits n = map digitToInt $ show n

consistOf :: Int -> [Int] -> Bool
consistOf n xs = sort (digits n) == sort xs

canDigitMul :: Int -> Int -> Int -> Bool
canDigitMul x y z =
  x + y == z + 1 || x + y == z

multipliableDigitsInSum :: Int -> [(Int, Int)]
multipliableDigitsInSum s =
  [(x, y) | x <- [1..(s-2)], y <- [x..(s-x-1)], canDigitMul x y (s-x-y)]

removeElement :: Eq a => a -> [a] -> [a]
removeElement a xs =
  case elemIndex a xs of
    Just idx -> fst split ++ (tail.snd) split where split = splitAt idx xs
    Nothing  -> xs

integersFromListWithDigit :: Int -> [Int] -> [Int]
integersFromListWithDigit 1 xs = xs
integersFromListWithDigit digit xs =
  [x * 10^(digit-1) + rest | x <- xs,
                             rest <- integersFromListWithDigit (digit-1) (removeElement x xs)]

diff :: Eq a => [a] -> [a] -> [a]
diff = foldl (flip removeElement)

getPandigitalProduct :: (Int, Int) -> [Int]
getPandigitalProduct (xDigit, yDigit) =
  [z | x <- integersFromListWithDigit xDigit [1..9],
       let yDigits = diff [1..9] $ digits x,
       y <- integersFromListWithDigit yDigit yDigits,
       let zDigits = diff yDigits $ digits y,
       let z = x * y,
       consistOf z zDigits]

removeDuplication :: (Ord a) => [a] -> [a]
removeDuplication = map head . group . sort

main :: IO ()
main = print $
  sum $ removeDuplication $ foldl1 (++) $ map getPandigitalProduct digitPairs
  where digitPairs = multipliableDigitsInSum 10


text:
namespace GafferScene
{

typedef Gaffer::ContextProcessor<SceneContextProcessorBase> SceneContextProcessor;
typedef Gaffer::TimeWarp<SceneContextProcessorBase> SceneTimeWarp;
IE_CORE_DECLAREPTR( SceneTimeWarp )

} // namespace GafferScene

#endif // GAFFER_SCENETIMEWARP_H


text:
SELECT
  public.vw_get_profilestructureattributes.profileshortname AS "metadataProfileName",
  public.vw_get_profilestructureattributes.profileversion AS "metadataProfileVersion",
  public.vw_get_profilestructureattributes.attributename AS "attributeName",
  replace(public.vw_get_profilestructureattributes.attributename, '_', ' ') AS "displayName",
  public.vw_get_profilestructureattributes.attributedescription AS "description",
  public.vw_get_profilestructureattributes.attributevalues AS "exampleValues",
  trim(both public.vw_get_profilestructureattributes.fmt_structuretype) AS "metadataType",
  trim(both public.vw_get_profilestructureattributes.fmt_structurename_short) AS "metadataTypeStructure",
  trim(both public.vw_get_profilestructureattributes.fmt_structurename_short) AS "metadataTypeStructureName",
  trim(both public.vw_get_profilestructureattributes."group") AS "metadataGroup",
  public.vw_get_profilestructureattributes.attributetype AS "metadataValueType",
  public.vw_get_profilestructureattributes.attributenecessity AS "complianceLevel"
FROM
  public.vw_get_profilestructureattributes
WHERE
  public.vw_get_profilestructureattributes.idprofile = 2 AND
  public.vw_get_profilestructureattributes.attributename IS NOT NULL
ORDER BY
  public.vw_get_profilestructureattributes."order";


text:
__author__ = 'brad'
import pygame
import pyaudio
import backend
from ctypes import *
from contextlib import contextmanager

ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)

def py_error_handler(filename, line, function, err, fmt):
    pass

c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)

@contextmanager
def noalsaerr():
    asound = cdll.LoadLibrary('libasound.so.2')
    asound.snd_lib_error_set_handler(c_error_handler)
    yield
    asound.snd_lib_error_set_handler(None)

class ResourceManager(object):
    def __init__(self, force_pygame=True, force_pyaudio=True, muted=False):
        pygame.font.init()
        # pygame.mixer.init()
        self.sprites = {}
        self.music = {}
        self.sounds = {}
        self.fonts = {}
        self.force_pygame = force_pygame
        self.force_pyaudio = force_pyaudio
        self.muted = muted
        self.current_key = None
        with noalsaerr():
            self.pya = pyaudio.PyAudio()
        self.sound_channels = 4
        self.current_sounds = [backend.Sound(self.pya) for x in xrange(self.sound_channels)]
        self.sound_queue_index = 0

    def add_image(self, key, image):
        self.sprites[key] = image

    def add_image_list(self, key, images):
        self.sprites[key] = images

    def add_image_file(self, key, filename):
        try:
            self.sprites[key] = pygame.image.load(filename).convert_alpha()
            return True
        except:
            return False

    def remove_image(self, key):
        del self.sprites[key]

    def add_image_file_list(self, key, filenames):
        self.sprites[key] = []
        for filename in filenames:
            try:
                self.sprites[key].append(pygame.image.load(filename).convert_alpha())
            except:
                pass

    def add_spritesheet_image(self, key, spritesheet, rectangle, colorkey=None):
        self.sprites[key] = spritesheet.image_at(rectangle, colorkey)

    def add_spritesheet_image_list(self, key, spritesheet, rectangle_list, colorkey=None):
        self.sprites[key] = spritesheet.images_at(rectangle_list, colorkey)

    def add_spritesheet_strip(self, key, spritesheet, rect, image_count, colorkey=None):
        self.sprites[key] = spritesheet.load_strip(rect, image_count, colorkey)

    def add_spritesheet_strip_offsets(self, key, spritesheet, topleft, image_count, per_line, image_size, hor_offset,
                                      ver_offset, colorkey=None):
        self.sprites[key] = spritesheet.load_strip_offsets(topleft, image_count, per_line, image_size, hor_offset,
                                                           ver_offset, colorkey)

    def get_images(self, key):
        return self.sprites[key]

    def add_font(self, key, filename, size):
        self.fonts[key] = pygame.font.Font(filename, size)

    def remove_font(self, key):
        del self.fonts[key]

    def add_music(self, key, filename):
        # if pyglet.media.have_avbin and not self.force_pygame:
        #     self.music[key] = pyglet.media.load(filename)
        if self.force_pyaudio:
            self.music[key] = backend.SoundStream(self.pya, filename)
        else:
            self.music[key] = filename

    def remove_music(self, key):
        del self.music[key]

    def play_music(self, key, start=0):
        if not self.muted:
            # if pyglet.media.have_avbin and not self.force_pygame:
            #     self.music[key].play()
            if self.force_pyaudio:
                if self.current_key is not None:
                    self.music[self.current_key].stop()
                self.music[key].play()
                self.current_key = key
            else:
                pygame.mixer.music.load(self.music[key])
                pygame.mixer.music.play(-1)
        # pygame.mixer.music.set_pos(start)
        # if pyglet.media.have_avbin and not self.force_pygame:
        #     self.music[key].play()

    def add_sound(self, key, filename):
        # if pyglet.media.have_avbin and not self.force_pygame:
        #     self.sounds[key] = pyglet.media.load(filename, streaming=False)
        if self.force_pyaudio:
            self.sounds[key] = backend.WaveFile(filename)
        else:
            self.sounds[key] = pygame.mixer.Sound(filename)
        # pass

    def remove_sound(self, key):
        del self.sounds[key]

    def play_sound(self, key):
        if not self.muted:
            if self.force_pyaudio:
                self.current_sounds[self.sound_queue_index].play(self.sounds[key])
                self.sound_queue_index += 1
                if self.sound_queue_index > self.sound_channels - 1:
                    self.sound_queue_index = 0
            else:
                self.sounds[key].play()
            # self.current_sounds.append(self.sounds[key])

    def update_sound(self):
        if self.current_key is not None:
            if self.force_pyaudio:
                if self.current_key is not None:
                    self.music[self.current_key].update()


text:
import type A from "A";
import type { B } from "B";
import C from "C";

export { A, B, C } // <-- A and B will be removed


text:
/*	$NetBSD: mot_ulmb60xa.c,v 1.5 2002/05/15 21:06:11 kleink Exp $	*/

/*-
 * Copyright (c) 2002 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Klaus J. Klein.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the NetBSD
 *	Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/systm.h>

#include <machine/bus.h>
#include <machine/intr.h>
#include <machine/platform.h>
#include <machine/residual.h>

/*
 * CPU Type Register
 * These definitions should eventually be moved to a separate header file.
 */
#define	MOT_CPUTYPE_REG			(PREP_BUS_SPACE_IO + 0x0800)

/* Cache Size */
#define	MOT_CPUTYPE_CSIZE_SHIFT		0
#define	MOT_CPUTYPE_CSIZE_MASK		0x3
#define	MOT_CPUTYPE_CSIZE(ct) \
    (((ct) >> MOT_CPUTYPE_CSIZE_SHIFT) & MOT_CPUTYPE_CSIZE_MASK)

#define	MOT_CPUTYPE_CSIZE_512K		0
#define	MOT_CPUTYPE_CSIZE_256K		1
#define	MOT_CPUTYPE_CSIZE_RESERVED	2
#define	MOT_CPUTYPE_CSIZE_NONE		3

/* Board ID */
#define	MOT_CPUTYPE_BOARDID_SHIFT	4
#define	MOT_CPUTYPE_BOARDID_MASK	0xf
#define	MOT_CPUTYPE_BOARDID(ct) \
    (((ct) >> MOT_CPUTYPE_BOARDID_SHIFT) & MOT_CPUTYPE_BOARDID_MASK)

#define	MOT_CPUTYPE_BOARDID_ULTRA	4
#define	MOT_CPUTYPE_BOARDID_MTX		14

static int mot_ulmb60xa_match(struct platform *);

struct platform platform_mot_ulmb60xa = {
	"BULL ESTRELLA (e0)         (e0)",	/* model */ /* XXX */
	mot_ulmb60xa_match,			/* match */
	prep_pci_get_chipset_tag_indirect,	/* pci_get_chipset_tag */
	pci_intr_fixup_mot_ulmb60xa,		/* pci_intr_fixup */
	ext_intr_ivr,				/* ext_intr */
	cpu_setup_unknown,			/* cpu_setup */
	reset_prep_generic,			/* reset */
	obiodevs_nodev,				/* obiodevs */
};

static int
mot_ulmb60xa_match(struct platform *p)
{
	uint8_t cputype;

	if (p == NULL || p->model == NULL)
		return 0;
	if (strcmp(res->VitalProductData.PrintableModel, p->model) != 0)
		return 0;
	/* Should possibly match against the FirmwareSupplier as well. */
	cputype = *(volatile uint8_t *)MOT_CPUTYPE_REG;
	__asm __volatile ("eieio; sync");
	if (MOT_CPUTYPE_BOARDID(cputype) != MOT_CPUTYPE_BOARDID_ULTRA)
		return 0;

	return 1;
}

void
pci_intr_fixup_mot_ulmb60xa(int bus, int dev, int *line)
{

	if (bus != 0)
		return;

	switch (dev) {
	case 12:		/* NCR 53c810 */
		*line = 11;
		break;
	case 14:		/* DEC 21440 */
		*line = 9;
		break;
	case 16:		/* Slot #1 */
		*line = 9;
		break;
	case 17:		/* Slot #2 */
		*line = 9;
		break;
	case 18:		/* Slot #3 */
		*line = 11;
		break;
	}
}


text:
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

/**
 * This is the class for the player
 * @author Jeremy
 *
 */
public class Player extends GameObject {
	private Image img = new Image("Images/myPlayer.jpg");
	static final int PLAYER_SPEED = 20;
	static final int PLAYER_SIZE = 50;
	static final int PLAYER_START_X = 250;
	static final int PLAYER_START_Y = 480;
	Player() {
		setSpeedSizeImageXY(PLAYER_SPEED,PLAYER_SIZE,img,PLAYER_START_X,PLAYER_START_Y);
	}

	Player(int XPosition,int YPosition) {
		setSpeedSizeImageXY(PLAYER_SPEED,PLAYER_SIZE,img,setPlayerXPosition(XPosition),setPlayerYPosition(YPosition));
		setCenterY(setPlayerYPosition(YPosition));
	}

	public int setPlayerXPosition (int width) {
		return width/2;
	}

	public int setPlayerYPosition (int height) {
		return height - getSize();
	}

}


text:
package net.sandius.rembulan.compiler.ir;

public abstract class AbstractVar {

}


text:
class SubmitMailer < ApplicationMailer
  def email(message)
    @from_address = message.from_address
    @from_name = message.from_name
    @body_html = message.body_html
    @body_text = message.body_text

    mail(
      to: message.to,
      from: message.from,
      reply_to: message.reply_to,
      subject: message.subject
    )
  end
end