text:
namespace llvm {

class Type;
class Instruction;
class GlobalValue;
class DSGraph;
class DSCallSite;
class DSNode;
class DSNodeHandle;

FunctionPass *createDataStructureStatsPass();
FunctionPass *createDataStructureGraphCheckerPass();

class InstCallGraph {
  typedef hash_map<const Instruction*, std::vector<const Function*> > ActualCalleesTy;

  // Callgraph
  ActualCalleesTy ActualCallees;

public:

  InstCallGraph() {
    //Dummy node for empty call sites
    ActualCallees[0];
  }

  typedef std::vector<const Function*>::const_iterator iterator;

  void add(const Instruction* I, const Function* F) {
    std::vector<const Function*>& callees = ActualCallees[I];
    std::vector<const Function*>::iterator ii
      = std::lower_bound(callees.begin(), callees.end(), F);
    if (ii != callees.end() && *ii == F) return;
    callees.insert(ii, F);
  }

  iterator begin(const Instruction *I) const {
    ActualCalleesTy::const_iterator ii = ActualCallees.find(I);
    if (ii == ActualCallees.end())
      ii = ActualCallees.find(0);
    return ii->second.begin();
  }

  iterator end(const Instruction *I) const {
    ActualCalleesTy::const_iterator ii = ActualCallees.find(I);
    if (ii == ActualCallees.end())
      ii = ActualCallees.find(0);
    return ii->second.end();
  }

  unsigned size() const {
    unsigned sum = 0;
    for (ActualCalleesTy::const_iterator ii = ActualCallees.begin(),
           ee = ActualCallees.end(); ii != ee; ++ii)
      sum += ii->second.size();
    return sum;
  }

  template<class OutputIterator>
  void get_keys(OutputIterator keys) {
    for (ActualCalleesTy::const_iterator ii = ActualCallees.begin(),
           ee = ActualCallees.end(); ii != ee; ++ii)
      *keys++ = ii->first;
  }

  void clear() {
    ActualCallees.clear();
  }
};

class DataStructures : public ModulePass {
  typedef hash_map<const Function*, DSGraph*> DSInfoTy;

  /// DataLayout, comes in handy
  DataLayout* TD;

  /// Pass to get Graphs from
  DataStructures* GraphSource;

  /// Do we clone Graphs or steal them?
  bool Clone;

  /// do we reset the aux list to the func list?
  bool resetAuxCalls;

  /// Were are DSGraphs stolen by another pass?
  bool DSGraphsStolen;

  // DSInfo, one graph for each function
  DSInfoTy DSInfo;

  // Name for printing
  const char* printname;

protected:

  /// The Globals Graph contains all information on the globals
  DSGraph *GlobalsGraph;

  /// GlobalECs - The equivalence classes for each global value that is merged
  /// with other global values in the DSGraphs.
  EquivalenceClasses<const GlobalValue*> GlobalECs;

  void init(DataStructures* D, bool clone, bool useAuxCalls, bool copyGlobalAuxCalls, bool resetAux);
  void init(DataLayout* T);

  void formGlobalECs();

  DataStructures(intptr_t id, const char* name)
    : ModulePass(id), TD(0), GraphSource(0), printname(name), GlobalsGraph(0) {

    // For now, the graphs are owned by this pass
    DSGraphsStolen = false;
  }

public:
  /// print - Print out the analysis results...
  ///
  void print(std::ostream &O, const Module *M) const;
  void dumpCallGraph() const;

  typedef InstCallGraph calleeTy;
  calleeTy callee;

  virtual void releaseMemory();

  virtual bool hasDSGraph(const Function* F) const {
    return DSInfo.find(F) != DSInfo.end();
  }

  /// getDSGraph - Return the data structure graph for the specified function.
  ///
  virtual DSGraph *getDSGraph(const Function* F) const {
    hash_map<const Function*, DSGraph*>::const_iterator I = DSInfo.find(F);
    assert(I != DSInfo.end() && "Function not in module!");
    return I->second;
  }

  void setDSGraph(const Function* F, DSGraph* G) {
    DSInfo[F] = G;
  }

  DSGraph* getOrFetchDSGraph(const Function* F);

  DSGraph* getGlobalsGraph() const { return GlobalsGraph; }

  EquivalenceClasses<const GlobalValue*> &getGlobalECs() { return GlobalECs; }

  DataLayout& getDataLayout() const { return *TD; }

  /// deleteValue/copyValue - Interfaces to update the DSGraphs in the program.
  /// These correspond to the interfaces defined in the AliasAnalysis class.
  void deleteValue(Value *V);
  void copyValue(Value *From, Value *To);
};

// LocalDataStructures - The analysis that computes the local data structure
// graphs for all of the functions in the program.
//
// FIXME: This should be a Function pass that can be USED by a Pass, and would
// be automatically preserved.  Until we can do that, this is a Pass.
//
class LocalDataStructures : public DataStructures {
public:
  static char ID;
  LocalDataStructures() : DataStructures((intptr_t)&ID, "local.") {}
  ~LocalDataStructures() { releaseMemory(); }

  virtual bool runOnModule(Module &M);

  /// getAnalysisUsage - This obviously provides a data structure graph.
  ///
  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    AU.addRequired<DataLayout>();
    AU.setPreservesAll();
  }
};

// StdLibDataStructures - This analysis recognizes common standard c library
// functions and generates graphs for them.
class StdLibDataStructures : public DataStructures {
  void eraseCallsTo(Function* F);
public:
  static char ID;
  StdLibDataStructures() : DataStructures((intptr_t)&ID, "stdlib.") {}
  ~StdLibDataStructures() { releaseMemory(); }

  virtual bool runOnModule(Module &M);

  /// getAnalysisUsage - This obviously provides a data structure graph.
  ///
  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    AU.addRequired<LocalDataStructures>();
    AU.addPreserved<DataLayout>();
    AU.setPreservesCFG();
  }
};

/// BUDataStructures - The analysis that computes the interprocedurally closed
/// data structure graphs for all of the functions in the program.  This pass
/// only performs a "Bottom Up" propagation (hence the name).
///
class BUDataStructures : public DataStructures {
protected:

  // This map is only maintained during construction of BU Graphs
  std::map<std::vector<const Function*>,
           std::pair<DSGraph*, std::vector<DSNodeHandle> > > IndCallGraphMap;

  const char* debugname;
  bool useCallGraph;
  bool ReInlineGlobals;

public:
  static char ID;
  //Child constructor (CBU)
  BUDataStructures(intptr_t CID, const char* name, const char* printname)
    : DataStructures(CID, printname), debugname(name), useCallGraph(true),
      ReInlineGlobals(true) {}
  //main constructor
  BUDataStructures()
    : DataStructures((intptr_t)&ID, "bu."), debugname("dsa-bu"),
      useCallGraph(false), ReInlineGlobals(false) {}
  ~BUDataStructures() { releaseMemory(); }

  virtual bool runOnModule(Module &M);

  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    AU.addRequired<StdLibDataStructures>();
    AU.addPreserved<DataLayout>();
    AU.setPreservesCFG();
  }

protected:
  bool runOnModuleInternal(Module &M);

private:
  void calculateGraph(DSGraph* G);

  void inlineUnresolved(DSGraph* G);

  unsigned calculateGraphs(const Function *F,
                           std::vector<const Function*> &Stack,
                           unsigned &NextID,
                           hash_map<const Function*, unsigned> &ValMap);

  void CloneAuxIntoGlobal(DSGraph* G);
  void finalizeGlobals(void);
};

/// CompleteBUDataStructures - This is the exact same as the bottom-up graphs,
/// but we use take a completed call graph and inline all indirect callees into
/// their callers graphs, making the result more useful for things like pool
/// allocation.
///
class CompleteBUDataStructures : public  BUDataStructures {
protected:
  void buildIndirectFunctionSets(Module &M);
public:
  static char ID;
  CompleteBUDataStructures(intptr_t CID = (intptr_t)&ID,
                           const char* name = "dsa-cbu",
                           const char* printname = "cbu.")
    : BUDataStructures(CID, name, printname) {}
  ~CompleteBUDataStructures() { releaseMemory(); }

  virtual bool runOnModule(Module &M);

  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    AU.addRequired<BUDataStructures>();
    AU.addPreserved<DataLayout>();
    AU.setPreservesCFG();
  }

};

/// EquivBUDataStructures - This is the same as the complete bottom-up graphs, but
/// with functions partitioned into equivalence classes and a single merged
/// DS graph for all functions in an equivalence class.  After this merging,
/// graphs are inlined bottom-up on the SCCs of the final (CBU) call graph.
///
class EquivBUDataStructures : public CompleteBUDataStructures {
  void mergeGraphsByGlobalECs();
public:
  static char ID;
  EquivBUDataStructures()
    : CompleteBUDataStructures((intptr_t)&ID, "dsa-eq", "eq.") {}
  ~EquivBUDataStructures() { releaseMemory(); }

  virtual bool runOnModule(Module &M);

  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    AU.addRequired<CompleteBUDataStructures>();
    AU.addPreserved<DataLayout>();
    AU.setPreservesCFG();
  }

};

/// TDDataStructures - Analysis that computes new data structure graphs
/// for each function using the closed graphs for the callers computed
/// by the bottom-up pass.
///
class TDDataStructures : public DataStructures {
  hash_set<const Function*> ArgsRemainIncomplete;

  /// CallerCallEdges - For a particular graph, we keep a list of these records
  /// which indicates which graphs call this function and from where.
  struct CallerCallEdge {
    DSGraph *CallerGraph;        // The graph of the caller function.
    const DSCallSite *CS;        // The actual call site.
    const Function *CalledFunction;    // The actual function being called.

    CallerCallEdge(DSGraph *G, const DSCallSite *cs, const Function *CF)
      : CallerGraph(G), CS(cs), CalledFunction(CF) {}

    bool operator<(const CallerCallEdge &RHS) const {
      return CallerGraph < RHS.CallerGraph ||
            (CallerGraph == RHS.CallerGraph && CS < RHS.CS);
    }
  };

  std::map<DSGraph*, std::vector<CallerCallEdge> > CallerEdges;

  // IndCallMap - We memoize the results of indirect call inlining operations
  // that have multiple targets here to avoid N*M inlining.  The key to the map
  // is a sorted set of callee functions, the value is the DSGraph that holds
  // all of the caller graphs merged together, and the DSCallSite to merge with
  // the arguments for each function.
  std::map<std::vector<const Function*>, DSGraph*> IndCallMap;

  bool useEQBU;

public:
  static char ID;
  TDDataStructures(intptr_t CID = (intptr_t)&ID, const char* printname = "td.", bool useEQ = false)
    : DataStructures(CID, printname), useEQBU(useEQ) {}
  ~TDDataStructures() { releaseMemory(); }

  virtual bool runOnModule(Module &M);

  /// getAnalysisUsage - This obviously provides a data structure graph.
  ///
  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    if (useEQBU) {
      AU.addRequired<EquivBUDataStructures>();
    } else {
      AU.addRequired<BUDataStructures>();
      AU.addPreserved<BUDataStructures>();
    }
    AU.addPreserved<DataLayout>();
    AU.setPreservesCFG();
  }

private:
  void markReachableFunctionsExternallyAccessible(DSNode *N,
                                                  hash_set<DSNode*> &Visited);

  void InlineCallersIntoGraph(DSGraph* G);
  void ComputePostOrder(const Function* F, hash_set<DSGraph*> &Visited,
                        std::vector<DSGraph*> &PostOrder);
};

/// EQTDDataStructures - Analysis that computes new data structure graphs
/// for each function using the closed graphs for the callers computed
/// by the EQ bottom-up pass.
///
class EQTDDataStructures : public TDDataStructures {
public:
  static char ID;
  EQTDDataStructures()
    :TDDataStructures((intptr_t)&ID, "eqtd.", false)
  {}
};

/// SteensgaardsDataStructures - Analysis that computes a context-insensitive
/// data structure graphs for the whole program.
///
class SteensgaardDataStructures : public DataStructures {
  DSGraph * ResultGraph;
  DataStructures * DS;
  void ResolveFunctionCall(const Function *F, const DSCallSite &Call,
                             DSNodeHandle &RetVal);
  bool runOnModuleInternal(Module &M);

public:
  static char ID;
  SteensgaardDataStructures() :
    DataStructures((intptr_t)&ID, "steensgaard."),
    ResultGraph(NULL) {}
  ~SteensgaardDataStructures();
  virtual bool runOnModule(Module &M);
  virtual void releaseMemory();

  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    AU.addRequired<DataLayout>();
    AU.addRequired<StdLibDataStructures>();
    AU.setPreservesAll();
  }

  /// getDSGraph - Return the data structure graph for the specified function.
  ///
  virtual DSGraph *getDSGraph(const Function* F) const {
    return getResultGraph();
  }

  virtual bool hasDSGraph(const Function* F) const {
    return true;
  }

  /// getDSGraph - Return the data structure graph for the whole program.
  ///
  DSGraph *getResultGraph() const {
    return ResultGraph;
  }

  void print(OStream O, const Module *M) const;
  void print(std::ostream &O, const Module *M) const;

};

} // End llvm namespace

#endif


text:
/**
 * @author TristanVALCKE / https://github.com/Itee
 */
/* global QUnit */

import { NothingsIsExportedYet } from '../../../editor/js/Loader';

export default QUnit.module( 'Editor', () => {

	QUnit.module.todo( 'Loader', () => {

		QUnit.test( 'write me !', ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

	} );

} );

redpajama_set_name: RedPajamaGithub


text:
npm-dedupe

Reduce duplication

SYNOPSIS

npm dedupe [package names...]
npm ddp [package names...]

DESCRIPTION

Searches the local package tree and attempts to simplify the overall
structure by moving dependencies further up the tree, where they can
be more effectively shared by multiple dependent packages.

For example, consider this dependency graph:

a
+-- b <-- depends on c@1.0.x
|   `-- c@1.0.3
`-- d <-- depends on c@~1.0.9
    `-- c@1.0.10

In this case, npm-dedupe(1) will transform the tree to:

a
+-- b
+-- d
`-- c@1.0.10

Because of the hierarchical nature of node's module lookup, b and d
will both get their dependency met by the single c package at the root
level of the tree.

If a suitable version exists at the target location in the tree
already, then it will be left untouched, but the other duplicates will
be deleted.

If no suitable version can be found, then a warning is printed, and
nothing is done.

If any arguments are supplied, then they are filters, and only the
named packages will be touched.

Note that this operation transforms the dependency tree, and may
result in packages getting updated versions, perhaps from the npm
registry.

This feature is experimental, and may change in future versions.

The --tag argument will apply to all of the affected dependencies. If a
tag with the given name exists, the tagged version is preferred over newer
versions.

SEE ALSO

npm-ls(1)

npm-update(1)

npm-install(1)


text:
package namecom

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/url"
)

var _ = bytes.MinRead

// ListURLForwardings returns a pagenated list of URL forwarding entries for a domain.
func (n *NameCom) ListURLForwardings(request *ListURLForwardingsRequest) (*ListURLForwardingsResponse, error) {
	endpoint := fmt.Sprintf("/v4/domains/%s/url/forwarding", request.DomainName)

	values := url.Values{}
	if request.PerPage != 0 {
		values.Set("perPage", fmt.Sprintf("%d", request.PerPage))
	}
	if request.Page != 0 {
		values.Set("page", fmt.Sprintf("%d", request.Page))
	}

	body, err := n.get(endpoint, values)
	if err != nil {
		return nil, err
	}

	resp := &ListURLForwardingsResponse{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// GetURLForwarding returns an URL forwarding entry.
func (n *NameCom) GetURLForwarding(request *GetURLForwardingRequest) (*URLForwarding, error) {
	endpoint := fmt.Sprintf("/v4/domains/%s/url/forwarding/%s", request.DomainName, request.Host)

	values := url.Values{}

	body, err := n.get(endpoint, values)
	if err != nil {
		return nil, err
	}

	resp := &URLForwarding{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// CreateURLForwarding creates an URL forwarding entry. If this is the first URL forwarding entry, it may modify the A records for the domain accordingly.
func (n *NameCom) CreateURLForwarding(request *URLForwarding) (*URLForwarding, error) {
	endpoint := fmt.Sprintf("/v4/domains/%s/url/forwarding", request.DomainName)

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.post(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &URLForwarding{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// UpdateURLForwarding updates which URL the host is being forwarded to.
func (n *NameCom) UpdateURLForwarding(request *URLForwarding) (*URLForwarding, error) {
	endpoint := fmt.Sprintf("/v4/domains/%s/url/forwarding/%s", request.DomainName, request.Host)

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.put(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &URLForwarding{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}

// DeleteURLForwarding deletes the URL forwarding entry.
func (n *NameCom) DeleteURLForwarding(request *DeleteURLForwardingRequest) (*EmptyResponse, error) {
	endpoint := fmt.Sprintf("/v4/domains/%s/url/forwarding/%s", request.DomainName, request.Host)

	post := &bytes.Buffer{}
	err := json.NewEncoder(post).Encode(request)
	if err != nil {
		return nil, err
	}

	body, err := n.delete(endpoint, post)
	if err != nil {
		return nil, err
	}

	resp := &EmptyResponse{}

	err = json.NewDecoder(body).Decode(resp)
	if err != nil {
		return nil, err
	}

	return resp, nil
}


text:
package de.shadowhunt.subversion.internal.httpv1.v1_4;

import de.shadowhunt.subversion.internal.AbstractRepositoryMoveIT;

public class RepositoryMoveIT extends AbstractRepositoryMoveIT {

    private static final Helper HELPER = new Helper();

    public RepositoryMoveIT() {
        super(HELPER.getRepositoryA(), HELPER.getTestId());
    }
}


text:
/**
 * All vendor styles that you would like to bundle should be required here.
 */

require("../../vendor/bootstrap-sass-official/assets/stylesheets/_bootstrap.scss");
require("../../../insignia/dist/insignia.css");
require("../../../PageTransitions/css/animations.css");


text:
<?php
/**
 * (c) 2013 Bossanova PHP Framework
 * http://www.bossanova-framework.com
 *
 * PHP version 5
 *
 * @category PHP
 * @package  BossanovaFramework
 * @author   Paul Hodel <paul.hodel@gmail.com>
 * @license  The MIT License (MIT)
 * @link     http://www.bossanova-framework.com
 *
 * Translation Library
 */
namespace bossanova\Translate;

class Translate
{
    // Keep the same instance all over the PHP scripting
    public static $instance = null;

    /**
    * Start the output buffering with the callback function
    *
    * @param string  $logDirectory File path to the logging directory
    * @param integer $severity One of the pre-defined severity constants
    * @return void
    */
    public function __construct()
    {
        if (!self::$instance) {
            self::$instance = $this;
            // Callback for the translation
            ob_start(function($b) {
                return $this->run($b);
            });
        }

        return self::$instance;
    }

    // Cannot be clonned
    private function __clone()
    {
    }

    /**
    * Load dictionary information, index and cache usign APC.
    *
    * @param string $locale dicionary name.
    * @return void
    */
    public function load($locale)
    {
        // Loading dictionary and caches everything

        try {
            // New dictionary to be loaded?
            if (!isset($_SESSION['locale']) || $_SESSION['locale'] != $locale) {
                // Remove any dictionary from the session
                unset($_SESSION['dictionary']);
                unset($_SESSION['locale']);
            }

            // Assembly dictionary
            if (!isset($_SESSION['dictionary']) || !$_SESSION['dictionary'] || !count($_SESSION['dictionary'])) {
                // Check if the language file exists
                if (file_exists("resources/locales/{$locale}.csv")) {
                    // Open the file and load all words in memory
                    $dictionary = $this->loadfile($locale);

                    if (count($dictionary)) {
                        // Keep dictionary in the session
                        $_SESSION['dictionary'] = $dictionary;
                        $_SESSION['locale'] = $locale;
                    }
                } else {
                    if (isset($_SESSION['locale'])) {
                        unset($_SESSION['locale']);
                    }

                    throw new \Exception("Locale file not found " . "resources/locales/{$locale}.csv");
                }
            }
        } catch (Expection $e) {
            \bossanova\Error\Error::handler("Translation error {$config[4]}", $e);
        }
    }

    /**
     * Load dictionary information, index and cache usign APC.
     *
     * @param string $locale dicionary name.
     * @return void
     */
    public function loadfile($locale)
    {
        // Open the file and load all words in memory
        $dictionary = array();

        if (file_exists("resources/locales/{$locale}.csv")) {
            $dic = fopen("resources/locales/{$locale}.csv", "r");

            while (!feof($dic)) {
                // Open word index and translate word
                $buffer = fgets($dic);
                $buffer = explode("|", $buffer);

                if ($buffer[0]) {
                    // Make sure to remove all white spaces and create a index based on the hash
                    $val = isset($buffer[1]) && trim($buffer[1]) ? $buffer[1] : $buffer[0];
                    $dictionary[md5(trim($buffer[0]))] = trim($val);
                }
            }

            fclose($dic);
        }

        return $dictionary;
    }
    /**
    * Reload dictionary information, index and cache usign APC.
    *
    * @param string $locale dictionary name.
    * @return void
    */
    public function reload($locale)
    {
        // Unset any dictionary from the session
        unset($_SESSION['dictionary']);

        // Unset locale
        unset($_SESSION['locale']);

        // Reload again
        $this->load($locale);
    }

    /**
    * Callback function
    *
    * @param string $buffer Output buffer
    * @return string $result Return buffer with all translations
    */
    public function run($buffer, $locale = null)
    {
        if (! isset($locale)) {
            $dictionary = isset($_SESSION['dictionary']) ? $_SESSION['dictionary'] : [];
        } else {
            $dictionary = $this->loadfile($locale);
        }

        // Processing buffer
        $result = '';
        $index  = '';
        $key    = '';

        $index_finded = 0;

        for ($i = 0; $i < strlen($buffer); $i++) {
            // Find one possible word mark
            if (($buffer{$i} == '^') && (strlen($buffer) > $i+2)) {
                // Check if this is a start macro, end macro (real macro to be translated)
                if ($buffer{$i+1} == '^') {
                    // start to counting or keep saving characters till the end of this word
                    if ($buffer{$i+2} == '[') {
                        $index_finded = 1;
                        $i = $i + 3;
                    }
                }
            }

            // Find one possible end word mark
            if (($buffer{$i} == ']') && (strlen($buffer) > $i+2)) {
                // Check if this is a start macro, end macro (real macro to be translated)
                if ($buffer{$i+1} == '^') {
                    // start to counting or keep saving characters till the end of this word
                    if ($buffer{$i+2} == '^') {
                        $index_finded = 0;
                        $i = $i + 3;
                    }
                }
            }

            // Check the
            if ($index_finded == 0) {
                // Check if there any word to be processed
                if ($index) {
                    // Find the hash based on index
                    $key = md5($index);

                    // Translate word
                    if (isset($dictionary[$key])) {
                        $result .= $dictionary[$key];
                    } else {
                        $result .= $index;
                    }

                    $index = '';
                }

                // Append to the final result
                if (isset($buffer{$i})) {
                    $result .= $buffer{$i};
                }
            } else {
                if (isset($buffer{$i})) {
                    // Capturing a new word
                    $index .= $buffer{$i};
                }
            }
        }

        return $result;
    }

    /**
    * Mapping all translation references
    *
    */
    public function search()
    {
        // Search application
        $words = $this->searchFolder('application');
        foreach ($words as $k => $v) {
            echo "$v|\n";
        }

        // Search templates
        $words = $this->searchFolder('templates');
        foreach ($words as $k => $v) {
            echo "$v|\n";
        }
    }

    /**
    * Search dir by dir all files looking for texts to be translates
    *
    * @param string $buffer Output buffer
    * @return string $result Return buffer with all translations
    */
    private function searchFolder($folder)
    {
        // Keep all to be translated text references
        $words = array();

        // Search all folders reading all files
        if ($dh = opendir($folder)) {
            while (false !== ($file = readdir($dh))) {
                if (substr($file, 0, 1) != '.') {
                    // Searching in a subfolder
                    if (is_dir($folder . '/' . $file)) {
                        if (($file != 'dev') && ($file != 'bin') && ($file != 'doc') && ($file != 'img')) {
                            $words = array_merge($words, $this->search_dir($folder . '/' . $file));
                        }
                    } else {
                        // Merging results
                        $words = array_merge($words, $this->getWords(file_get_contents($folder . '/' . $file)));
                    }
                }
            }

            // Close resource
            closedir($dh);
        }

        return $words;
    }

    /**
    * Search for words to be translate
    *
    * @param string $buffer full file text
    * @return string $result words to be translated
    */
    private function getWords($buffer)
    {
        // Processing buffer
        $result = array();
        $index  = '';
        $key    = '';

        $index_finded = 0;

        for ($i = 0; $i < strlen($buffer); $i++) {
            // Find one possible word mark
            if (($buffer{$i} == '^') && (strlen($buffer) > $i+2)) {
                // Check if this is a start macro, end macro (real macro to be translated)
                if ($buffer{$i+1} == '^') {
                    // start to counting or keep saving characters till the end of this word
                    if ($buffer{$i+2} == '[') {
                        $index_finded = 1;
                        $i = $i + 3;
                    }
                }
            }

            // Find one possible end word mark
            if (($buffer{$i} == ']') && (strlen($buffer) > $i+2)) {
                // Check if this is a start macro, end macro (real macro to be translated)
                if ($buffer{$i+1} == '^') {
                    // start to counting or keep saving characters till the end of this word
                    if ($buffer{$i+2} == '^') {
                        $index_finded = 0;
                        $i = $i + 3;
                    }
                }
            }

            // Check the
            if ($index_finded == 0) {
                // Check if there any word to be processed
                if ($index) {
                    // Find the hash based on index
                    $key = md5($index);

                    // Keep the word
                    $result[$key] = $index;

                    // Reset the word
                    $index = '';
                }
            } else {
                // Capturing a new word
                $index .= $buffer{$i};
            }
        }

        return $result;
    }
}


text:
from pyportfolio.models import Equity, Option, Future, Account, Trade, Commodity, Index, Currency, TradeList
from datetime import date
import unittest

AAPL = Equity(ticker='AAPL')
AAPL_option = Option(underlying=AAPL, expiry=date(2016, 6, 30), strike=105, type='call')
copper = Commodity(name='Copper')
cu_future = Future(underlying=copper, expiry=date(2020, 6, 30))
USD = Currency(name='USD')
trade = Trade(security=AAPL, amount=100, price=120, commission=7.99, currency=USD)
account = Account(name='Test Account')
account.add_trade(trade)
option_trade = Trade(security=AAPL_option, amount=100, price=20, commission=7.99, currency=USD)

class TestModels(unittest.TestCase):
    def test_account(self):
        self.assertEquals(account.positions[AAPL].amount, 100)

    def test_trade(self):
        self.assertEquals(trade.value, 100*120)
        self.assertEquals(trade.commission, 7.99)

class TestCollections(unittest.TestCase):
    def test_positions(self):
        tl = TradeList()
        tl.add_trade(trade)
        self.assertEquals(tl.positions[AAPL].amount, 100)
        self.assertEquals(tl.positions[AAPL].cost_basis, 100 * 120 + 7.99)

    def test_to_csv(self):
        tl = TradeList()
        tl.add_trade(trade)
        tl.add_trade(option_trade)
        #tl.to_csv('test.csv')


text:
The provided MATLAB MEX functions are

`ddm_fpt`: computed the first-passage time density for symmetric bounds. See [ddm_fpt.m](ddm_fpt.m) for usage information.

`ddm_fpt_full`: computes the first-passage time density for arbitrary bounds. See [ddm_fpt_full.m](ddm_fpt.m) for usage information.

`ddm_rand_sym`: samples first-passage time and boundary from diffusion models with symmetric bounds. See [ddm_rand_sym.m](ddm_rand_sym.m) for usage information.

`ddm_rand_asym`: samples first-passage time and boundary from diffusion models with asymmetric bounds. See [ddm_rand_asym.m](ddm_rand_asym.m) for usage information.

Usage
-----

The MATLAB MEX functions need to be compiled before use. To do so, run

```Shell
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_fpt.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_fpt_full.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_rand_sym.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_rand_asym.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_rand_full.cpp ../src/ddm_fpt_lib.cpp
```

at the MATLAB prompt. Alternatively, the files can be compiled at the shell. Do do so, use

```Shell
mex CXXFLAGS="$CXXFLAGS -std=c++11" ddm_fpt.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS="$CXXFLAGS -std=c++11" ddm_fpt_full.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS="$CXXFLAGS -std=c++11" ddm_rand_sym.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS="$CXXFLAGS -std=c++11" ddm_rand_asym.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_rand_full.cpp ../src/ddm_fpt_lib.cpp
```

at the Windows Command Prompt (using double quotes, (")), or

```Shell
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_fpt.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_fpt_full.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_rand_sym.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_rand_asym.cpp ../src/ddm_fpt_lib.cpp
mex CXXFLAGS='$CXXFLAGS -std=c++11' ddm_rand_full.cpp ../src/ddm_fpt_lib.cpp
```

at the Mac and Linux shell command line (using single quotes (')). Note that, for older versions of MATLAB, all occurences of `CXXFLAGS` might need to be replaced with `CFLAGS`.

The location of the `mex` executable and exact syntax for specifying the compiler flags might be depend on OS and installation details.


text:
package com.github.baoti.pioneer.ui.splash;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.github.baoti.android.presenter.ActivityView;
import com.github.baoti.pioneer.AppMain;
import com.github.baoti.pioneer.R;
import com.github.baoti.pioneer.ui.Navigator;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import dagger.Lazy;
import timber.log.Timber;

/**
 * Created by liuyedong on 14-12-18.
 */
public class SplashActivity extends ActivityView<ISplashView, SplashPresenter> implements ISplashView {

    @Bind(R.id.tv_status)
    TextView statusText;

    @Bind(R.id.btn_retain_in_bundle)
    Button retainInBundle;

    @Bind(R.id.btn_retain_in_presenter)
    Button retainInPresenter;

    @Inject
    Lazy<SplashPresenter> presenterLazy;

    @Override
    protected SplashPresenter createPresenter(ISplashView view) {
        return presenterLazy.get();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);

        AppMain.globalGraph().plus(new SplashModule()).inject(this);
    }

    @OnCheckedChanged(R.id.cb_retain)
    public void onRetainChanged(boolean checked) {
        Timber.i("retain turn %s", checked ? "on" : "off");
        setRetainPresenter(checked);
    }

    @Override
    public void showStatus(String status) {
        statusText.setText(status);
    }

    @OnClick(R.id.btn_go_to_main)
    void onGoToMainClicked() {
        getPresenter().onGoToMainClicked();
    }

    @Override
    public void navigateToMain(boolean byUser) {
        Navigator.launchMain(SplashActivity.this);
    }

    @Override
    public void hideRetainInPresenter() {
        retainInPresenter.setVisibility(View.GONE);
    }

    @Override
    public void hideRetainInBundle() {
        retainInBundle.setVisibility(View.GONE);
    }

    @OnClick(R.id.btn_retain_in_presenter)
    void onHideRetainInPresenterClicked() {
        getPresenter().onRetainInPresenterClicked();
    }

    @OnClick(R.id.btn_retain_in_bundle)
    void onHideRetainInBundleClicked() {
        getPresenter().onRetainInBundleClicked();
    }
}


text:
layout: page
title: About
---

<img src="/assets/images/me.jpg" style="width: 200px;" />

I am passionate about computers: hardware, software, theory, history... For the past few years, I have been working as a Software Developer, particularly using **Python** (my personal favorite language and [xkcd](http://xkcd.com/353) explains why), **Ruby on Rails** and **React**. In my free time, I love reading about **History**, **Politics**, and **Foreign Languages**. Check out my [portfolio](/portfolio) or [GitHub](http://github.com/matheusportela/) to see some projects I have put my hands on.

Besides being a Software Developer, my interests include classical acoustic guitar (specially Brazilian styles, such as [Choro](https://www.youtube.com/watch?v=xDzekDP4IKI), [Samba](https://www.youtube.com/watch?v=XoUtxWU8lW8) and [Bossa Nova](https://www.youtube.com/watch?v=5LfaYKdqfnY)) and foreign languages (I speak Portuguese, English, and Spanish so far).

## Education
- Dec 2019: Master of Science in Computer Science at the [New York University](http://www.nyu.edu), [Tandon School of Engineering](https://engineering.nyu.edu/)
- Dec 2015: Bachelor of Engineering in Mechatronics Engineering at the [University of Brasília](http://www.unb.br)
- Jun 2012 - Jun 2013: Exchange program at the [Australian National University](http://www.anu.edu.au)

## Experience
- Jan 2020 - Present: Software Engineer at [Justworks](https://justworks.com/)
- May 2019 - Dec 2019: Software Engineer Intern at [Justworks](https://justworks.com/)
- Sep 2018 - May 2019: Graduate Research Assistant at [Control and Network Lab](http://eeweb.poly.edu/~canlab/), [NYU Tandon School of Engineering](https://engineering.nyu.edu)
- Mar 2017 - Jul 2018: Software Developer at [Bxblue (YC S17)](https://bxblue.com.br/), accelerated by [Y Combinator](https://blog.ycombinator.com/bxblue-is-the-only-marketplace-for-payroll-secured-loans-in-brazil/)
- Jan 2017 - Jun 2017: Lecturer in Software Engineering at [University of Brasília](http://www.unb.br)
- Nov 2015 - Feb 2017: Software Developer at [Simbiose Ventures](http://www.simbioseventures.com)
- Mar 2014 - Dec 2015: General Manager at [UnBall Robot Soccer Team](http://equipeunball.wordpress.com/)
- Jun 2014 - Dec 2014: Network Engineering Intern at [IPe Network Engineering](http://www.ipe.io/)
- Dec 2012 - Mar 2013: Research Intern at [CSIRO, Australia](http://www.csiro.au/)

## Technical Skills
- Programming Languages: `Python`, `Ruby`, `C`, `C++`, `JavaScript`, `Go`, `Java`, `C#`, `Bash Script`, `MATLAB`
- Further interests: `Lisp`, `Haskell`, `Julia`, `Assembly`
- Web Frameworks: `Rails`, `Django`, `React`, `Redux`, `Flask`
- Databases: `PostgreSQL`, `MySQL`, `MongoDB`, `Redis`, `Elasticsearch`
- DevOps: `Docker`, `AWS`, `Ansible`
- Machine Learning Tools: `PyTorch`, `Numpy`, `Scikit-learn`, `Pandas`, `Tensorflow`
- Big Data: `Hadoop`, `Spark`, `Giraph`, `HDFS`
- Others: `OpenCV`, `Arduino`, `Raspberry Pi`, `OpenGL`, `Hardware`, `ROS`, `Robotics`

## Foreign Languages
- Portuguese (Native)
- English (Fluent)
- Spanish (Advanced)
- French (Intermediate)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <ImageView
        android:id="@+id/temp_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="113dp"
        android:src="@mipmap/icon_nfc"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/nfc_notice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/temp_btn"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="31dp"
        android:textSize="18dp"
        android:textColor="#bbbbbb"
        android:text="Touch GoTip on the desk" />

    <TextView
        android:id="@+id/nfc_notice2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:textSize="18dp"
        android:textColor="#bbbbbb"
        android:text="with your mobile back"
        android:layout_below="@+id/nfc_notice"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>


text:
package org.stringtemplate.v4.misc;

import org.stringtemplate.v4.Interpreter;
import org.stringtemplate.v4.ModelAdaptor;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
import java.util.Map;

public class MapModelAdaptor implements ModelAdaptor {
    @Override
    public Object getProperty(Interpreter interp, ST self, Object o, Object property, String propertyName) throws STNoSuchPropertyException {
        Object value;
        Map<?, ?> map = (Map<?, ?>)o;
        if ( property==null ) value = map.get(STGroup.DEFAULT_KEY);
        else if ( property.equals("keys") ) value = map.keySet();
        else if ( property.equals("values") ) value = map.values();
        else if ( map.containsKey(property) ) value = map.get(property);
        else if ( map.containsKey(propertyName) ) { // if can't find the key, try toString version
            value = map.get(propertyName);
             }
        else value = map.get(STGroup.DEFAULT_KEY); // not found, use default
        if ( value==STGroup.DICT_KEY ) {
            value = property;
        }
        return value;
    }
}


text:
package com.baidu.oped.apm.rpc;

import com.baidu.oped.apm.rpc.common.SocketStateCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author Taejin Koo
 */
public class LoggingStateChangeEventListener implements StateChangeEventListener<ApmSocket> {

    public static final LoggingStateChangeEventListener INSTANCE = new LoggingStateChangeEventListener();

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void eventPerformed(ApmSocket apmSocket, SocketStateCode stateCode) throws Exception {
        logger.info("eventPerformed socket:{}, stateCode:{}", apmSocket, stateCode);
    }

    @Override
    public void exceptionCaught(ApmSocket apmSocket, SocketStateCode stateCode, Throwable e) {
        logger.warn("exceptionCaught message:{}, socket:{}, stateCode:{}", e.getMessage(), apmSocket, stateCode, e);
    }

}


text:
package alluxio.security;

import alluxio.Configuration;
import alluxio.PropertyKey;
import alluxio.exception.status.UnauthenticatedException;
import alluxio.security.authentication.AuthType;
import alluxio.security.login.AppLoginModule;
import alluxio.security.login.LoginModuleConfiguration;

import java.util.Set;

import javax.annotation.concurrent.ThreadSafe;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

/**
 * A Singleton of LoginUser, which is an instance of {@link alluxio.security.User}. It represents
 * the user of Alluxio client, when connecting to Alluxio service.
 *
 * The implementation of getting a login user supports Windows, Unix, and Kerberos login modules.
 *
 * This singleton uses lazy initialization.
 */
@ThreadSafe
public final class LoginUser {

  /** User instance of the login user in Alluxio client process. */
  private static User sLoginUser;

  private LoginUser() {} // prevent instantiation

  /**
   * Gets current singleton login user. This method is called to identify the singleton user who
   * runs Alluxio client. When Alluxio client gets a user by this method and connects to Alluxio
   * service, this user represents the client and is maintained in service.
   *
   * @return the login user
   */
  public static User get() {
    if (sLoginUser == null) {
      synchronized (LoginUser.class) {
        if (sLoginUser == null) {
          sLoginUser = login();
        }
      }
    }
    return sLoginUser;
  }

  /**
   * Logs in based on the LoginModules.
   *
   * @return the login user
   */
  private static User login() {
    AuthType authType =
        Configuration.getEnum(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.class);
    checkSecurityEnabled(authType);
    Subject subject = new Subject();

    try {
      CallbackHandler callbackHandler = null;
      if (authType.equals(AuthType.SIMPLE) || authType.equals(AuthType.CUSTOM)) {
        callbackHandler = new AppLoginModule.AppCallbackHandler();
      }

      // Create LoginContext based on authType, corresponding LoginModule should be registered
      // under the authType name in LoginModuleConfiguration.
      LoginContext loginContext =
          new LoginContext(authType.getAuthName(), subject, callbackHandler,
              new LoginModuleConfiguration());
      loginContext.login();
    } catch (LoginException e) {
      throw new UnauthenticatedException("Failed to login: " + e.getMessage(), e);
    }

    Set<User> userSet = subject.getPrincipals(User.class);
    if (userSet.isEmpty()) {
      throw new UnauthenticatedException("Failed to login: No Alluxio User is found.");
    }
    if (userSet.size() > 1) {
      StringBuilder msg = new StringBuilder(
          "Failed to login: More than one Alluxio Users are found:");
      for (User user : userSet) {
        msg.append(" ").append(user.toString());
      }
      throw new UnauthenticatedException(msg.toString());
    }
    return userSet.iterator().next();
  }

  /**
   * Checks whether Alluxio is running in secure mode, such as {@link AuthType#SIMPLE},
   * {@link AuthType#KERBEROS}, {@link AuthType#CUSTOM}.
   *
   * @param authType the authentication type in configuration
   */
  private static void checkSecurityEnabled(AuthType authType) {
    // TODO(dong): add Kerberos condition check.
    if (authType != AuthType.SIMPLE && authType != AuthType.CUSTOM) {
      throw new UnsupportedOperationException("User is not supported in " + authType.getAuthName()
          + " mode");
    }
  }
}


text:
require 'test/helper'

class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
  context "validate_attachment_content_type" do
    setup do
      reset_table("dummies") do |d|
        d.string :avatar_file_name
      end
      @dummy_class = reset_class "Dummy"
      @dummy_class.has_attached_file :avatar
      @matcher     = self.class.validate_attachment_content_type(:avatar).
                       allowing(%w(image/png image/jpeg)).
                       rejecting(%w(audio/mp3 application/octet-stream))
    end

    should "reject a class with no validation" do
      assert_rejects @matcher, @dummy_class
    end

    should "reject a class with a validation that doesn't match" do
      @dummy_class.validates_attachment_content_type :avatar, :content_type => %r{audio/.*}
      assert_rejects @matcher, @dummy_class
    end

    should "accept a class with a validation" do
      @dummy_class.validates_attachment_content_type :avatar, :content_type => %r{image/.*}
      assert_accepts @matcher, @dummy_class
    end
  end
end


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.download;

import android.app.DownloadManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;

import org.chromium.base.ContextUtils;
import org.chromium.base.Log;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * A wrapper for Android DownloadManager to provide utility functions.
 */
public class DownloadManagerDelegate {
    private static final String TAG = "DownloadDelegate";
    private static final long INVALID_SYSTEM_DOWNLOAD_ID = -1;
    private static final String DOWNLOAD_ID_MAPPINGS_FILE_NAME = "download_id_mappings";
    private static final Object sLock = new Object();
    protected final Context mContext;

    public DownloadManagerDelegate(Context context) {
        mContext = context;
    }

    /**
     * Inserts a new download ID mapping into the SharedPreferences
     * @param downloadId system download ID from Android DownloadManager.
     * @param downloadGuid Download GUID.
     */
    private void addDownloadIdMapping(long downloadId, String downloadGuid) {
        synchronized (sLock) {
            SharedPreferences sharedPrefs = getSharedPreferences();
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putLong(downloadGuid, downloadId);
            editor.apply();
        }
    }

    /**
     * Removes a download Id mapping from the SharedPreferences given the download GUID.
     * @param guid Download GUID.
     * @return the Android DownloadManager's download ID that is removed, or
     *         INVALID_SYSTEM_DOWNLOAD_ID if it is not found.
     */
    private long removeDownloadIdMapping(String downloadGuid) {
        long downloadId = INVALID_SYSTEM_DOWNLOAD_ID;
        synchronized (sLock) {
            SharedPreferences sharedPrefs = getSharedPreferences();
            downloadId = sharedPrefs.getLong(downloadGuid, INVALID_SYSTEM_DOWNLOAD_ID);
            if (downloadId != INVALID_SYSTEM_DOWNLOAD_ID) {
                SharedPreferences.Editor editor = sharedPrefs.edit();
                editor.remove(downloadGuid);
                editor.apply();
            }
        }
        return downloadId;
    }

    /**
     * Lazily retrieve the SharedPreferences when needed. Since download operations are not very
     * frequent, no need to load all SharedPreference entries into a hashmap in the memory.
     * @return the SharedPreferences instance.
     */
    private SharedPreferences getSharedPreferences() {
        return ContextUtils.getApplicationContext().getSharedPreferences(
                DOWNLOAD_ID_MAPPINGS_FILE_NAME, Context.MODE_PRIVATE);
    }

    /**
     * @see android.app.DownloadManager#addCompletedDownload(String, String, boolean, String,
     * String, long, boolean)
     */
    protected long addCompletedDownload(String fileName, String description, String mimeType,
            String path, long length, String originalUrl, String referer, String downloadGuid) {
        DownloadManager manager =
                (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
        boolean useSystemNotification = !notificationManager.areNotificationsEnabled();
        long downloadId = -1;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            Class<?> c = manager.getClass();
            try {
                Class[] args = {String.class, String.class, boolean.class, String.class,
                        String.class, long.class, boolean.class, Uri.class, Uri.class};
                Method method = c.getMethod("addCompletedDownload", args);
                // OriginalUri has to be null or non-empty.
                Uri originalUri = TextUtils.isEmpty(originalUrl) ? null : Uri.parse(originalUrl);
                Uri refererUri = TextUtils.isEmpty(referer) ? null : Uri.parse(referer);
                downloadId = (Long) method.invoke(manager, fileName, description, true, mimeType,
                        path, length, useSystemNotification, originalUri, refererUri);
            } catch (SecurityException e) {
                Log.e(TAG, "Cannot access the needed method.");
            } catch (NoSuchMethodException e) {
                Log.e(TAG, "Cannot find the needed method.");
            } catch (InvocationTargetException e) {
                Log.e(TAG, "Error calling the needed method.");
            } catch (IllegalAccessException e) {
                Log.e(TAG, "Error accessing the needed method.");
            }
        } else {
            downloadId = manager.addCompletedDownload(fileName, description, true, mimeType, path,
                    length, useSystemNotification);
        }
        addDownloadIdMapping(downloadId, downloadGuid);
        return downloadId;
    }

    /**
     * Removes a download from Android DownloadManager.
     * @param downloadGuid The GUID of the download.
     */
    void removeCompletedDownload(String downloadGuid) {
        long downloadId = removeDownloadIdMapping(downloadGuid);
        if (downloadId != INVALID_SYSTEM_DOWNLOAD_ID) {
            DownloadManager manager =
                    (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            manager.remove(downloadId);
        }
    }

    /**
     * Interface for returning the query result when it completes.
     */
    public interface DownloadQueryCallback {
        /**
         * Callback function to return query result.
         * @param result Query result from android DownloadManager.
         * @param showNotifications Whether to show status notifications.
         */
        public void onQueryCompleted(DownloadQueryResult result, boolean showNotifications);
    }

    /**
     * Result for querying the Android DownloadManager.
     */
    static class DownloadQueryResult {
        public final DownloadItem item;
        public final int downloadStatus;
        public final long downloadTimeInMilliseconds;
        public final long bytesDownloaded;
        public final boolean canResolve;
        public final int failureReason;

        DownloadQueryResult(DownloadItem item, int downloadStatus, long downloadTimeInMilliseconds,
                long bytesDownloaded, boolean canResolve, int failureReason) {
            this.item = item;
            this.downloadStatus = downloadStatus;
            this.downloadTimeInMilliseconds = downloadTimeInMilliseconds;
            this.canResolve = canResolve;
            this.bytesDownloaded = bytesDownloaded;
            this.failureReason = failureReason;
        }
    }

    /**
     * Query the Android DownloadManager for download status.
     * @param downloadItem Download item to query.
     * @param showNotifications Whether to show status notifications.
     * @param callback Callback to be notified when query completes.
     */
    void queryDownloadResult(
            DownloadItem downloadItem, boolean showNotifications, DownloadQueryCallback callback) {
        DownloadQueryTask task = new DownloadQueryTask(downloadItem, showNotifications, callback);
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    /**
     * Async task to query download status from Android DownloadManager
     */
    private class DownloadQueryTask extends AsyncTask<Void, Void, DownloadQueryResult> {
        private final DownloadItem mDownloadItem;
        private final boolean mShowNotifications;
        private final DownloadQueryCallback mCallback;

        public DownloadQueryTask(DownloadItem downloadItem, boolean showNotifications,
                DownloadQueryCallback callback) {
            mDownloadItem = downloadItem;
            mShowNotifications = showNotifications;
            mCallback = callback;
        }

        @Override
        public DownloadQueryResult doInBackground(Void... voids) {
            DownloadManager manager =
                    (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            Cursor c = manager.query(
                    new DownloadManager.Query().setFilterById(mDownloadItem.getSystemDownloadId()));
            if (c == null) {
                return new DownloadQueryResult(mDownloadItem,
                        DownloadManagerService.DOWNLOAD_STATUS_CANCELLED, 0, 0, false, 0);
            }
            long bytesDownloaded = 0;
            boolean canResolve = false;
            int downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_IN_PROGRESS;
            int failureReason = 0;
            long lastModifiedTime = 0;
            if (c.moveToNext()) {
                int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_COMPLETE;
                    if (mShowNotifications) {
                        canResolve = DownloadManagerService.isOMADownloadDescription(
                                mDownloadItem.getDownloadInfo())
                                || DownloadManagerService.canResolveDownloadItem(
                                        mContext, mDownloadItem, false);
                    }
                } else if (status == DownloadManager.STATUS_FAILED) {
                    downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_FAILED;
                    failureReason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                }
                lastModifiedTime =
                        c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));
                bytesDownloaded =
                        c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            } else {
                downloadStatus = DownloadManagerService.DOWNLOAD_STATUS_CANCELLED;
            }
            c.close();
            long totalTime = Math.max(0, lastModifiedTime - mDownloadItem.getStartTime());
            return new DownloadQueryResult(mDownloadItem, downloadStatus, totalTime,
                    bytesDownloaded, canResolve, failureReason);
        }

        @Override
        protected void onPostExecute(DownloadQueryResult result) {
            mCallback.onQueryCompleted(result, mShowNotifications);
        }
    }

    static Uri getContentUriFromDownloadManager(Context context, long downloadId) {
        DownloadManager manager =
                (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri contentUri = null;
        try {
            contentUri = manager.getUriForDownloadedFile(downloadId);
        } catch (SecurityException e) {
            Log.e(TAG, "unable to get content URI from DownloadManager");
        }
        return contentUri;
    }
}


text:
import { ValidationModel } from './index';

describe('ValidationModel', () => {
  it('presence', function() {
    class TestModelPresence extends ValidationModel {
      property: number;
      constructor(property? :number) {
        super();
        this.property = property;
      }
    }
    TestModelPresence.validates('property', { presence: true });
    let testModel = new TestModelPresence();
    expect(testModel.isValid).toEqual(false);
    expect(testModel.errors[0]['property']).toEqual({ blank: "can't be blank" });
    expect(testModel.errors.messages[0]).toEqual("Property can't be blank");
  });

  it('greatherThan', function() {
    class TestModeGreaterThan extends ValidationModel {
      property: number;
      constructor(property? :number) {
        super();
        this.property = property;
      }
    }
    TestModeGreaterThan.validates('property', { greaterThan: 2 });
    let testModel = new TestModeGreaterThan(2);
    expect(testModel.isValid).toEqual(false);
    expect(testModel.errors[0]['property']).toEqual({ greaterThan: "must be greater than 2" });
    expect(testModel.errors.messages[0]).toEqual("Property must be greater than 2");
  });

  it('greatherThan function', function() {
    class TestModeGreaterThanFunc extends ValidationModel {
      property: number;
      a: number = 1;
      b: number = 2;
      constructor(property? :number) {
        super();
        this.property = property;
      }
    }
    TestModeGreaterThanFunc.validates('property', { greaterThan: (self)=> { return self.a + self.b; } });
    let testModel = new TestModeGreaterThanFunc(-1);
    expect(testModel.isValid).toEqual(false);
    expect(testModel.errors[0]['property']).toEqual({ greaterThan: 'must be greater than 3' });
    expect(testModel.errors.messages[0]).toEqual("Property must be greater than 3");
  });

  it('greatherThanOrequalTo', function() {
    class TestModeGreaterThanOrEqualTo extends ValidationModel {
      property: number;
      constructor(property? :number) {
        super();
        this.property = property;
      }
      get getter() {
        return this.property;
      }
    }
    TestModeGreaterThanOrEqualTo.validates('getter', { greaterThanOrEqualTo: 2 });
    let testModel = new TestModeGreaterThanOrEqualTo(-1);
    expect(testModel.isValid).toEqual(false);
    expect(testModel.errors[0]['getter']).toEqual({ greaterThanOrEqualTo: 'must be greater than or equal to 2' });
    expect(testModel.errors.messages[0]).toEqual("Getter must be greater than or equal to 2");
  });
});


text:
#include "config.h"

#if ENABLE(SVG) && ENABLE(FILTERS)
#include "SVGFEOffsetElement.h"

#include "Attribute.h"
#include "FilterEffect.h"
#include "SVGFilterBuilder.h"
#include "SVGNames.h"

namespace WebCore {

// Animated property definitions
DEFINE_ANIMATED_STRING(SVGFEOffsetElement, SVGNames::inAttr, In1, in1)
DEFINE_ANIMATED_NUMBER(SVGFEOffsetElement, SVGNames::dxAttr, Dx, dx)
DEFINE_ANIMATED_NUMBER(SVGFEOffsetElement, SVGNames::dyAttr, Dy, dy)

inline SVGFEOffsetElement::SVGFEOffsetElement(const QualifiedName& tagName, Document* document)
    : SVGFilterPrimitiveStandardAttributes(tagName, document)
{
}

PassRefPtr<SVGFEOffsetElement> SVGFEOffsetElement::create(const QualifiedName& tagName, Document* document)
{
    return adoptRef(new SVGFEOffsetElement(tagName, document));
}

void SVGFEOffsetElement::parseMappedAttribute(Attribute* attr)
{
    const String& value = attr->value();
    if (attr->name() == SVGNames::dxAttr)
        setDxBaseValue(value.toFloat());
    else if (attr->name() == SVGNames::dyAttr)
        setDyBaseValue(value.toFloat());
    else if (attr->name() == SVGNames::inAttr)
        setIn1BaseValue(value);
    else
        SVGFilterPrimitiveStandardAttributes::parseMappedAttribute(attr);
}

void SVGFEOffsetElement::svgAttributeChanged(const QualifiedName& attrName)
{
    SVGFilterPrimitiveStandardAttributes::svgAttributeChanged(attrName);

    if (attrName == SVGNames::inAttr
        || attrName == SVGNames::dxAttr
        || attrName == SVGNames::dyAttr)
        invalidate();
}

void SVGFEOffsetElement::synchronizeProperty(const QualifiedName& attrName)
{
    SVGFilterPrimitiveStandardAttributes::synchronizeProperty(attrName);

    if (attrName == anyQName()) {
        synchronizeDx();
        synchronizeDy();
        synchronizeIn1();
        return;
    }

    if (attrName == SVGNames::dxAttr)
        synchronizeDx();
    else if (attrName == SVGNames::dyAttr)
        synchronizeDy();
    else if (attrName == SVGNames::inAttr)
        synchronizeIn1();
}

AttributeToPropertyTypeMap& SVGFEOffsetElement::attributeToPropertyTypeMap()
{
    DEFINE_STATIC_LOCAL(AttributeToPropertyTypeMap, s_attributeToPropertyTypeMap, ());
    return s_attributeToPropertyTypeMap;
}

void SVGFEOffsetElement::fillAttributeToPropertyTypeMap()
{
    AttributeToPropertyTypeMap& attributeToPropertyTypeMap = this->attributeToPropertyTypeMap();

    SVGFilterPrimitiveStandardAttributes::fillPassedAttributeToPropertyTypeMap(attributeToPropertyTypeMap);
    attributeToPropertyTypeMap.set(SVGNames::inAttr, AnimatedString);
    attributeToPropertyTypeMap.set(SVGNames::dxAttr, AnimatedNumber);
    attributeToPropertyTypeMap.set(SVGNames::dyAttr, AnimatedNumber);
}

PassRefPtr<FilterEffect> SVGFEOffsetElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
{
    FilterEffect* input1 = filterBuilder->getEffectById(in1());

    if (!input1)
        return 0;

    RefPtr<FilterEffect> effect = FEOffset::create(filter, dx(), dy());
    effect->inputEffects().append(input1);
    return effect.release();
}

}

#endif // ENABLE(SVG)


text:
#ifndef _BITLIB2_SERIALIZE_HPP_
#define _BITLIB2_SERIALIZE_HPP_

#include "bitlib2.hpp"

namespace bitlib2 {
namespace serialize {

    /**
     * Simple stream serializer.
     */
    class StreamSerializer : public ISerializer
    {
        public:
            enum {
                SEGMENTTYPE_START = 0,
                SEGMENTTYPE_INVERTED = 1,
                SEGMENTTYPE_EMPTYBLOCK_32BIT = 2, // 32 bit length
                SEGMENTTYPE_BLOCK_32BIT = 3, // 32 bit length
                SEGMENTTYPE_END = 255,
            };

            /**
             * Constructor.
             * @param stream Output stream.
             */
            StreamSerializer(std::ostream& stream) :
                outputStream(stream)
            {
            }

            /**
             * Start serialization.
             */
            virtual void start() {
                const byte data = SEGMENTTYPE_START;
                this->outputStream.write(reinterpret_cast<const char*>(&data), 1);
            }

            /**
             * End serialization.
             */
            virtual void end() {
                const byte data = SEGMENTTYPE_END;
                this->outputStream.write(reinterpret_cast<const char*>(&data), 1);
            }

            /**
             * Check whether something failed during serialization upto now.
             * @return Failure (true) or no failure (false).
             */
            virtual bool failed() const {
                return this->outputStream.fail();
            }

            /**
             * Set the inverted flag on or off.
             * @param inverted Inverted (true) or not inverted (false).
             */
            virtual void setInverted(bool inverted) {
                byte data[2] = { SEGMENTTYPE_INVERTED };
                data[1] = inverted ? 1 : 0;
                this->outputStream.write(reinterpret_cast<const char*>(data), 2);
            }

            /**
             * Add bytes.
             * @param bitData Byte data buffer.
             * @param bytesCount Number of bytes in the data buffer.
             * @param onBitCount Number of 'ON' bits in the buffer.
             */
            virtual void addBytes(const byte* bitData, std::size_t bytesCount, std::size_t onBitCount) {
                byte data[5] = { SEGMENTTYPE_BLOCK_32BIT };
                writeIntToByteBuffer(bytesCount, &data[1]);
                this->outputStream.write(reinterpret_cast<const char*>(data), 5);
                this->outputStream.write(reinterpret_cast<const char*>(bitData), bytesCount);
            }

            /**
             * Add empty bytes.
             * @param bytesCount Number of empty bytes.
             */
            virtual void addEmptyBytes(std::size_t bytesCount) {
                byte data[5] = { SEGMENTTYPE_EMPTYBLOCK_32BIT };
                writeIntToByteBuffer(bytesCount, &data[1]);
                this->outputStream.write(reinterpret_cast<const char*>(data), 5);
            }

            /**
             * Write a 32 bit integer to a byte array.
             * @param n Integer.
             * @param buf Data buffer.
             */
            template <typename IntType> static void writeIntToByteBuffer(const IntType& n, byte* buf) {
                for (int bitOffset = 0; bitOffset < 32; bitOffset += 8) {
                    *(buf++) = (n >> bitOffset) & 0xFF;
                }
            }

        private:
            std::ostream& outputStream;
    };

    /**
     * Simple stream deserializer. Corresponds to StreamSerializer.
     */
    class StreamDeserializer : public IDeserializer
    {
        public:
            /**
             * Constructor.
             * @param stream Input stream.
             */
            StreamDeserializer(std::istream& stream) :
                inputStream(stream),
                fail(false),
                inverted(false),
                currentSegmentType(StreamSerializer::SEGMENTTYPE_START),
                currentSegmentDataLeft(0)
            {
            }

            /**
             * Start deserialization.
             */
            virtual void start() {
                this->fail = false;
                this->inverted = false;
                this->readFromInput(&this->currentSegmentType, 1);
                if (this->currentSegmentType != StreamSerializer::SEGMENTTYPE_START) {
                    this->fail = true;
                    this->currentSegmentType = StreamSerializer::SEGMENTTYPE_END;
                }
            }

            /**
             * Check whether something failed during deserialization upto now.
             * @return Failure (true) or no failure (false).
             */
            virtual bool failed() const {
                return this->fail || this->inputStream.fail();
            }

            /**
             * Return whether deserialization data is finished (or failed).
             * @return Finished (true) or not (false).
             */
            virtual bool finished() const {
                return this->currentSegmentType == StreamSerializer::SEGMENTTYPE_END;
            }

            /**
             * Check whether the inverted flag is set.
             * Note: This information is only available once the (optional)
             * inversion segment is read or the deserialization has finished.
             * @return Inverted (true) or not inverted (false).
             */
            virtual bool isInverted() {
                return this->inverted;
            }

            /**
             * Deserialize bits into a byte block buffer.
             * @param data Data buffer.
             * @param bytesCount Size of data buffer.
             * @param empty Set to true if an empty block is retrieved.
             * @return Data has been read (true) or no data is read (false).
             */
            virtual bool getBytes(byte* data, std::size_t bytesCount, bool& empty) {
                bool isDataRead = false;
                empty = true;
                while (bytesCount > 0 && this->currentSegmentType != StreamSerializer::SEGMENTTYPE_END) {
                    switch (this->currentSegmentType) {
                        case StreamSerializer::SEGMENTTYPE_EMPTYBLOCK_32BIT:
                            if (this->currentSegmentDataLeft > bytesCount) {
                                this->currentSegmentDataLeft -= bytesCount;
                                return true;
                            }
                            else if (this->currentSegmentDataLeft > 0) {
                                data += this->currentSegmentDataLeft;
                                bytesCount -= this->currentSegmentDataLeft;
                                isDataRead = true;
                            }
                            break;

                        case StreamSerializer::SEGMENTTYPE_BLOCK_32BIT:
                            if (this->currentSegmentDataLeft > bytesCount) {
                                this->readFromInput(data, bytesCount);
                                this->currentSegmentDataLeft -= bytesCount;
                                empty = false;
                                return true;
                            }
                            else if (this->currentSegmentDataLeft > 0) {
                                this->readFromInput(data, this->currentSegmentDataLeft);
                                data += this->currentSegmentDataLeft;
                                bytesCount -= this->currentSegmentDataLeft;
                                empty = false;
                                isDataRead = true;
                            }
                            break;

                        default:
                            break;
                    }

                    this->readSegmentHead();
                }
                return isDataRead;
            }

            /**
             * Read a 32 bit integer from a byte array.
             * @param n Integer.
             * @param buf Data buffer.
             */
            template <typename IntType> static void readIntFromByteBuffer(IntType& n, const byte* buf) {
                n = 0;
                for (int bitOffset = 0; bitOffset < 32; bitOffset += 8) {
                    n |= static_cast<IntType>(*(buf++)) << bitOffset;
                }
            }

        private:
            void readSegmentHead() {
                byte buf[4];
                this->readFromInput(&this->currentSegmentType, 1);
                switch (this->currentSegmentType) {
                    case StreamSerializer::SEGMENTTYPE_INVERTED:
                        this->readFromInput(buf, 1);
                        this->inverted = buf[0] != 0;
                        break;

                    case StreamSerializer::SEGMENTTYPE_EMPTYBLOCK_32BIT:
                    case StreamSerializer::SEGMENTTYPE_BLOCK_32BIT:
                        this->readFromInput(buf, 4);
                        readIntFromByteBuffer(this->currentSegmentDataLeft, buf);
                        break;

                    case StreamSerializer::SEGMENTTYPE_END:
                        break;

                    default:
                        this->fail = true;
                        this->currentSegmentType = StreamSerializer::SEGMENTTYPE_END;
                }
            }

            /**
             * Read data from input.
             * @param buf Data buffer pointer.
             * @param size Number of bytes to read.
             */
            void readFromInput(void* const buf, const std::size_t size) {
                char* const charbuf = reinterpret_cast<char*>(buf);
                this->inputStream.read(charbuf, size);
            }

        private:
            std::istream& inputStream;
            bool fail;
            bool inverted;
            byte currentSegmentType;
            std::size_t currentSegmentDataLeft;
    };

} // namespace serialize
} // namespace bitlib2

#endif // _BITLIB2_SERIALIZE_HPP_


text:
using System.Windows.Controls;

namespace vsgerrit.Features.ChangeBrowser
{
    public partial class ChangeBrowserControl : UserControl
    {
        public ChangeBrowserControl()
        {
            InitializeComponent();
        }
    }
}


text:
package org.iotp.server.actors.rule;

public class ComplexRuleActorChain implements RuleActorChain {

  private final RuleActorChain systemChain;
  private final RuleActorChain tenantChain;

  public ComplexRuleActorChain(RuleActorChain systemChain, RuleActorChain tenantChain) {
    super();
    this.systemChain = systemChain;
    this.tenantChain = tenantChain;
  }

  @Override
  public int size() {
    return systemChain.size() + tenantChain.size();
  }

  @Override
  public RuleActorMetaData getRuleActorMd(int index) {
    if (index < systemChain.size()) {
      return systemChain.getRuleActorMd(index);
    } else {
      return tenantChain.getRuleActorMd(index - systemChain.size());
    }
  }

}


text:
package regex;

public class DirectedDFS {
    private boolean[] marked; // marked[v] = true if v is reachable
    // from source (or sources)

    // single-source reachability
    public DirectedDFS(Digraph G, int s) {
        marked = new boolean[G.V()];
        dfs(G, s);
    }

    // multiple-source reachability
    public DirectedDFS(Digraph G, Iterable<Integer> sources) {
        marked = new boolean[G.V()];
        for (int v : sources)
            dfs(G, v);
    }

    private void dfs(Digraph G, int v) {
        marked[v] = true;
        for (int w : G.adj(v)) {
            if (!marked[w])
                dfs(G, w);
        }
    }

    // is there a directed path from the source (or sources) to v?
    public boolean marked(int v) {
        return marked[v];
    }

    // test client
    public static void main(String[] args) {

        // read in digraph from command-line argument
    /*
	 * In in = new In(args[0]); Digraph G = new Digraph(in);
	 *
	 * // read in sources from command-line arguments Bag<Integer> sources =
	 * new Bag<Integer>(); for (int i = 1; i < args.length; i++) { int s =
	 * Integer.parseInt(args[i]); sources.add(s); }
	 *
	 * // multiple-source reachability DirectedDFS dfs = new DirectedDFS(G,
	 * sources);
	 *
	 * // print out vertices reachable from sources for (int v = 0; v <
	 * G.V(); v++) { if (dfs.marked(v)) StdOut.print(v + " "); }
	 * StdOut.println();
	 */
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project
  xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
    http://maven.apache.org/POM/4.0.0
    https://maven.apache.org/maven-v4_0_0.xsd
  "
>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>ca.bc.gov.open.cpf</groupId>
    <artifactId>cpf-parent</artifactId>
    <version>6.1.x-SNAPSHOT</version>
    <relativePath>../../pom.xml</relativePath>
  </parent>
  <groupId>ca.bc.gov.open.cpf.plugins</groupId>
  <artifactId>mandelbrot</artifactId>
  <name>Mandelbrot Plug-in</name>
  <description>Mandelbrot Plug-in</description>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>ca.bc.gov.open.cpf</groupId>
      <artifactId>cpf-api-plugin</artifactId>
      <version>${project.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
</project>


text:
import { Injectable } from '@angular/core';

import { HEROES } from '../stuff/mock-heroes';
import { Hero } from '../interfaces/hero';

@Injectable()
export class HeroServiceService {

  getHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  }

  getHeroesSlowly(): Promise<Hero[]> {
  return new Promise(resolve => {
    // Simulate server latency with 2 second delay
    setTimeout(() => resolve(this.getHeroes()), 2000);
  });
}

}