text:
namespace testing {
namespace crunchy_status {
namespace internal_crunchy_status {

inline const ::crunchy::Status& GetStatus(const ::crunchy::Status& status) {
  return status;
}

template <typename T>
const ::crunchy::Status& GetStatus(const ::crunchy::StatusOr<T>& status) {
  return status.status();
}

////////////////////////////////////////////////////////////
// Implementation of IsOkAndHolds().

// Monomorphic implementation of matcher IsOkAndHolds(m).  StatusOrType can be
// either StatusOr<T> or a reference to it.
template <typename StatusOrType>
class IsOkAndHoldsMatcherImpl : public MatcherInterface<StatusOrType> {
 public:
  typedef typename std::remove_reference<StatusOrType>::type::element_type
      value_type;

  template <typename InnerMatcher>
  explicit IsOkAndHoldsMatcherImpl(InnerMatcher&& inner_matcher)
      : inner_matcher_(SafeMatcherCast<const value_type&>(
            std::forward<InnerMatcher>(inner_matcher))) {}

  void DescribeTo(std::ostream* os) const override {
    *os << "is OK and has a value that ";
    inner_matcher_.DescribeTo(os);
  }

  void DescribeNegationTo(std::ostream* os) const override {
    *os << "isn't OK or has a value that ";
    inner_matcher_.DescribeNegationTo(os);
  }

  bool MatchAndExplain(StatusOrType actual_value,
                       MatchResultListener* result_listener) const override {
    if (!actual_value.ok()) {
      *result_listener << "which has status " << actual_value.status();
      return false;
    }

    StringMatchResultListener inner_listener;
    const bool matches = inner_matcher_.MatchAndExplain(
        actual_value.ValueOrDie(), &inner_listener);
    const std::string inner_explanation = inner_listener.str();
    if (inner_explanation != "") {
      *result_listener << "which contains value "
                       << PrintToString(actual_value.ValueOrDie()) << ", "
                       << inner_explanation;
    }
    return matches;
  }

 private:
  const Matcher<const value_type&> inner_matcher_;
};

// Implements IsOkAndHolds(m) as a polymorphic matcher.
template <typename InnerMatcher>
class IsOkAndHoldsMatcher {
 public:
  explicit IsOkAndHoldsMatcher(InnerMatcher inner_matcher)
      : inner_matcher_(std::move(inner_matcher)) {}

  // Converts this polymorphic matcher to a monomorphic matcher of the
  // given type.  StatusOrType can be either StatusOr<T> or a
  // reference to StatusOr<T>.
  template <typename StatusOrType>
  operator Matcher<StatusOrType>() const {
    return MakeMatcher(
        new IsOkAndHoldsMatcherImpl<StatusOrType>(inner_matcher_));
  }

 private:
  const InnerMatcher inner_matcher_;
};

////////////////////////////////////////////////////////////
// Implementation of StatusIs().

inline Matcher<int> ToCodeMatcher(const Matcher<int>& m) { return m; }

// StatusIs() is a polymorphic matcher.  This class is the common
// implementation of it shared by all types T where StatusIs() can be
// used as a Matcher<T>.
class StatusIsMatcherCommonImpl {
 public:
  StatusIsMatcherCommonImpl(Matcher<int> code_matcher,
                            Matcher<const std::string&> message_matcher)
      : code_matcher_(std::move(code_matcher)),
        message_matcher_(std::move(message_matcher)) {}

  void DescribeTo(std::ostream* os) const;

  void DescribeNegationTo(std::ostream* os) const;

  bool MatchAndExplain(const ::crunchy::Status& status,
                       MatchResultListener* result_listener) const;

 private:
  const Matcher<int> code_matcher_;
  const Matcher<const std::string&> message_matcher_;
};

// Monomorphic implementation of matcher StatusIs() for a given type
// T.  T can be Status, StatusOr<>, or a reference to either of them.
template <typename T>
class MonoStatusIsMatcherImpl : public MatcherInterface<T> {
 public:
  explicit MonoStatusIsMatcherImpl(StatusIsMatcherCommonImpl common_impl)
      : common_impl_(std::move(common_impl)) {}

  void DescribeTo(std::ostream* os) const override {
    common_impl_.DescribeTo(os);
  }

  void DescribeNegationTo(std::ostream* os) const override {
    common_impl_.DescribeNegationTo(os);
  }

  bool MatchAndExplain(T actual_value,
                       MatchResultListener* result_listener) const override {
    return common_impl_.MatchAndExplain(GetStatus(actual_value),
                                        result_listener);
  }

 private:
  StatusIsMatcherCommonImpl common_impl_;
};

// Implements StatusIs() as a polymorphic matcher.
class StatusIsMatcher {
 public:
  template <typename StatusCodeMatcher>
  StatusIsMatcher(StatusCodeMatcher&& code_matcher,
                  Matcher<const std::string&> message_matcher)
      : common_impl_(
            ToCodeMatcher(std::forward<StatusCodeMatcher>(code_matcher)),
            std::move(message_matcher)) {}

  // Converts this polymorphic matcher to a monomorphic matcher of the
  // given type.  T can be StatusOr<>, Status, or a reference to
  // either of them.
  template <typename T>
  operator Matcher<T>() const {
    return MakeMatcher(new MonoStatusIsMatcherImpl<T>(common_impl_));
  }

 private:
  const StatusIsMatcherCommonImpl common_impl_;
};

// Monomorphic implementation of matcher IsOk() for a given type T.
// T can be Status, StatusOr<>, or a reference to either of them.
template <typename T>
class MonoIsOkMatcherImpl : public MatcherInterface<T> {
 public:
  void DescribeTo(std::ostream* os) const override { *os << "is OK"; }
  void DescribeNegationTo(std::ostream* os) const override {
    *os << "is not OK";
  }
  bool MatchAndExplain(T actual_value, MatchResultListener*) const override {
    return GetStatus(actual_value).ok();
  }
};

// Implements IsOk() as a polymorphic matcher.
class IsOkMatcher {
 public:
  template <typename T>
  operator Matcher<T>() const {  // NOLINT
    return MakeMatcher(new MonoIsOkMatcherImpl<T>());
  }
};

}  // namespace internal_crunchy_status

// Macros for testing the results of functions that return crunchy::Status or
// crunchy::StatusOr<T> (for any type T).
#define CRUNCHY_EXPECT_OK(expression) \
  EXPECT_THAT(expression, ::testing::crunchy_status::IsOk())
#define CRUNCHY_ASSERT_OK(expression) \
  ASSERT_THAT(expression, ::testing::crunchy_status::IsOk())
#define CRUNCHY_CHECK_OK(expression) \
  CRUNCHY_CHECK_EQ(expression, crunchy::OkStatus())

// Returns a gMock matcher that matches a StatusOr<> whose status is
// OK and whose value matches the inner matcher.
template <typename InnerMatcher>
internal_crunchy_status::IsOkAndHoldsMatcher<
    typename std::decay<InnerMatcher>::type>
IsOkAndHolds(InnerMatcher&& inner_matcher) {
  return internal_crunchy_status::IsOkAndHoldsMatcher<
      typename std::decay<InnerMatcher>::type>(
      std::forward<InnerMatcher>(inner_matcher));
}

// Returns a gMock matcher that matches a Status or StatusOr<>  whose status
// code matches code_matcher, and whose error message matches message_matcher.
template <typename StatusCodeMatcher>
internal_crunchy_status::StatusIsMatcher StatusIs(
    StatusCodeMatcher&& code_matcher, Matcher<const std::string&> message_matcher) {
  return internal_crunchy_status::StatusIsMatcher(
      std::forward<StatusCodeMatcher>(code_matcher),
      std::move(message_matcher));
}

// Returns a gMock matcher that matches a Status or StatusOr<> whose status code
// matches code_matcher.
template <typename StatusCodeMatcher>
internal_crunchy_status::StatusIsMatcher StatusIs(
    StatusCodeMatcher&& code_matcher) {
  return StatusIs(std::forward<StatusCodeMatcher>(code_matcher), _);
}

// Returns a gMock matcher that matches a Status or StatusOr<> which is OK.
inline internal_crunchy_status::IsOkMatcher IsOk() {
  return internal_crunchy_status::IsOkMatcher();
}

}  // namespace crunchy_status
}  // namespace testing

#endif  // CRUNCHY_INTERNAL_COMMON_STATUS_MATCHERS_H_


text:
NSUInteger CDMNumericConvolve(double *values, NSUInteger valuesSize,
                              const double kernel[], NSUInteger kernelSize) {
  if (valuesSize < kernelSize) {
    return valuesSize;
  }

  NSUInteger n = valuesSize - kernelSize;

  for (NSUInteger i = 0; i < n; i++) {
    double accumulator = 0.0;

    for (NSUInteger j = 0; j < kernelSize; j++) {
      accumulator += values[i + j] * kernel[kernelSize - j - 1];
    }
    values[i] = accumulator;
  }
  return n;
}

NSUInteger CDMNumericCorrelate(double *values, NSUInteger valuesSize,
                               const double kernel[], NSUInteger kernelSize) {
  if (valuesSize < kernelSize) {
    return valuesSize;
  }

  NSUInteger n = valuesSize - kernelSize;

  for (NSUInteger i = 0; i < n; i++) {
    double accumulator = 0.0;

    for (NSUInteger j = 0; j < kernelSize; j++) {
      accumulator += values[i + j] * kernel[j];
    }
    values[i] = accumulator;
  }
  return n;
}

NSUInteger CDMNumericDiff(double *values, NSUInteger valuesSize) {
  for (NSUInteger i = 0; i < valuesSize - 1; i++) {
    values[i] = values[i + 1] - values[i];
  }
  return valuesSize - 1;
}

NSUInteger CDMNumericFilterZero(double *values, NSUInteger valuesSize) {
  NSUInteger numberOfZeros = 0;

  for (NSUInteger i = 0; i < valuesSize; i++) {
    if (values[i] != 0.0) {
      if (numberOfZeros > 0) {
        values[i - numberOfZeros] = values[i];
      }
    } else {
      numberOfZeros++;
    }
  }
  return valuesSize - numberOfZeros;
}

double CDMNumericMax(double *values, NSUInteger valuesSize) {
  if (valuesSize == 0) {
    return 0.0;
  }

  double maxValue = values[0];
  for (NSUInteger i = 1; i < valuesSize; i++) {
    if (maxValue < values[i]) {
      maxValue = values[i];
    }
  }
  return maxValue;
}

double CDMNumericMin(double *values, NSUInteger valuesSize) {
  if (valuesSize == 0) {
    return 0.0;
  }

  double minValue = values[0];
  for (NSUInteger i = 1; i < valuesSize; i++) {
    if (minValue > values[i]) {
      minValue = values[i];
    }
  }
  return minValue;
}

void CDMNumericMap(double *values, NSUInteger valuesSize, double (^block)(double)) {
  for (NSUInteger i = 0; i < valuesSize; i++) {
    values[i] = block(values[i]);
  }
}

NSArray *CDMNumericArrayFromRange(NSRange range) {
  NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:range.length];

  for (NSUInteger i = 0; i < range.length; i++) {
    [result addObject:[NSNumber numberWithDouble:(double) (range.location + i)]];
  }
  return result;
}

redpajama_set_name: RedPajamaGithub


text:
![Travis Build Status](https://travis-ci.org/code-for-nashville/oss-intro-class.svg?branch=master)

# Calculator
An example open source project that implements calculator functions (add, subtract, multiply, divide) in different
languages.

## Usage
Each langague is located in it's own folder. Right now we support these languages:

* Python - [Python folder](python)
* Node.js - [Node folder](node)

Each language should implement a calculator that can `add`, `subtract`, `multiply`, and `divide`.

For installation and testing instructions, see the README in each language folder.

## Contributing
See our guidelines in [CONTRIBUTING.md](CONTRIBUTING.md)

## OSS Intro Class
### Goals
Students should feel comfortable and confident making small contributions to open source projects. This includes
identifying issues, not doing work on issues that have already been claimed, participate in project chat channels (Slack, gitter, Discord, etc.), and filing pull requests with tests, and any necessary documentation updates.

### Outcomes
Students should be able to
* find a project they are interested in
* find issues they can tackle, communicate their interest, and file a pull request that solves the issue
* file an effective bug report
* understand what makes a good commit message
* these people make it all for free, so be patient and appreciate the work

### Resources
* [Diving Into Other People's Code](http://www.lihaoyi.com/post/DivingIntoOtherPeoplesCode.html)
* [Github Contributing to Open Source Guide](https://guides.github.com/activities/contributing-to-open-source/)

## License
[MIT](LICENSE.md)


text:
'''
Stpl2
=====
Please note only stuff exposed though __init__ module is considered public API

'''

import re
import sys
import zlib
import collections
import os
import os.path
import functools

# Py3k fixes
py3k = sys.version > '3'
if py3k:
    import builtins
    import html
    xrange = range
    iteritems = dict.items
    itervalues = dict.values
    unicode_prefix = ''
    base_notfounderror = FileNotFoundError
    yield_from_supported = sys.version_info.minor > 2
    maxint = sys.maxsize
    native_string_bases = (str,)
    tostr_safe = str

    def escape_html_safe(data):
        '''
        Parse given data to string and apply escape_html

        :param obj: any python object
        :return str: escaped html string
        '''
        return html.escape('%s' % data)
else:
    import __builtin__ as builtins
    import cgi
    iteritems = dict.iteritems
    itervalues = dict.itervalues
    unicode_prefix = 'u'
    base_notfounderror = IOError
    yield_from_supported = False
    maxint = sys.maxint
    native_string_bases = (basestring,)

    def tostr_safe(data):
        return '%s' % data

    def escape_html_safe(data):
        '''
        Parse given data to string and apply escape_html

        :param obj: any python object
        :return str: escaped html string
        '''
        return cgi.escape('%s' % data, quote=True).replace("'", "'")

class TemplateSyntaxError(SyntaxError):
    pass

class TemplateContextError(ValueError):
    pass

class TemplateNotFoundError(base_notfounderror):
    pass

class TemplateValueError(ValueError):
    pass

class TemplateRuntimeError(RuntimeError):
    def __init__(self, error, code=None, lineno=None, pycode=None, pylineno=None):
        self.error = error
        self.code = code
        self.lineno = lineno
        self.pycode = pycode
        self.pylineno = pylineno

        context = []
        if code:
            cstart = max(lineno-5, 0)
            context.extend("    %s" % line for line in code[cstart:lineno-1])
            context.append(">>> %s" % code[lineno-1])
            context.extend("    %s" % line for line in code[lineno:lineno+3])
            message = "in line %d:" % lineno
        elif pycode:
            cstart = max(pylineno-4, 0)
            context.extend("    %s" % line for line in pycode[cstart:pylineno])
            context.append(">>> %s" % pycode[pylineno])
            context.extend("    %s" % line for line in pycode[pylineno+1:pylineno+4])
            message = "in unknown line. Generated code was:\n"
        else:
            message = "in unknown line"

        error_name = type(error).__name__
        error_message = str(error)

        # Error message unification
        if error_message.endswith("."):
            message = message.capitalize()
        elif error_message.strip()[-1].isalnum():
            message = ", %s" % message
        elif not error_message.endswith(" "):
            message = " %s" % message

        error = "%s: %s%s" % (error_name, error_message, message)
        if context:
            error = "%s\n%s" % (error, "\n".join(context))
        RuntimeError.__init__(self, error)

class CodeTranslator(object):
    '''
    Translate from SimpleTemplate Engine 2 syntax to Python code.
    '''
    syntax_error_class = TemplateSyntaxError
    value_error_class = TemplateValueError

    tab = "    "
    linesep = "\n"
    literal_open = "<%"
    literal_close = "%>"
    variable_open = "{{"
    variable_close = "}}"
    code_line_prefix = "%"

    indent_tokens = ("class", "def", "with", "if", "for", "while")
    redent_tokens = ("else", "elif", "except", "finally")
    custom_tokens = ("block", "block.super", "end", "extends", "include", "rebase", "base")

    def __init__(self):
        # compile regexps
        indent = r"((?P<indent>(%s))(?!\w))" % "|".join(re.escape(i) for i in self.indent_tokens)
        redent = r"((?P<redent>(%s))(?!\w))" % "|".join(re.escape(i) for i in self.redent_tokens)
        custom = r"((?P<custom>(%s))(?!\w)\s*(?P<params>((\s+.*)|(\(.*\)))\s*)?$)" % "|".join(re.escape(i) for i in self.custom_tokens)

        redict = {
            'string': r"(\'((\\.)|[^\'])*?\')|(\"((\\.)|[^\"])*?\")", # massive nongreedy string and escape sensitive dotall regexp
            'var_open': re.escape(self.variable_open),
            'var_close': re.escape(self.variable_close),
        }

        # regexp precompilation
        self.re_tokens = re.compile("^(%s)" % "|".join((indent, redent, custom)))
        self.re_var = re.compile("(%(var_open)s(?P<var>(%(string)s|.)*?)%(var_close)s)|(?P<escape>%%)" % redict)
        self.re_inline = re.compile("(\{(%(string)s)\}|(%(string)s)|.)*?:(?P<inline>.*)" % redict)

        self.code_line_prefix_length = len(self.code_line_prefix)

    @classmethod
    def param_split(cls, params, seps, valuesep, strip, quote='\'"',
                    must_quote=False, escape='\\', free_escape=False,
                    maxnum=maxint):
        '''
        Split a param string based on rules and return a  tuple with arguments,
        keyword arguments and unparsed data (see `maxnum` argument).

        :param string params: param string
        :param iterable seps: field separators
        :param iterable valuesep: key-value separator for keyword fields
        :param iterable strip: characters to strip outside quotes
        :param iterable quote: quote characters
        :param iterable escape: escape characters
        :param bool free_escape: wether allow escapes outside quoted values
        :param int maxnum: number of arguments will be parsed (default is all)
        :returns tuple: tuple with arguments list, keyword arguments dict and unparsed string.
        '''
        args = [[]]
        kwargs = {}
        quoted = None
        escaped = False
        key = None
        for p, char in enumerate(params):
            if escaped:
                escaped = False
                (kwargs[key] if key else args[-1]).append(char)
            elif char in escape and free_escape:
                escaped = True
            elif quoted:
                if char in escape:
                    escaped = True
                elif char == quoted:
                    quoted = None
                else:
                    (kwargs[key] if key else args[-1]).append(char)
            elif char in valuesep and not key:
                key = "".join(args.pop())
                kwargs[key] = []
            elif char in quote:
                quoted = char
            elif char in seps and (args[-1] or key):
                if len(args) + len(kwargs) < maxnum:
                    key = None
                    args.append([])
                else:
                    break
            elif not char in strip:
                (kwargs[key] if key else args[-1]).append(char)

        # strip
        extra = params[p+1:]
        for i in strip:
            extra = extra.strip(i)
        args = ["".join(i) for i in args]
        kwargs = dict((k, "".join(v)) for k, v in iteritems(kwargs))
        return args, kwargs, extra

    @classmethod
    def token_params(cls, params, maxnum=maxint):
        '''
        Parse custom token params detecting the correct parsing configuration
        for :py:method:param_split.

        :param string params: param string
        :param int maxnum: number of arguments will be parsed (default is all)
        :returns tuple: tuple with arguments list, keyword arguments dict and unparsed string.
        '''
        params = params.strip() if params else ""
        if params:
            if params.startswith("(") and params.endswith(")"):
                params = params[1:-1]
                valuesep = "="
                seps = ","
                free_escape = False
                must_quote = True
            else:
                valuesep = ""
                seps = ", "
                free_escape = True
                must_quote = False
            return cls.param_split(params, seps, valuesep, ", ",
                                   must_quote=must_quote,
                                   free_escape=free_escape, maxnum=maxnum)
        return (), {}, ""

    def check_indent(self, line):
        '''
        Get if current line should increment indent or not (if has inline code).
        :param string line: line of code with indent token
        :returns bool: True if line contains no inline code so must indent.
        '''
        match = self.re_inline.match(line)
        if match:
            stripped = match.groupdict().get("inline", "").strip()
            return not stripped or stripped.startswith("#")
        return True

    @property
    def indent(self):
        '''
        Get current indentation string, based in :py:cvar:tab and :py:var:level.

        :return string: current indent as string.
        '''
        return self.tab * self.level

    @property
    def dopass(self):
        if self.level == self.minlevel or self.block_stack and self.level == self.block_stack[-1][0]:
            return "%sreturn; yield" % self.indent
        return "%spass" % self.indent

    def yield_string_start(self):
        '''
        :yield basestring: line with string start yield
        '''
        if self.first_string_line:
            self.level_touched = True
            self.first_string_line = False
            yield "%syield (" % self.indent
            self.level += 1

    def yield_string_finish(self):
        '''
        :yield basestring: line with string finish and substitution tuple
        '''
        if not self.first_string_line:
            self.level_touched = True
            self.first_string_line = True
            if self.string_vars:
                rtup = ", ".join(self.string_vars)
                suffix = "" if "," in rtup else ","
                yield "%s) %% (%s%s)" % (self.indent, rtup, suffix)
                del self.string_vars[:]
            else:
                yield "%s)" % self.indent
            self.level -= 1

    def yield_from_native(self, param):
        '''
        :yield basestring: line with yield from for supported python versions
        '''
        yield "%syield from %s" % (self.indent, param)

    def yield_from_legacy(self, param):
        '''
        :yield basestring: lines with for line in... yield line for legacy python versions
        '''
        yield "%sfor line in %s:" % (self.indent, param)
        self.level += 1
        yield "%syield line" % self.indent
        self.level -= 1

    yield_from = yield_from_native if yield_from_supported else yield_from_legacy

    def translate_var(self, match):
        '''
        Get variable string substitution (for re.sub) and store variable code.
        :return str: positional variable string substitution '%s'
        '''
        group = match.groupdict()
        if group.get('escape', None):
            return '%%'
        var = group.get('var', None)
        if var is None:
            return ''
        var = var.strip()
        # STPL awful bang ('!') modifier
        var = var[1:].lstrip() if var[0] == '!' else '_escape(%s)' % var
        self.string_vars.append(var)
        return "%s"

    def translate_token_end(self, params=None):
        '''
        Decrement current indentation level.
        :yield str: line pass if current block is empty
        '''
        if not self.level_touched:
            yield self.dopass
        self.level -= 1
        self.level_touched = True # level already touched by indent token
        if self.level < self.minlevel:
            if self.block_stack:
                # level below minimum cos we're ending current block
                self.level, name = self.block_stack.pop()
            else:
                # prevent writing lines at module level
                raise self.syntax_error_class("Unmatching 'end' token on line %d" % self.linenum)

    def translate_token_extends(self, params=None):
        '''
        Declare that current template is based on given one.
        '''
        # extends is managed by template context
        if self.level > self.minlevel or self.block_stack:
            raise self.syntax_error_class("Token 'extends' must be outside any block (line %d)." % self.linenum)
        elif not self.extends is None:
            raise self.syntax_error_class("Token 'extends' cannot be defined twice (line %d)." % self.linenum)
        args, kwargs, unparsed = self.token_params(params)
        name = kwargs.get("name", args[0] if args else None)
        if name is None:
            raise self.value_error_class("Token 'extends' receives at least one argument: name (line %d)." % self.linenum)
        self.extends = name

    def translate_token_block(self, params=None):
        '''
        Generate lines for yielding block and starts block.
        :yield: lines for yielding from block
        '''
        # yield from block
        args, kwargs, unparsed = self.token_params(params, 1)
        name = kwargs.get("name", args[0] if args else None)
        if name is None:
            raise self.value_error_class("Token 'block' receives at least one argument: name (line %d)." % self.linenum)
        params = ("%r, %s" % (name, unparsed)) if unparsed else repr(name)
        for line in self.yield_from("block(%s)" % params):
            yield line
        # start putting lines on new block
        self.block_stack.append((self.level, name))
        self.level = self.minlevel
        self.level_touched = False

    def translate_token_block_super(self, params=None):
        '''
        Generate lines for yielding for block with the same name on parent template.
        :yield: lines for yielding from parent block
        '''
        if not self.block_stack:
            raise self.syntax_error_class("Token 'block.super' outside any block (line %d)" % self.linenum)
        for line in self.yield_from("block.super"):
            yield line

    def translate_token_include(self, params=None):
        '''
        Generate lines for yielding for other template with given name.
        :yield: lines for yielding from external template.
        '''
        args, kwargs, unparsed = self.token_params(params, 1)
        name = kwargs.get("name", args[0] if args else None)
        if name is None:
            raise self.value_error_class("Token 'include' receives at least one argument: name (line %d)." % self.linenum)
        params = ("%r, %s" % (name, unparsed)) if unparsed else repr(name)
        for line in self.yield_from("include(%s)" % params):
            yield line
        self.includes.append(name)

    def translate_token_rebase(self, params=None):
        '''
        Parses name from params and adds to :py:var:rebase which will be used
        later.
        '''
        args, kwargs, unparsed = self.token_params(params, 1)
        name = kwargs.get("name", args[0] if args else None)
        if name is None:
            raise self.value_error_class("Token 'rebase' receives at least one argument: name (line %d)." % self.linenum)
        self.rebase = name

    def translate_token_base(self, params=None):
        '''
        :yield: lines for yielding base template
        '''
        for line in self.yield_from("base"):
            yield line

    def translate_code_line(self, data):
        '''
        Translate a template line with inline python code
        '''
        # Code line
        lstripped = data[self.code_line_prefix_length:].lstrip()
        try:
            group = self.re_tokens.match(lstripped).groupdict()
        except AttributeError:
            group = {'custom':None,'redent':None,'indent':None}
        if group['custom']:
            method = 'translate_token_%s' % group['custom'].replace('.', '_')
            for line in getattr(self, method)(group['params']) or ():
                yield line
        elif group['redent']:
            if not self.level_touched:
                yield self.dopass
            self.level -= 1
            yield self.indent + lstripped
            if self.check_indent(lstripped):
                self.level += 1
                self.level_touched = False
        else:
            if lstripped.strip():
                yield self.indent + lstripped
            if group['indent'] and self.check_indent(lstripped):
                self.level += 1
                self.level_touched = False

    def translate_string_line(self, data):
        '''
        Translate regular template line with or without variable substitutions.
        :yields: lines that's starts yielding string (if not already done) and string line.
        '''
        # String
        if data.strip():
            data = self.re_var.sub(self.translate_var, data)
            for i in self.yield_string_start():
                yield i
            yield '%s%r' % (self.indent, data)
        elif not self.inline:
            for i in self.yield_string_start():
                yield i
            yield '%s%r' % (self.indent, data)

    def translate_literal_line(self, data):
        '''
        Generator function for translating lines inside python code blocks.

        When a code block ending is reached, this function switches :py:var:translate_line
        to :py:method:translate_literal_line.
        '''
        template_data = None
        if self.literal_close in data:
            data, template_data = data.split(self.literal_close, 1)
        if self.base is None and data.strip():
            self.base = len(data) - len(data.lstrip())
        # Remove unnecessary 'pass' commands
        if not self.level_touched or data.strip() != "pass":
            for line in self.yield_string_finish():
                yield line
            yield self.indent + data[self.base:]
        if not template_data is None:
            # Reset
            self.base = None
            self.inline = False
            # Switch to template mode
            self.translate_line = self.translate_template_line
            if template_data.strip():
                for i in self.yield_string_start():
                    yield i
                if self.previous_indent:
                    yield "%s%r" % (self.indent, " " * self.previous_indent)
                for line in self.translate_line(template_data):
                    yield line
            elif self.previous_string:
                for i in self.yield_string_start():
                    yield i
                yield "%s%r" % (self.indent, self.linesep)

    def translate_template_line(self, data):
        '''
        Generator function for translating template lines.

        When a code block is reached, this function switches :py:var:translate_line
        to :py:method:translate_literal_line.
        '''
        literal_data = None
        if self.literal_open in data:
            data, literal_data = data.split(self.literal_open, 1)
            self.inline = True
        lstripped = data.lstrip()
        if lstripped.startswith(self.code_line_prefix):
            for line in self.yield_string_finish():
                yield line
            self.previous_string = False
            for line in self.translate_code_line(lstripped):
                yield line
        else:
            if self.inline:
                if data.strip():
                    self.previous_string = True
                    self.previous_indent = 0
                else:
                    self.previous_string = False
                    self.previous_indent = len(data) - len(lstripped)
            for line in self.translate_string_line(data):
                yield line
        if not literal_data is None:
            # Switch to literal mode
            self.translate_line = self.translate_literal_line
            for line in self.translate_line(literal_data):
                yield line

    def translate_code(self, data):
        '''
        Resets object state (see :py:method:reset) and generate python code
        that yields given data.

        :param str data: template string
        :yields str: generated lines of python code with endings
        '''
        self.reset()

        # Yield lines
        yield "# -*- coding: UTF-8 -*-%s" % self.linesep
        yield "def __template__():%s" % self.linesep
        oneline = False
        annotated = False
        for self.linenum, line in enumerate(data.splitlines(True), 1):
            annotated = False
            for part in self.translate_line(line):
                if part.endswith(self.linesep):
                    # needed for annotations, removes extra whitelines
                    part = part[:-1]
                if not annotated:
                    annotated = True
                    margin = 67 - len(part) - len("%d" % self.linenum)
                    part += ("#lineno:%d#" % self.linenum).rjust(margin)
                if self.block_stack:
                    block_line, block_name = self.block_stack[-1]
                    self.block_content[block_name].append(part)
                    continue
                oneline |= True
                yield part + self.linesep
        self.level = self.minlevel # Reset level
        if not oneline:
            # empty template, pass
            yield self.dopass + self.linesep
        else:
            for line in self.yield_string_finish():
                yield line + self.linesep
            del self.string_vars[:]
        # Yield blocks
        yield "__blocks__ = {}%s" % self.linesep
        for name, lines in iteritems(self.block_content):
            yield "def __block__(block):%s" % self.linesep
            oneline = False
            for linenum, line in enumerate(lines, 1):
                oneline |= True
                yield line + self.linesep
            if not oneline:
                yield self.dopass + self.linesep
            yield "__blocks__[%r] = __block__%s" % (name, self.linesep)

        # Yield metadata fields
        yield (
            "__includes__ = %r%s"
            "__extends__ = %r%s"
            "__rebase__ = %r%s"
            ) % (
            self.includes, self.linesep,
            self.extends, self.linesep,
            self.rebase, self.linesep,
            )

    def reset(self):
        '''
        Sets object to initial state
        '''
        self.inline = False # if True will skip linesep to string lines
        self.first_string_line = True
        self.unfinished_token = False
        self.base = None
        self.linenum = -1
        self.level = self.minlevel = 1
        self.translate_line = self.translate_template_line
        self.extends = None
        self.rebase = None
        self.includes = []
        self.string_vars = []
        self.block_stack = [] # list of block levels as (base, name)
        self.block_content = collections.defaultdict(list)
        self.level_touched = False

class StringGenerator(object):
    '''
    Generic generator wrapper which receives a generator factory function and
    arguments and allows iteration.
    '''
    __slots__ = ('_iterfunc', '_args', '_kwargs')

    def __init__(self, iterfunc=None, *args, **kwargs):
        self._iterfunc = iterfunc
        self._args = args
        self._kwargs = kwargs

    def __iter__(self):
        if self._iterfunc:
            return self._iterfunc(*self._args, **self._kwargs)
        return ()

    def __str__(self):
        return "".join(self)

class LocalBlockGenerator(StringGenerator):
    '''
    Block context variable inside blocks
    '''
    __slots__ = ('super',)

    def __init__(self, superfunc, *args, **kwargs):
        StringGenerator.__init__(self)
        self.super = StringGenerator(superfunc, *args, **kwargs)

class BlockGenerator(StringGenerator):
    '''
    Object retrieved by block function
    '''
    __slots__ = ('_name', '_superfunc')

    local_block_class = LocalBlockGenerator

    @property
    def super(self):
        return StringGenerator(self._superfunc, self.name)

    def __init__(self, iterfunc, superfunc, name):
        StringGenerator.__init__(self, iterfunc)
        self._name = name
        self._superfunc = superfunc

    def __iter__(self):
        local_block = self.local_block_class(self._superfunc, self._name, self.local_block_class)
        return self._iterfunc(local_block)

class TemplateContext(object):
    '''
    Template namespace boilerplate, interpret, manages context, inheritance and
    generator functions from given template code.

    Can be used as context manager.
    '''
    block_class = BlockGenerator
    base_class = StringGenerator
    include_class = StringGenerator
    context_error_class = TemplateContextError
    escape_html = staticmethod(escape_html_safe)
    tostr = staticmethod(tostr_safe)

    _context = None

    @property
    def template(self):
        '''
        Current template generator-function.
        '''
        if self.rebased:
            return self.rebased.template
        return self.base_template

    @property
    def base_template(self):
        '''
        Current non-rebased template generator-function
        '''
        if self.parent:
            return self.parent.template
        return self.owned_template

    @property
    def context(self):
        if self.rebased:
            return self.rebased.context
        return self.base_context

    @property
    def base_context(self):
        if self.parent:
            return self.parent.base_context
        return self.owned_context

    @property
    def namespace(self):
        if self.rebased:
            return self.rebased.namespace
        return self.base_namespace

    @property
    def base_namespace(self):
        if self.parent:
            return self.parent.base_namespace
        return self.owned_namespace

    @property
    def parentmost(self):
        if self.parent:
            return self.parent.parentmost or self.parent
        return None

    @property
    def childmost(self):
        if self.child:
            return self.child.childmost or self.child
        return None

    def iter_ancestors(self):
        '''
        Iterate over ancestors as in (self, parentmost].
        '''
        ancestor = self.parent
        while ancestor:
            yield ancestor
            ancestor = ancestor.parent

    def iter_descendants(self):
        '''
        Iterate over descendants as in (self, childmost].
        '''
        descendant = self.child
        while descendant:
            yield descendant
            descendant = descendant.child

    def __init__(self, code, manager=None):
        '''
        Create environment, evaluates given code object and set up context.
        '''
        self.manager = manager

        self.includes_cache = {}

        # Relations for rebase
        self.rebased = None
        self.base = ""

        # Relations for extends
        self.parent = None
        self.child = None

        # Inheritance contexts
        self.owned_context = {}
        self.owned_namespace = {}

        eval(code, self.owned_namespace)
        self.owned_template = self.owned_namespace["__template__"]

        self.blocks = self.owned_namespace["__blocks__"]
        self.includes = self.owned_namespace["__includes__"]

        self.extends = self.owned_namespace["__extends__"]
        self.rebase = self.owned_namespace["__rebase__"]

        if self.manager is None and (self.includes or self.extends or self.rebase):
            raise self.context_error_class("TemplateContext's extends, include and rebase require a template manager.")

        if self.includes:
            self.includes_cache.update(
                (name, self.manager.get_template(name).get_context())
                for name in self.includes
                )

        if self.extends:
            self.parent = self.manager.get_template(self.extends).get_context()
            self.parent.child = self

        if self.rebase:
            self.rebased = self.manager.get_template(self.rebase).get_context()
            self.rebased.builtins['base'] = self.base_class(self.iter_base)

        self.builtins = {}
        self.builtins.update(builtins.__dict__)
        self.builtins.update({
            # Ctx reference for debugging
            "__ctx__": self,
            # Backwards-compatible ugly vars
            "_stdout": None,
            "_printlist": None,
            "_rebase": None,
            "_str": self.tostr,
            "_escape": self.escape_html,
            # Global functions
            "include": self.get_include,
            "block": self.get_block,
            # Namespace methods
            "defined": self.owned_namespace.__contains__,
            "get": self.owned_namespace.get,
            "setdefault": self.owned_namespace.setdefault,
            # Updated by related TemplateContexts
            "base": None,
            })

        self.reset()

    def get_include(self, name, **environ):
        '''
        Get include iterable based on :py:cvar:include_class
        '''
        if not name in self.includes_cache:
            self.includes_cache[name] = self.manager.get_template(name).get_context()
        context = self.includes_cache[name]
        context.reset(False)
        context.update(self.context)
        context.owned_namespace.update(environ)
        return self.include_class(self.includes_cache[name].template)

    def get_block(self, name, **environ):
        '''
        Get block iterable based on :py:cvar:block_class
        '''
        child = self.childmost or self
        if name in child.blocks:
            context = child
        else:
            for child in child.iter_ancestors():
                if name in child.blocks:
                    context = child
                    break
        if context:
            context.reset(False)
            context.owned_namespace.update(self.context)
            context.owned_namespace.update(environ)
            return context.block_class(context.blocks[name], context.iter_super, name)

    def iter_base(self, **environ):
        '''
        Yield from rebased template
        '''
        context = self
        context.reset(False)
        context.base_context.update(self.context)
        context.base_namespace.update(self.context)
        context.base_namespace.update(environ)
        return self.base_template()

    def iter_super(self, name, local_block_class, **environ):
        '''
        Yield from parent block generator with given name
        '''
        context = None
        for parent in self.iter_ancestors():
            if name in parent.blocks:
                context = parent
                break
        if context:
            context.reset(False)
            context.owned_namespace.update(self.context)
            context.owned_namespace.update(environ)
            return context.blocks[name](local_block_class(context.iter_super, name, local_block_class))
        return ()

    def reset(self, full_reset=True):
        '''
        Clears and repopulate template namespace

        :param bool reset_context: Whether (defaults to True) clean user-defined context vars

        '''
        if full_reset:
            if self.rebased:
                self.rebased.reset()
            self.base_context.clear()
        self.owned_namespace.clear()
        self.owned_namespace.update(self.builtins)

    def update(self, v):
        '''
        Add given iterable to namespace.
        '''
        self.context.update(v)
        self.namespace.update(v)

class Template(object):
    '''
    Template class using a template context-function pool for thread-safety.
    '''

    translate_class = CodeTranslator
    template_context_class = TemplateContext
    runtime_error_class = TemplateRuntimeError
    lineno_annotation_re = re.compile("^.*#lineno:(?P<lineno>\d+)#$")

    @property
    def pycode(self):
        return zlib.decompress(self._pycode).decode("utf-8")

    def __init__(self, code, filename=None, manager=None):
        self.filename = filename
        self.manager = manager
        self.code = code

        pycode = "".join(self.translate_class().translate_code(code))

        self._pycode = zlib.compress(pycode.encode("utf-8"))
        self._pycompiled = compile(pycode, filename or "<template>", "exec")
        self._pool = []

    def get_context(self, env=None):
        '''
        Generate or retrieve from pool a template context object for
        thread-safety usage.

        :param dict env: environment dictionary
        :returns TemplateContext: template context object
        '''
        if self._pool:
            context = self._pool.pop()
        else:
            context = self.template_context_class(self._pycompiled, self.manager)
        if env:
            context.update(env)
        return context

    def render(self, env=None):
        '''
        Renders template updating global namespace with env dict-like object.

        :param dict env: environment dictionary
        :yields str: template lines as string
        :raise TemplateRuntimeError: on any template exception.
        '''
        context = self.get_context(env)
        try:
            # Yielding here for proper error handling
            for line in context.template():
                yield line
        except BaseException as e:
            type, value, traceback = sys.exc_info()

            # Get exception template context
            tb_next = traceback
            while tb_next.tb_next:
                tb_next = tb_next.tb_next
            tb_ctx = tb_next.tb_frame.f_globals.get('__ctx__')
            if tb_ctx is None:
                raise

            # Get related template object
            template = None
            if tb_ctx is context:
                template = self
            elif self.manager:
                # Search for reference recursively
                queue = [context]
                candidates = {}
                while queue:
                    # Inspect reachable contexts
                    ctx = queue.pop()
                    candidates.clear()
                    if ctx.rebase:
                        candidates[ctx.rebase] = ctx.rebased
                    if ctx.extends:
                        candidates[ctx.extends] = ctx.parent
                    candidates.update(ctx.includes_cache)
                    # Check if one of candidates is reference
                    for name, cctx in iteritems(candidates):
                        if cctx is tb_ctx:
                            template = self.manager.get_template(name)
                            break
                        queue.append(cctx)
                    else:
                        continue
                    break

            # Generate exception
            if template:
                pycode = template.pycode.splitlines()
                pycode_lineno = tb_next.tb_lineno-1
                code_lineno = None

                # Search template line looking at annotations
                for lineno in xrange(pycode_lineno, -1, -1):
                    match = self.lineno_annotation_re.match(pycode[lineno])
                    if match:
                        code_lineno = int(match.groupdict()['lineno'], 10)
                        break
                else:
                    # should not happen
                    raise self.runtime_error_class(value,
                        pycode=pycode, pylineno=pycode_lineno
                        )
                raise self.runtime_error_class(value,
                    code=template.code.splitlines(), lineno=code_lineno,
                    pycode=pycode, pylineno=pycode_lineno
                    )
            raise self.runtime_error_class(value)
        finally:
            context.reset()
            self._pool.append(context)

class BufferingTemplate(Template):
    '''
    Template which yields buffered chunks of :py:cvar:buffersize size.

    You may want to inherit from this class in order to define a different
    value or, alternatively, change it once object is initialized.
    '''
    buffersize = 4096

    def render(self, env=None):
        '''
        Renders template updating global namespace with env dict-like object.
        Additionaly, this function ensures all-but-last yielded strings have
        the same length defined in :py:cvar:buffersize.

        :param dict env: environment dictionary
        :yields str: template lines as string
        '''
        buffsize = 0
        cache = []
        for line in Template.render(self, env):
            cache.append(line)
            buffsize += len(line)
            # Buffering
            while buffsize > self.buffersize:
                data = "".join(cache)
                yield data[:self.buffersize]
                data = data[self.buffersize:]
                cache[:] = (data,) if data else ()
                buffsize = len(data)
        if cache:
            yield "".join(cache)

class TemplateManager(object):
    '''
    Template manager is responsible of Template loading and caching, and should
    be instanced once for your application.

    Please consider that template parsing, compiling and running is much slower
    than taken a precompiled template from cache, so using this class is
    absolutely recommended.
    '''
    template_class = Template
    notfound_error_class = TemplateNotFoundError
    template_extensions = (".tpl", ".stpl")

    @staticmethod
    def _ensure_set(obj):
        '''
        Ensure given object is correctly converted to a set.

        :param obj: any python object
        :return set: set containing obj or elements from obj if non-string iterable.
        '''
        if obj is None:
            return set()
        elif isinstance(obj, native_string_bases):
            return set((obj,))
        elif not isinstance(obj, set):
            return set(obj)
        return obj

    def __init__(self, directories=None):
        self.directories = self._ensure_set(directories)
        self.templates = {}

    def get_template(self, name):
        '''
        Get template object from given name from cache, template directories, or path.

        Note that template is cached based on given name, so if you pass to this method an absolute path, it will be the key from cache.

        :param str name: name of template (path or name if extension is in :py:cvar:template_extensions)
        :return Template: template object
        '''
        if not name in self.templates:
            template_path = None
            if not os.path.isabs(name):
                for directory in self.directories:
                    path = os.path.join(directory, name)
                    if os.path.isfile(path):
                        template_path = path
                        break
                    for ext in self.template_extensions:
                        extpath = path + ext
                        if os.path.isfile(extpath):
                            template_path = extpath
                            break
                    else:
                        continue
                    break
            elif os.path.exists(name):
                template_path = name
            if template_path is None:
                raise self.notfound_error_class("Template %r not found" % name)
            with open(template_path) as f:
                self.templates[name] = Template(f.read(), template_path, self)
        return self.templates[name]

    def render(self, name, env=None):
        '''
        Render template corresponding to given name or path.

        :param str name: name or path for template
        :param dict env: optional variable dictionary
        :yield str: string with lines from rendered template
        '''
        return self.get_template(name).render(env)

    def reset(self):
        '''
        Clear template cache.
        '''
        self.templates.clear()


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Just how much baggage is getting lost with British Airways?</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="https://danharr.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//danharr.github.io/themes/ichi/assets/css/normalize.css?v=1470761575831" />
    <link rel="stylesheet" type="text/css" href="//danharr.github.io/themes/ichi/assets/css/foundation.min.css?v=1470761575831" />

    <link rel="stylesheet" type="text/css" href="//danharr.github.io/themes/ichi/assets/fonts/foundation-icons/foundation-icons.css?v=1470761575831" />
    <link rel="stylesheet" type="text/css" href="//danharr.github.io/themes/ichi/assets/css/styles.css?v=1470761575831" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Open+Sans:300,700,400|Source+Sans+Pro:300,400,600,700,900,300italic,400italic,600italic,700italic,900italic" />

    <link rel="canonical" href="https://danharr.github.io/2016/08/08/Just-how-much-baggage-is-getting-lost-with-British-Airways.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Dan Harrington Blog" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Just how much baggage is getting lost with British Airways?" />
    <meta property="og:description" content="Live dashboard using d3js and google docs Click here for the live dashboard So in July 2016 I got married.  Not a thing went wrong until the honeymoon.  To cut a long story short our luggage was delayed from Heathrow Terminal 5 and so half the honeymoon was spent without" />
    <meta property="og:url" content="https://danharr.github.io/2016/08/08/Just-how-much-baggage-is-getting-lost-with-British-Airways.html" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Just how much baggage is getting lost with British Airways?" />
    <meta name="twitter:description" content="Live dashboard using d3js and google docs Click here for the live dashboard So in July 2016 I got married.  Not a thing went wrong until the honeymoon.  To cut a long story short our luggage was delayed from Heathrow Terminal 5 and so half the honeymoon was spent without" />
    <meta name="twitter:url" content="https://danharr.github.io/2016/08/08/Just-how-much-baggage-is-getting-lost-with-British-Airways.html" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Dan Harrington Blog" href="https://danharr.github.io/rss/" />

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

    <button type="button" class="overlay-close">Close</button>

Home

Dan Harrington Blog

Latest projects and ideas of Dan Harrington

Just how much baggage is getting lost with British Airways?

            <time datetime="2016-08-08">08 Aug 2016</time>

Live dashboard using d3js and google docs

Click here for the live dashboard

So in July 2016 I got married.  Not a thing went wrong until the honeymoon.  To cut a long story short our luggage was delayed from Heathrow Terminal 5 and so half the honeymoon was spent without the items we’d packed (we’d planned to go hiking, etc. stuff you can’t easily replace)

There have been -- tweets since July 2016 containing the terms british_airways and lost

I was intrigued about just how often this is happening to other people.  Was I very unlucky to be without my bags?  Or is this simply inevitable and simply 'my turn'?  Using IFTTT and a Google Analytics script I was able to collect every tweet that contained the terms british_airways and lost.  Obviously some of these were unrelated to lost baggage (e.g. BA ran a program where they reunited long lost relatives), but most of the time tweets were of this nature:

If you're a courier in Marseille and you could deliver my lost luggage tonight, do let @British_Airways know. They say it's 'not possible'.
— James May (@MrJamesMay) July 31, 2016

Click here for the live dashboard

How to make a live dashboard

I’ve made one of these live updating dashboards before, by tracking my weight as measured by a set of Withings scales.  The short version is that IFTTT writes a row to a spreadsheet everytime there’s a tweet which matches my conditions (containing the terms british_airways and lost).

From there, I use this Google Apps script which converts the Google doc to json, a format I’m able to then visualise.  d3.js handles the data visualisation.

Rather than just repeat the dashboard I’d used earlier, this time I included the excellent swoopy-drag library.  This helps me annotate certain points on the chart that might need explaining.  I added the below line to the source code (line 54 I believe) to allow me to add hyperlinks to the annotations

var textSel = annotationSel.append('a').attr('href',ƒ('link')).append('text')

I then updated the annotations variale to include the hyperlink

"link":'https://twitter.com/MrJamesMay/status/759827333997924352',

                        No tag

Liked this post ? Share it.

                        About the author

@danjharrington

                        London
                        https://danjharrington.wordpress.com/

Discussions

          Please enable JavaScript to view the comments powered by Disqus.
          comments powered by Disqus


text:
var SKL_API_URL = 'http://api.toast-it.io/v0-2';
// var SKL_API_URL = 'http://dockervm:8080/v0-2';

angular.module('SceneSkeleton')
	.factory("Scenes", function($resource) {
		var service = $resource(SKL_API_URL+"/scenes/:id/:completedAt",{},{
			get:{
				transformResponse:function(data,header){
					var scene = JSON.parse(data);
					return NormaliseScene(scene);
				}
			},
			query:{
				isArray: true,
				transformResponse:function(data,header){
					var scenes = angular.fromJson(data);
					console.log(scenes);
					return scenes.map(NormaliseScene);
				}
			}
		});
		return service;
	});

angular.module('SceneSkeleton')
	.factory("SceneRequests", function($resource) {
		var service = $resource(SKL_API_URL+"/scene-requests/:id/:createdAt",{},{
			get:{
				transformResponse:function(data,header){
					var scene = JSON.parse(data);
					return NormaliseScene(scene);
				}
			},
			query:{
				isArray: true,
				transformResponse:function(data,header){
					var scenes = angular.fromJson(data);
					console.log(scenes);
					return scenes.map(NormaliseScene);
				}
			}
		});
		return service;
	});

angular.module('SceneSkeleton')
	.factory("Generators", function($resource) {
		var service = {
			query:function(){
				return [
					"Snowflake"
				];
			}
		}
		return service;
	});

function NormaliseScene(scene){
	return scene;
}


text:
from django.contrib import admin
from .models import ShippingAddress, CustomerUser, CreditCard

admin.site.register(ShippingAddress)
admin.site.register(CustomerUser)
admin.site.register(CreditCard)


text:
requirejs.config({
    "baseUrl": "js/lib",
    "waitSeconds": 0,
    "paths": {
      "app": "../app",
      "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min",
      /*
       * Loading the plug in this way to avoid making a copy of
       * the source files to the baseUrl directory.
       * This is just for the demo.  You would be able to add the
       * file directly to your baseUrl directory.
       */
      "jquery.editrowform": "../../../../dist/jquery.editrowform.min"
    }
});

// Load the main app module to start the app
requirejs(["app/main"]);


text:
import fs from 'fs';
import path from 'path';
import eventEmitter from './events';

// TODO: find a better way to have plugins play nice with webpack bundling
// tslint:disable-next-line:no-eval
const req = eval('require');
const pluginsPath = path.join(__dirname, '..', '..', 'plugins');
const plugins = fs.readdirSync(pluginsPath).filter(file => fs.statSync(path.join(pluginsPath, file)).isDirectory());
plugins.forEach(file => req('../plugins/' + file + '/index.js')(eventEmitter));


text:
<component name="libraryTable">
  <library name="Maven: com.ibm.watson.developer_cloud:visual-recognition:3.5.3">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/com/ibm/watson/developer_cloud/visual-recognition/3.5.3/visual-recognition-3.5.3.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/com/ibm/watson/developer_cloud/visual-recognition/3.5.3/visual-recognition-3.5.3-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/com/ibm/watson/developer_cloud/visual-recognition/3.5.3/visual-recognition-3.5.3-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
var utils = require('../lib/utils.js');

var merica = {
  info: {
    name: 'merica',
    style: 2
  },
  ai: function(playerState, enemiesStates, gameEnvironment) {
    var directionToAmmo;

    // if camping, and enemy in line of fire, fire.
    if (utils.canKill(playerState, enemiesStates) && playerState.ammo) {
      return 'shoot';
    }

    // if no ammo, find ammo
    if (!playerState.ammo && gameEnvironment.ammoPosition.length) {
      directionToAmmo = utils.fastGetDirection(playerState.position, gameEnvironment.ammoPosition[0]);

      if (directionToAmmo !== playerState.direction) return directionToAmmo;
      return 'move';
    }

    // if have ammo, go camp somewhere
    //return utils.safeRandomMove();
    var myArray = ['north', 'south', 'east', 'west'];
    return myArray[Math.floor(Math.random() * myArray.length)];
    //return utils.safeRandomMove();
  }
}
var getNextPosition = function(playerState) {
    switch (playerState.direction) {
        case 'north':
            return [playerState[0], playerState[1] + 1];
        case 'west':
            return [playerState[0] - 1, playerState[1]];
        case 'south':
            return [playerState[0], playerState[1] - 1];
        case 'east':
            return [playerState[0] + 1, playerState[1]];
    }

module.exports = merica


text:
package util.crypto;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

/**
 * Utilities to deal with Certificates.
 * This class only provides static helper classes to pack/unpack Certifiates
 * into x.509/java.security.cert.Certificate objects and does not provide a
 * Wrapper as many of the other classes in this library do.
 * Created by a2800276 on 2015-11-03.
 */
public class Certificate {

	/**
	 * Convert x.509 bytes into a java.security.cert.Certificate
	 *
	 * @param bytes raw x.509 bytes
	 * @return java.security.cert.Certificate
	 * @throws WrappedException on invalid x.509 bytes
	 */
	public static java.security.cert.Certificate loadCertificate(byte[] bytes) {
		return loadCertificate(bytes, 0, bytes.length);
	}

	/**
	 * Convert x.509 bytes into a java.security.cert.Certificate
	 *
	 * @param bytes raw x.509 bytes
	 * @return java.security.cert.Certificate
	 * @throws WrappedException on invalid x.509 bytes
	 */
	public static java.security.cert.Certificate loadCertificate(byte[] bytes, int offset, int length) {
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes, offset, length);
		return loadCertificate(bis);
	}

	/**
	 * Convert x.509 bytes from an InputStream into a java.security.cert.Certificate
	 *
	 * @param is InputStream to read raw x.509 bytes from
	 * @return java.security.cert.Certificate
	 * @throws WrappedException on invalid x.509 bytes
	 */
	public static java.security.cert.Certificate loadCertificate(InputStream is) {
		try {
			CertificateFactory cf = CertificateFactory.getInstance(Constants.CERTIFICATE_TYPE_X509);
			return cf.generateCertificate(is);
		} catch (CertificateException e) {
			throw new WrappedException(e);
		}
	}

	/**
	 * Generate the X509 representation of the certificate.
	 *
	 * @return x.509 bytes of certificate
	 * @throws IllegalArgumentException if certificate type is not x.509 (no other types exist in
	 *                                  default JCA) or null is provided.
	 *                                  CryptoException wrapping an underlying CertificateEncodingException if "encoding errors occur"
	 */
	public static byte[] getX509Bytes(java.security.cert.Certificate certificate) {
		if (certificate == null || !(certificate.getType().equals(Constants.CERTIFICATE_TYPE_X509))) {
			throw new IllegalArgumentException("can not convert to x509");
		}
		try {
			return certificate.getEncoded();
		} catch (CertificateEncodingException e) {
			throw new WrappedException(e);
		}
	}
}


text:
import os
from pathlib import Path
import unittest

import ray
import ray.rllib.agents.marwil as marwil
from ray.rllib.utils.framework import try_import_tf
from ray.rllib.utils.test_utils import check_compute_single_action, \
    framework_iterator

tf1, tf, tfv = try_import_tf()

class TestBC(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        ray.init()

    @classmethod
    def tearDownClass(cls):
        ray.shutdown()

    def test_bc_compilation_and_learning_from_offline_file(self):
        """Test whether a BCTrainer can be built with all frameworks.

        And learns from a historic-data file (while being evaluated on an
        actual env using evaluation_num_workers > 0).
        """
        rllib_dir = Path(__file__).parent.parent.parent.parent
        print("rllib dir={}".format(rllib_dir))
        data_file = os.path.join(rllib_dir, "tests/data/cartpole/large.json")
        print("data_file={} exists={}".format(data_file,
                                              os.path.isfile(data_file)))

        config = marwil.BC_DEFAULT_CONFIG.copy()
        config["num_workers"] = 0  # Run locally.

        config["evaluation_interval"] = 3
        config["evaluation_num_workers"] = 1
        config["evaluation_num_episodes"] = 5
        config["evaluation_parallel_to_training"] = True
        # Evaluate on actual environment.
        config["evaluation_config"] = {"input": "sampler"}
        # Learn from offline data.
        config["input"] = [data_file]
        num_iterations = 350
        min_reward = 70.0

        # Test for all frameworks.
        for _ in framework_iterator(config, frameworks=("tf", "torch")):
            trainer = marwil.BCTrainer(config=config, env="CartPole-v0")
            learnt = False
            for i in range(num_iterations):
                eval_results = trainer.train().get("evaluation")
                if eval_results:
                    print("iter={} R={}".format(
                        i, eval_results["episode_reward_mean"]))
                    # Learn until good reward is reached in the actual env.
                    if eval_results["episode_reward_mean"] > min_reward:
                        print("learnt!")
                        learnt = True
                        break

            if not learnt:
                raise ValueError(
                    "BCTrainer did not reach {} reward from expert offline "
                    "data!".format(min_reward))

            check_compute_single_action(
                trainer, include_prev_action_reward=True)

            trainer.stop()

if __name__ == "__main__":
    import pytest
    import sys
    sys.exit(pytest.main(["-v", __file__]))


text:
package org.kuali.kfs.fp.document.web.struts;

import org.kuali.kfs.fp.document.CapitalAssetEditable;

/**
 * Struts form for <code>{@link YearEndGeneralErrorCorrectionDocument}</code>. This class is mostly empty because it inherits
 * everything it needs from its parent non-year end version. This is necessary to adhere to the transactional document framework.
 */
public class YearEndGeneralErrorCorrectionForm extends GeneralErrorCorrectionForm  implements CapitalAssetEditable{
    /**
     * Constructs a YearEndGeneralErrorCorrectionForm instance.
     */
    public YearEndGeneralErrorCorrectionForm() {
        super();
    }

    @Override
    protected String getDefaultDocumentTypeName() {
        return "YEGE";
    }
}


text:
describe("Tests for navigation-common behavior", function() {
  var behavior, sandbox, contextFake, windowSvc;

  beforeEach(function() {
    windowSvc = {
      openAlerts: function() {},
      getHashVariable: function() {},
      variableStateInHash: function() {}
    };
    jquery = {
      attr: function() {}
    };
    contextFake = new Box.TestServiceProvider({
      'window': windowSvc,
      'jQuery': jquery
    });
    contextFake.getElement = function() { return this };
    behavior = Box.Application.getBehaviorForTest('navigation-common', contextFake);
    behavior.init();
    sandbox = sinon.sandbox.create();
  });

  afterEach(function() {
    behavior.destroy();
    sandbox.verifyAndRestore();
  });

  it('Clicking an element with "alert" type should open the alert window', function() {
    sandbox.mock(windowSvc).expects('openAlerts').once();
    var target = $(' <svg data-type="alerts"></svg>')[0];
    var event = $.Event('click', {
      target: target
    });
    behavior.onclick(event, target, 'alerts');
  });

  it('Changeing time scale should send "timescale-changed" message', function() {
    sandbox.mock(contextFake).expects('broadcast').once().withExactArgs("timescale-changed", "1000");
    var target = $('<select id="timescale" class="navcenter smooth" data-type="select-timescale"><option value="1000">3h</option></select>')[0];
    target.selectedIndex = 0;
    var event = $.Event('change', {
      target: target
    });
    behavior.onchange(event, target, 'select-timescale');
  });

});


text:
<?php

/**
 * Hybrid_Providers_Deezer - Deezer provider adapter based on OAuth2 protocol
 */
class Hybrid_Providers_Deezer extends Hybrid_Provider_Model_OAuth2
{
    // default permissions
    public $scope = "basic_access,email,offline_access";

    public static $_profileData = null;

    /**
     * IDp wrappers initializer
     */
    function initialize()
    {
        parent::initialize();

        $this->api->api_base_url = 'https://api.deezer.com/';
        $this->api->authorize_url = 'https://connect.deezer.com/oauth/auth.php';
        $this->api->token_url = 'https://connect.deezer.com/oauth/access_token.php';

        $this->api->curl_authenticate_method = "GET";
    }

    public function getUserProfile()
    {
        if (self::$_profileData === null)
        {
            $data = $this->request('user/me');
            self::$_profileData = json_decode($data, true);
        }
        return self::$_profileData;
    }

    public function getUserId()
    {
        $data = $this->getUserProfile();
        $id = $data['id'];
        return $id;
    }

    public function getUserArtists()
    {
        $data = $this->request('user/' . $this->getUserId() . '/artists');
        $data = json_decode($data, true);
        while (isset($data['next']))
        {
            $tempData = $this->request($data['next']);
            $tempData = json_decode($tempData, true);
            unset($data['next']);
            if (isset($tempData['next']))
            {
                $data['next'] = $tempData['next'];
            }
            $data['data'] = array_merge($data['data'], $tempData['data']);
        }
        return $data;
    }

    public function getUserAlbums()
    {
        $data = $this->request('user/' . $this->getUserId() . '/albums');
        $data = json_decode($data, true);
        while (isset($data['next']))
        {
            $tempData = $this->request($data['next']);
            $tempData = json_decode($tempData, true);
            unset($data['next']);
            if (isset($tempData['next']))
            {
                $data['next'] = $tempData['next'];
            }
            $data['data'] = array_merge($data['data'], $tempData['data']);
        }
        return $data;
    }

    public function getUserFriends()
    {
        $data = $this->request('user/' . $this->getUserId() . '/followings');
        $data = json_decode($data, true);
        while (isset($data['next']))
        {
            $tempData = $this->request($data['next']);
            $tempData = json_decode($tempData, true);
            unset($data['next']);
            if (isset($tempData['next']))
            {
                $data['next'] = $tempData['next'];
            }
            $data['data'] = array_merge($data['data'], $tempData['data']);
        }
        return $data;
    }

    public function request($method, $params = [])
    {
        try
        {
            if (preg_match("/https:\/\//", $method)) {
                $url = $method . '?access_token=' . $this->api->access_token;
            }
            else
            {
                $url = $this->api->api_base_url . $method . '?access_token=' . $this->api->access_token . '&limit=10000';
            }
            $data = CURLHelper::simple($url);
        } catch (Exception $e)
        {
            $data = ['error' => "Can't provide query"];
        }
        return $data;
    }

    /**
     * begin login step
     */
    function loginBegin()
    {
        // redirect the user to the provider authentication url
        Hybrid_Auth::redirect($this->api->authorizeUrl(array("perms" => $this->scope)));
    }

}


text:
<?php

namespace Bow\Auth\Exception;

class AuthenticateException extends \Exception
{

}


text:
package ca.weixiao.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * A ListView with upward/downward infinite scrolling capability, with a customizable view
 * to be displayed at the top/bottom of the list as the loading indicator
 */
public class InfiniteScrollListView extends ListView implements InfiniteScrollListPageListener {

	public static final String TAG = InfiniteScrollListView.class.getSimpleName();
	// Two conditions allowing loading to happen: either the list view scrolls to the top or bottom
	public static enum LoadingMode {SCROLL_TO_TOP, SCROLL_TO_BOTTOM};
	// Decides where the ending position: either scrolls up to the start of the list, scrolls down to the
	// end of the list or where remains where it was
	public static enum StopPosition {START_OF_LIST, END_OF_LIST, REMAIN_UNCHANGED};

	private View loadingView;
	private LoadingMode loadingMode = LoadingMode.SCROLL_TO_BOTTOM;
	private StopPosition stopPosition = StopPosition.REMAIN_UNCHANGED;

	// A flag to prevent loading header or footer more than once
	private boolean loadingViewVisible = false;

    public InfiniteScrollListView(Context context) {
        super(context);
    }

    public InfiniteScrollListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public InfiniteScrollListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setLoadingView(View loadingView) {
		this.loadingView = loadingView;
	}

    public void setLoadingMode(LoadingMode loadingMode) {
    	this.loadingMode = loadingMode;
    }

    public void setStopPosition(StopPosition stopPosition) {
		this.stopPosition = stopPosition;
	}

    private void addLoadingView(ListView listView, View loadingView) {
    	if (listView == null || loadingView == null) {
    		return;
    	}
    	// Avoid overlapping the header or footer
    	if (!loadingViewVisible) {
			if (loadingMode == LoadingMode.SCROLL_TO_TOP) {
				// Add loading view to list view header when scroll up to load
				listView.addHeaderView(loadingView);
			} else {
				// Add loading view to list view footer when scroll down to load
				listView.addFooterView(loadingView);
			}
			loadingViewVisible = true;
    	}
    }

    private void removeLoadingView(ListView listView, View loadingView) {
    	if (listView == null || loadingView == null) {
    		return;
    	}
    	// Remove header or footer depending on the loading mode
    	if (loadingViewVisible) {
	    	if (loadingMode == LoadingMode.SCROLL_TO_TOP) {
				listView.removeHeaderView(loadingView);
			} else {
				listView.removeFooterView(loadingView);
			}
	    	loadingViewVisible = false;
    	}
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
    	// Force the list view to accept its own type of adapter
    	if (!(adapter instanceof InfiniteScrollListAdapter)) {
    		throw new IllegalArgumentException(InfiniteScrollListAdapter.class.getSimpleName() + " expected");
    	}
    	// Pass information to adaptor
    	InfiniteScrollListAdapter infiniteListAdapter = (InfiniteScrollListAdapter) adapter;
    	infiniteListAdapter.setLoadingMode(loadingMode);
    	infiniteListAdapter.setStopPosition(stopPosition);
    	infiniteListAdapter.setInfiniteListPageListener(this);
		this.setOnScrollListener(infiniteListAdapter);
		// Workaround to keep spaces for header and footer
		View dummy = new View(getContext());
		addLoadingView(InfiniteScrollListView.super, dummy);
    	super.setAdapter(adapter);
    	removeLoadingView(InfiniteScrollListView.super, dummy);
    }

	@Override
	public void endOfList() {
		// Remove loading view when there is no more to load
		removeLoadingView(this, loadingView);
	}

	@Override
	public void hasMore() {
		// Display loading view when there might be more to load
		addLoadingView(InfiniteScrollListView.this, loadingView);
	}

}


text:
require "rails-latex/version"
require "rails-latex/erb_latex"


text:
package ow.dht;

import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Random;
import java.util.Set;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.DefaultParser;

import ow.id.ID;
import ow.messaging.Signature;
import ow.routing.RoutingException;
import ow.tool.emulator.EmulatorControllable;
import ow.tool.util.toolframework.AbstractDHTBasedTool;

/**
 * A test and benchmarking tool for a DHT instance locally.
 * It is assumed to be invoked from a scenario DHTBenchmarkScenario.
 */
public class DHTBenchmark extends AbstractDHTBasedTool<String> {
	private final static String COMMAND = "java ow.dht.DHTBenchmark";

	public final static int NUM_VALUES = 1000;
	public final static int TTL = 5 * 60 * 1000;	// 5 min
	public final static String ENCODING = "UTF-8";
	private final static String KEY_PREFIX = "key";
	private final static String VALUE_PREFIX = "value";

	protected void usage(String command) {
		super.usage(command, null);
	}

	public static void main(String[] args) {
		(new DHTBenchmark()).start(args);
	}

	protected void start(String[] args) {
		this.invoke(args, System.out);
	}

	/**
	 * Implements {@link EmulatorControllable#invoke(String[], PrintStream)
	 * EmulatorControllableApplication#start}.
	 */
	public Writer invoke(String[] args, PrintStream out) {
		int repeat = 0;

		// parse command-line arguments
		Options opts = this.getInitialOptions();
		opts.addOption("b", "benchmark", true, "do benchmark");

		CommandLineParser parser = new DefaultParser();
		CommandLine cmd = null;
		try {
			cmd = parser.parse(opts, args);
		}
		catch (ParseException e) {
			System.out.println("There is an invalid option.");
			e.printStackTrace();
			System.exit(1);
		}

		parser = null;
		opts = null;

		String optVal;
		optVal = cmd.getOptionValue('b');
		if (optVal != null) {
			repeat = Integer.parseInt(optVal);
		}

		// parse remaining arguments
		// and initialize DHT
		DHT<String> dht = null;
		try {
			dht = super.initialize(Signature.APPLICATION_ID_DHT_SHELL, (short)0x10000,
					DHTFactory.getDefaultConfiguration(),
					COMMAND, cmd);
		}
		catch (Exception e) {
			System.err.println("An Exception thrown:");
			e.printStackTrace();
			return null;
		}

		cmd = null;

		if (repeat <= 0) {
			try {
				Thread.sleep(Long.MAX_VALUE);
			}
			catch (InterruptedException e) { /* ignore */ }

			return null;
		}

		// benchmark
		out.println("preparation: putting " + NUM_VALUES + " values.");

		dht.setTTLForPut(TTL);

		int idSize = dht.getRoutingAlgorithmConfiguration().getIDSizeInByte();
		for (int i = 0; i < NUM_VALUES; i++) {
			String key = KEY_PREFIX + i;
			String value = VALUE_PREFIX + i;

			ID id = null;
			try {
				id = ID.getID(key.getBytes(ENCODING), idSize);
			}
			catch (UnsupportedEncodingException e) { /* NOTREACHED */ }

			try {
				dht.put(id, value);
			}
			catch (Exception e) {
				out.println("put failed: " + key);
			}
		}

		out.println("benchmark: getting " + repeat + " times.");

		Random rnd = new Random();
		int numSuccess = 0;

		long time = System.currentTimeMillis();

		for (int i = 0; i < repeat; i++) {
			String key = KEY_PREFIX + rnd.nextInt(NUM_VALUES);

			ID id = null;
			try {
				id = ID.getID(key.getBytes(ENCODING), idSize);
			}
			catch (UnsupportedEncodingException e) { /* NOTREACHED */ }

			try {
				Set<ValueInfo<String>> valueSet = dht.get(id);
				if (valueSet != null) {
					numSuccess++;
				}
			}
			catch (RoutingException e) { /* ignore */ }
		}

		time = System.currentTimeMillis() - time;

		System.out.println("time (msec): " + time);
		System.out.println("num of successful get: " + numSuccess + " / " + repeat);

		return null;
	}
}


text:
<?php

namespace Tempo\Bundle\AppBundle\Form\Type;

use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ProfileType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', TextType::class, array(
                'label' => 'tempo.profile.form.firstName'
            ))
            ->add('lastName', TextType::class, array(
                'label' => 'tempo.profile.form.lastName'
            ))
            ->add('company', TextType::class, array(
                'label' => 'tempo.profile.form.company',
                'required' => false
            ))
            ->add('jobTitle', TextType::class, array(
                'label' => 'tempo.profile.form.job_title',
                'required' => false
            ))
            ->add('phones', CollectionType::class, array(
                'entry_type' => PhoneType::class,
                'allow_add' => true,
                'allow_delete' => true,
                'prototype' => true,
                'entry_options' => array(
                    'label' => false
                )
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Tempo\Bundle\AppBundle\Model\User',
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'user';
    }
}


text:
package org.fcrepo.http.commons.exceptionhandlers;

import static com.google.common.base.Throwables.getStackTraceAsString;
import static javax.ws.rs.core.Response.serverError;
import static javax.ws.rs.core.Response.status;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static org.slf4j.LoggerFactory.getLogger;

import javax.jcr.RepositoryException;
import javax.jcr.ValueFormatException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;

/**
 * Provide a quasi-useful stacktrace when a generic RepositoryException is caught
 *
 * @author awoods
 */
@Provider
public class RepositoryExceptionMapper implements
        ExceptionMapper<RepositoryException> {

    private static final Logger LOGGER = getLogger(RepositoryExceptionMapper.class);

    @Override
    public Response toResponse(final RepositoryException e) {

        LOGGER.warn("Caught repository exception: {}", e.getMessage() );
        if ( e.getMessage().matches("Error converting \".+\" from String to a Name")) {
            return status(BAD_REQUEST).entity(e.getMessage()).build();
        } else if ( e instanceof ValueFormatException ) {
            return status(BAD_REQUEST).entity(e.getMessage()).build();
        }

        return serverError().entity(getStackTraceAsString(e)).build();
    }
}


text:
using System;
using System.IO;

namespace SkidiKit.Resources
{
    public interface IAssets: IDisposable
    {
        void LoadTexture(string path, string frameName = null);
        void LoadTextureAtlas(string path);
        void LoadSoundEffect(string path, string name);
        void LoadFont(string path, string name);
        void LoadEffect(string path, string name);
        string LoadText(string path);
        Stream OpenStream(string path);
    }
}


text:
<!DOCTYPE html>

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">

<title>module Duxml::RngValueRule - RDoc Documentation</title>

<link type="text/css" media="screen" href="../rdoc.css" rel="stylesheet">

    Home
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input type="text" name="search" placeholder="Search" id="search-field"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Defined In

lib/duxml/meta/grammar/relax_ng/value_rule.rb

Included Modules

Duxml::LazyOx

Methods

#relaxng

Class and Module Index

Duxml

Duxml::Add

Duxml::AddClass

Duxml::AttrNamePattern

Duxml::AttrNamePatternClass

Duxml::AttrValPattern

Duxml::AttrValPatternClass

Duxml::AttrsRule

Duxml::AttrsRuleClass

Duxml::Change

Duxml::ChangeAttr

Duxml::ChangeAttrClass

Duxml::ChangeClass

Duxml::ChangeText

Duxml::ChangeTextClass

Duxml::ChildPattern

Duxml::ChildPatternClass

Duxml::ChildrenRule

Duxml::ChildrenRuleClass

Duxml::Doc

Duxml::Element

Duxml::ElementGuts

Duxml::Error

Duxml::ErrorClass

Duxml::Grammar

Duxml::GrammarClass

Duxml::History

Duxml::HistoryClass

Duxml::LazyOx

Duxml::Meta

Duxml::MetaClass

Duxml::NewAttr

Duxml::NewAttrClass

Duxml::NewText

Duxml::NewTextClass

Duxml::NodeSet

Duxml::NullChildPatternClass

Duxml::Pattern

Duxml::PatternClass

Duxml::PatternMaker

Duxml::QualifyError

Duxml::QualifyErrorClass

Duxml::RelaxNG

Duxml::Remove

Duxml::RemoveClass

Duxml::RngAttrsRule

Duxml::RngChildrenRule

Duxml::RngValueRule

Duxml::Rule

Duxml::RuleClass

Duxml::Saxer

Duxml::Saxer::DocuLiner

Duxml::Spreadsheet

Duxml::TextPattern

Duxml::TextPatternClass

Duxml::TextRule

Duxml::TextRuleClass

Duxml::Undo

Duxml::UndoClass

Duxml::ValidateError

Duxml::ValidateErrorClass

Duxml::ValueRule

Duxml::ValueRuleClass

Fixnum

Module

Object

Regexp

Reportable

String

module Duxml::RngValueRule

Public Instance Methods

          relaxng(parent)

          click to toggle source

@param parent [Nokogiri::XML::Node] <grammar> i.e. parent node in RelaxNG document, NOT this Rule's document
@return [Nokogiri::XML::Node] parent, but adds to corresponding
<define><attribute> a child <data type="#{statement}">

where #statement can be 'CDATA', 'NMTOKEN', etc.

# File lib/duxml/meta/grammar/relax_ng/value_rule.rb, line 17
def relaxng(parent)
  parent.Define.each do |define|
    if define[:name] == attr_name
      attr_def = define.nodes.first
      unless attr_def.nodes.any?
        data_type = statement == 'CDATA' ? 'string' : statement
        if data_type.include?('|')
          choice_node = Element.new('choice')
          attr_def << choice_node
          data_type.split(/[\(\|\)]/).each do |en_val|
            if !en_val.empty? && Regexp.nmtoken.match(en_val)
              value_def = Element.new('value')
              value_def << en_val
              choice_node << value_def
            end
          end
        else
          data_def = Element.new('data')
          data_def[:type] = data_type
          attr_def << data_def
        end
      end # unless attr_def.nodes.any?
      return parent
    end # if define[:name] == attr_name
  end # parent.nodes.each
end

[Validate]

Generated by RDoc 4.0.0.

Generated with the Darkfish Rdoc Generator 3.


text:
/** Finds the specified Angular @Input in the given elements with tag name. */
export declare function findInputsOnElementWithTag(html: string, inputName: string, tagNames: string[]): number[];
/** Finds the specified Angular @Input in elements that have one of the specified attributes. */
export declare function findInputsOnElementWithAttr(html: string, inputName: string, attrs: string[]): number[];
/** Finds the specified Angular @Output in the given elements with tag name. */
export declare function findOutputsOnElementWithTag(html: string, outputName: string, tagNames: string[]): number[];
/** Finds the specified Angular @Output in elements that have one of the specified attributes. */
export declare function findOutputsOnElementWithAttr(html: string, outputName: string, attrs: string[]): number[];


text:
module JSON::LD::SIGNATURE

  class Verify

    def self.verify(input, options = {})

      # We require a publicKeyPem in the options hash
      if options['publicKeyPem'].nil?
        raise JsonLdSignatureError::MissingKey, "options parameter must include publicKeyPem"
      end

      # The publicKeyPem can be either a String or a parsed RSA key
      publicKey = case options['publicKeyPem']
      when String then OpenSSL::PKey::RSA.new options['publicKeyPem']
      when OpenSSL::PKey::RSA then options['publicKeyPem']
      else
        raise JsonLdSignatureError::InvalidKeyType, "key must be RSA Key or PEM String"
      end

      # Check the input, it should either be a String or a parsed JSON object

      jsonld = case input
      when String then
      begin
          JSON.parse(input)
        rescue JSON::ParserError => e
            raise JsonLdSignatureError::InvalidJsonLdDocument, e.message
      end
      when Hash then input
      else
        raise JsonLdSignatureError::InvalidJsonLdDocument
      end

      signature = jsonld['signature']

      created = signature['created']
      creator = signature['creator']
      signatureValue = signature['signatureValue']
      domain = signature['domain']
      nonce = signature['nonce']

      uri = URI(creator)
      response = Net::HTTP.get_response(uri)

      case response.code
        when "200"
          publicKey = OpenSSL::PKey::RSA.new response.body
        else
          raise JsonLdSignatureError::UnreachableKey,
             "Key #{creator} could not be retrieved. Error: #{response.code}, #{response.message}"
      end

      normOpts = {
        'nonce' => nonce,
        'domain' => domain,
        'created' => created,
        'creator' => creator
      }

      normalizedGraph = JSON::LD::SIGNATURE::generateNormalizedGraph jsonld, normOpts

      digest = OpenSSL::Digest::SHA256.new
      publicKey.verify digest, Base64.decode64(signatureValue), normalizedGraph
    end
  end
end


text:
package akka.persistence

import scala.collection.JavaConverters._

import java.util.Properties

import com.typesafe.config.Config

package object kafka {
  def journalTopic(persistenceId: String): String =
    persistenceId.replaceAll("[^\\w\\._-]", "_")

  def configToProperties(config: Config, extra: Map[String, String] = Map.empty): Properties = {
    val properties = new Properties()

    config.entrySet.asScala.foreach { entry =>
      properties.put(entry.getKey, entry.getValue.unwrapped.toString)
    }

    extra.foreach {
      case (k, v) => properties.put(k, v)
    }

    properties
  }
}


text:
namespace witsmllib
{

    //import java.util.Date;

    /**
     * Java representation of a WITSML "bhaRun".
     *
     * @author NWitsml
     */
    using System;
    public abstract class WitsmlBhaRun : WitsmlObject
    {
        /** The WITSML type name */
        private static String WITSML_TYPE = "bhaRun";

        protected DateTime? startTime; // dTimStart
        protected DateTime? endTime; // dTimStop
        protected DateTime? drillingStartTime; // dTimStartDrilling
        protected DateTime? drillingEndTime; // dTimStopDrilling
        protected Value plannedDls; // planDogleg
        protected Value actualDls; // actDogleg
        protected Value maxActualDls; // actDoglegMx
        protected String status; // statusBha
        protected String bitRunNumber; // numBitRun
        protected String stringRunNumber; // numStringRun
        protected String reason; // reasonTrip
        protected String objective; // objectiveBha
        // protected WitsmlDrillingParameters drillingParameters; // drillingParams

        /**
         * Create a well object with specified ID.
         *
         * @param id  ID of this well.
         */
        protected WitsmlBhaRun(WitsmlServer server, String id, String name,
                               WitsmlObject parent, String parentId)
            : base(server, WITSML_TYPE, id, name, parent, parentId)
        { }

        public DateTime? getStartTime()
        {
            return startTime;
        }

        public DateTime? getEndTime()
        {
            return endTime;
        }

        public DateTime? getDrillingStartTime()
        {
            return drillingStartTime;
        }

        public DateTime? getDrillingEndTime()
        {
            return drillingEndTime;
        }

        public Value getPlannedDls()
        {
            return plannedDls;
        }

        public Value getActualDls()
        {
            return actualDls;
        }

        public Value getMaxActualDls()
        {
            return maxActualDls;
        }

        public String getStatus()
        {
            return status;
        }

        public String getBitRunNumber()
        {
            return bitRunNumber;
        }

        public String getStringRunNumber()
        {
            return stringRunNumber;
        }

        public String getReason()
        {
            return reason;
        }

        public String getObjective()
        {
            return objective;
        }
    }
}


text:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="stylesheets/reset.css">
    <link rel="stylesheet" type="text/css" href="stylesheets/typography.css">
    <link rel="stylesheet" type="text/css" href="stylesheets/autocomplete.css">
    <title>Object Oriented JavaScript</title>

Object Oriented JavaScript

    <input type="text" name="autocomplete" id="autocomplete-field" />


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>WorkoutInfo</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.param.valuation

Class WorkoutInfo

java.lang.Object

org.drip.param.valuation.WorkoutInfo

public class WorkoutInfo
extends java.lang.Object

WorkoutInfo is the place-holder for the work-out parameters. It contains the date, the factor, the type,
  and the yield of the work-out.

Author:

Lakshmi Krishnamurthy

Field Summary

Fields

Modifier and Type
Field and Description

static int
WO_TYPE_CALL

Work out type Call

static int
WO_TYPE_MATURITY

Work out type Maturity

static int
WO_TYPE_PUT

Work out type Put

Constructor Summary

Constructors

Constructor and Description

WorkoutInfo(int iDate,
           double dblYield,
           double dblExerciseFactor,
           int iWOType)

Constructor: Construct the class from the work-out date, yield, exercise factor, and type

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

int
date()

Retrieve the Work-out Date

double
factor()

Retrieve the Work-out Factor

int
type()

Retrieve the Work-out Type

double
yield()

Retrieve the Work-out Yield

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

WO_TYPE_CALL

public static final int WO_TYPE_CALL

Work out type Call

See Also:

Constant Field Values

WO_TYPE_PUT

public static final int WO_TYPE_PUT

Work out type Put

See Also:

Constant Field Values

WO_TYPE_MATURITY

public static final int WO_TYPE_MATURITY

Work out type Maturity

See Also:

Constant Field Values

Constructor Detail

WorkoutInfo

public WorkoutInfo(int iDate,
                   double dblYield,
                   double dblExerciseFactor,
                   int iWOType)
            throws java.lang.Exception

Constructor: Construct the class from the work-out date, yield, exercise factor, and type

Parameters:

iDate - Work-out Date

dblYield - Work-out Yield

dblExerciseFactor - Work-out Factor

iWOType - Work out Type

Throws:

java.lang.Exception - Thrown if input is invalid

Method Detail

date

public int date()

Retrieve the Work-out Date

Returns:

The Work-out Date

yield

public double yield()

Retrieve the Work-out Yield

Returns:

The Work-out Yield

factor

public double factor()

Retrieve the Work-out Factor

Returns:

The Work-out Factor

type

public int type()

Retrieve the Work-out Type

Returns:

The Work-out Type

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method