text:
"""
A gdb-compatible frontend for lldb that implements just enough
commands to run the tests in the debuginfo-tests repository with lldb.
"""

# ----------------------------------------------------------------------
# Auto-detect lldb python module.
import commands, platform, os,  sys
try:
    # Just try for LLDB in case PYTHONPATH is already correctly setup.
    import lldb
except ImportError:
    lldb_python_dirs = list()
    # lldb is not in the PYTHONPATH, try some defaults for the current platform.
    platform_system = platform.system()
    if platform_system == 'Darwin':
        # On Darwin, try the currently selected Xcode directory
        xcode_dir = commands.getoutput("xcode-select --print-path")
        if xcode_dir:
            lldb_python_dirs.append(os.path.realpath(xcode_dir +
'/../SharedFrameworks/LLDB.framework/Resources/Python'))
            lldb_python_dirs.append(xcode_dir +
'/Library/PrivateFrameworks/LLDB.framework/Resources/Python')
        lldb_python_dirs.append(
'/System/Library/PrivateFrameworks/LLDB.framework/Resources/Python')
    success = False
    for lldb_python_dir in lldb_python_dirs:
        if os.path.exists(lldb_python_dir):
            if not (sys.path.__contains__(lldb_python_dir)):
                sys.path.append(lldb_python_dir)
                try:
                    import lldb
                except ImportError:
                    pass
                else:
                    print 'imported lldb from: "%s"' % (lldb_python_dir)
                    success = True
                    break
    if not success:
        print "error: couldn't locate the 'lldb' module, please set PYTHONPATH correctly"
        sys.exit(1)
# ----------------------------------------------------------------------

# Command line option handling.
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--quiet', '-q', action="store_true", help='ignored')
parser.add_argument('-batch', action="store_true",
                    help='exit after processing comand line')
parser.add_argument('-n', action="store_true", help='ignore .lldb file')
parser.add_argument('-x', dest='script', type=file, help='execute commands from file')
parser.add_argument("target", help="the program to debug")
args = parser.parse_args()

# Create a new debugger instance.
debugger = lldb.SBDebugger.Create()
debugger.SkipLLDBInitFiles(args.n)

# Don't return from lldb function calls until the process stops.
debugger.SetAsync(False)

# Create a target from a file and arch.
arch = os.popen("file "+args.target).read().split()[-1]
target = debugger.CreateTargetWithFileAndArch(args.target, arch)

if not target:
    print "Could not create target", args.target
    sys.exit(1)

if not args.script:
    print "Interactive mode is not implemented."
    sys.exit(1)

import re
for command in args.script:
    # Strip newline and whitespaces and split into words.
    cmd = command[:-1].strip().split()
    if not cmd:
        continue

    print '> %s'% command[:-1]

    try:
        if re.match('^r|(run)$', cmd[0]):
            error = lldb.SBError()
            launchinfo = lldb.SBLaunchInfo([])
            launchinfo.SetWorkingDirectory(os.getcwd())
            process = target.Launch(launchinfo, error)
            print error
            if not process or error.fail:
                state = process.GetState()
                print "State = %d" % state
                print """
ERROR: Could not launch process.
NOTE: There are several reasons why this may happen:
  * Root needs to run "DevToolsSecurity --enable".
  * Older versions of lldb cannot launch more than one process simultaneously.
"""
                sys.exit(1)

        elif re.match('^b|(break)$', cmd[0]) and len(cmd) == 2:
            if re.match('[0-9]+', cmd[1]):
                # b line
                mainfile = target.FindFunctions('main')[0].compile_unit.file
                print target.BreakpointCreateByLocation(mainfile, int(cmd[1]))
            else:
                # b file:line
                file, line = cmd[1].split(':')
                print target.BreakpointCreateByLocation(file, int(line))

        elif re.match('^ptype$', cmd[0]) and len(cmd) == 2:
            # GDB's ptype has multiple incarnations depending on its
            # argument (global variable, function, type).  The definition
            # here is for looking up the signature of a function and only
            # if that fails it looks for a type with that name.
            # Type lookup in LLDB would be "image lookup --type".
            for elem in target.FindFunctions(cmd[1]):
                print elem.function.type
                continue
            print target.FindFirstType(cmd[1])

        elif re.match('^po$', cmd[0]) and len(cmd) > 1:
            try:
                opts = lldb.SBExpressionOptions()
                opts.SetFetchDynamicValue(True)
                opts.SetCoerceResultToId(True)
                print target.EvaluateExpression(' '.join(cmd[1:]), opts)
            except:
                # FIXME: This is a fallback path for the lab.llvm.org
                # buildbot running OS X 10.7; it should be removed.
                thread = process.GetThreadAtIndex(0)
                frame = thread.GetFrameAtIndex(0)
                print frame.EvaluateExpression(' '.join(cmd[1:]))

        elif re.match('^p|(print)$', cmd[0]) and len(cmd) > 1:
            thread = process.GetThreadAtIndex(0)
            frame = thread.GetFrameAtIndex(0)
            print frame.EvaluateExpression(' '.join(cmd[1:]))

        elif re.match('^n|(next)$', cmd[0]):
            thread = process.GetThreadAtIndex(0)
            thread.StepOver()

        elif re.match('^q|(quit)$', cmd[0]):
            sys.exit(0)

        else:
            print debugger.HandleCommand(' '.join(cmd))

    except SystemExit:
        lldb.SBDebugger_Terminate()
        raise
    except:
        print 'Could not handle the command "%s"' % ' '.join(cmd)

redpajama_set_name: RedPajamaGithub


text:
SCRIPT_PATH="$( dirname "${BASH_SOURCE[0]}" )"
cd "$SCRIPT_PATH/.."

pip3 install pdoc3
pdoc3 --html --force --output-dir docs/html bigbench


text:
using System;
using System.Collections.Generic;
using System.Linq;

public static class Say
{
    public static string InEnglish(long number)
    {
        if (number < 0L || number >= 1000000000000L)
        {
            throw new ArgumentOutOfRangeException("Number out of range.");
        }

        if (number == 0L)
        {
            return "zero";
        }

        return string.Join(" ", Parts(number));
    }

    private static IEnumerable<string> Parts(long number)
    {
        var counts = Counts(number);
        var billionsCount = counts.Item1;
        var millionsCount = counts.Item2;
        var thousandsCount = counts.Item3;
        var remainder = counts.Item4;

        var billions = Billions(billionsCount);
        var millions = Millions(millionsCount);
        var thousands = Thousands(thousandsCount);
        var hundreds = Hundreds(remainder);

        return new[] { billions, millions, thousands, hundreds }.Where(x => x != null);
    }

    private static string Bases(long number)
    {
        var values = new[]
        {
            "one",
            "two",
            "three",
            "four",
            "five",
            "six",
            "seven",
            "eight",
            "nine",
            "ten",
            "eleven",
            "twelve",
            "thirteen",
            "fourteen",
            "fifteen",
            "sixteen",
            "seventeen",
            "eighteen",
            "nineteen"
        };

        return number > 0 && number <= values.Length ? values[number - 1] : null;
    }

    private static string Tens(long number)
    {
        if (number < 20L)
        {
            return Bases(number);
        }

        var values = new[]
        {
            "twenty",
            "thirty",
            "forty",
            "fifty",
            "sixty",
            "seventy",
            "eighty",
            "ninety"
        };

        var count = number / 10L;
        var remainder = number % 10L;
        var bases = Bases(remainder);

        var countStr = values[count - 2];
        var basesStr = bases == null ? "" : $"-{bases}";

        return $"{countStr}{basesStr}";
    }

    private static string Hundreds(long number)
    {
        if (number < 100L)
        {
            return Tens(number);
        }

        var count = number / 100L;
        var remainder = number % 100L;
        var bases = Bases(count);
        var tens = Tens(remainder);
        var tensStr = tens == null ? "" : $" {tens}";

        return $"{bases} hundred{tensStr}";
    }

    private static string Chunk(string str, long number)
    {
        var hundreds = Hundreds(number);
        return hundreds == null ? null : $"{hundreds} {str}";
    }

    private static string Thousands(long number) => Chunk("thousand", number);
    private static string Millions(long number) => Chunk("million", number);
    private static string Billions(long number) => Chunk("billion", number);

    private static Tuple<long, long, long, long> Counts(long number)
    {
        var billionsCount = number / 1000000000L;
        var billionsRemainder = number % 1000000000L;

        var millionsCount = billionsRemainder / 1000000L;
        var millionsRemainder = billionsRemainder % 1000000L;

        var thousandsCount = millionsRemainder / 1000L;
        var thousandsRemainder = millionsRemainder % 1000L;

        return Tuple.Create(billionsCount, millionsCount, thousandsCount, thousandsRemainder);
    }
}


text:
testes
======

Diretorio de Testes para Github


text:
#include "SessionCallback.h"

using namespace cms;
using namespace activemq::cmsutil;

////////////////////////////////////////////////////////////////////////////////
SessionCallback::~SessionCallback() {

}


text:
import functools

from pip._vendor.requests.adapters import HTTPAdapter

from .controller import CacheController
from .cache import DictCache
from .filewrapper import CallbackFileWrapper

class CacheControlAdapter(HTTPAdapter):
    invalidating_methods = set(['PUT', 'DELETE'])

    def __init__(self, cache=None,
                 cache_etags=True,
                 controller_class=None,
                 serializer=None,
                 heuristic=None,
                 *args, **kw):
        super(CacheControlAdapter, self).__init__(*args, **kw)
        self.cache = cache or DictCache()
        self.heuristic = heuristic

        controller_factory = controller_class or CacheController
        self.controller = controller_factory(
            self.cache,
            cache_etags=cache_etags,
            serializer=serializer,
        )

    def send(self, request, **kw):
        """
        Send a request. Use the request information to see if it
        exists in the cache and cache the response if we need to and can.
        """
        if request.method == 'GET':
            cached_response = self.controller.cached_request(request)
            if cached_response:
                return self.build_response(request, cached_response, from_cache=True)

            # check for etags and add headers if appropriate
            request.headers.update(self.controller.conditional_headers(request))

        resp = super(CacheControlAdapter, self).send(request, **kw)

        return resp

    def build_response(self, request, response, from_cache=False):
        """
        Build a response by making a request or using the cache.

        This will end up calling send and returning a potentially
        cached response
        """
        if not from_cache and request.method == 'GET':

            # apply any expiration heuristics
            if response.status == 304:
                # We must have sent an ETag request. This could mean
                # that we've been expired already or that we simply
                # have an etag. In either case, we want to try and
                # update the cache if that is the case.
                cached_response = self.controller.update_cached_response(
                    request, response
                )

                if cached_response is not response:
                    from_cache = True

                # We are done with the server response, read a
                # possible response body (compliant servers will
                # not return one, but we cannot be 100% sure) and
                # release the connection back to the pool.
                response.read(decode_content=False)
                response.release_conn()

                response = cached_response
            else:
                # Check for any heuristics that might update headers
                # before trying to cache.
                if self.heuristic:
                    response = self.heuristic.apply(response)

                # Wrap the response file with a wrapper that will cache the
                #   response when the stream has been consumed.
                response._fp = CallbackFileWrapper(
                    response._fp,
                    functools.partial(
                        self.controller.cache_response,
                        request,
                        response,
                    )
                )

        resp = super(CacheControlAdapter, self).build_response(
            request, response
        )

        # See if we should invalidate the cache.
        if request.method in self.invalidating_methods and resp.ok:
            cache_url = self.controller.cache_url(request.url)
            self.cache.delete(cache_url)

        # Give the request a from_cache attr to let people use it
        resp.from_cache = from_cache

        return resp


text:
/*
 * etch_field.h -- defines the etch_field object.
 * An etch_field is an etch_id_name representing a field of a struct or message
 * (i.e. a key for a value).
 */

#ifndef ETCHFIELD_H
#define ETCHFIELD_H

#include "etch_id_name.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * etch_field
 * We're simply typef'ing this for now, but we've left it open to later define
 * an etch_field struct having an etch_id_name as a member.
 */
typedef etch_id_name etch_field;

etch_field* new_field(const wchar_t* name);
etch_field* new_static_field(const wchar_t* name);
int destroy_static_field(etch_field*);

#define clone_field      clone_id_name
#define destroy_field    destroy_id_name
#define is_good_field    is_good_id_name
#define is_equal_fields  is_equal_id_names
#define compute_field_id compute_id_name_id
#define compute_field_id_from_widename compute_id_name_id_from_widename

#ifdef __cplusplus
}
#endif

#endif /* #ifndef ETCHFIELD_H */


text:
{-# LANGUAGE OverloadedStrings, StandaloneDeriving, DeriveDataTypeable #-}
{-# LANGUAGE CPP #-}
module Github.Private where

import Github.Data
import Data.Aeson
import Data.Attoparsec.ByteString.Lazy
import Data.Data
import Data.Monoid
import Control.Applicative
import Data.List
import Data.CaseInsensitive (mk)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Network.HTTP.Types (Status(..), notFound404)
import Network.HTTP.Conduit
-- import Data.Conduit (ResourceT)
import qualified Control.Exception as E
import Data.Maybe (fromMaybe)

-- | user/password for HTTP basic access authentication
data GithubAuth = GithubBasicAuth BS.ByteString BS.ByteString
                | GithubOAuth String
                deriving (Show, Data, Typeable, Eq, Ord)

githubGet :: (FromJSON b, Show b) => [String] -> IO (Either Error b)
githubGet = githubGet' Nothing

githubGet' :: (FromJSON b, Show b) => Maybe GithubAuth -> [String] -> IO (Either Error b)
githubGet' auth paths =
  githubAPI (BS.pack "GET")
            (buildUrl paths)
            auth
            (Nothing :: Maybe Value)

githubGetWithQueryString :: (FromJSON b, Show b) => [String] -> String -> IO (Either Error b)
githubGetWithQueryString = githubGetWithQueryString' Nothing

githubGetWithQueryString' :: (FromJSON b, Show b) => Maybe GithubAuth -> [String] -> String -> IO (Either Error b)
githubGetWithQueryString' auth paths qs =
  githubAPI (BS.pack "GET")
            (buildUrl paths ++ "?" ++ qs)
            auth
            (Nothing :: Maybe Value)

githubPost :: (ToJSON a, Show a, FromJSON b, Show b) => GithubAuth -> [String] -> a -> IO (Either Error b)
githubPost auth paths body =
  githubAPI (BS.pack "POST")
            (buildUrl paths)
            (Just auth)
            (Just body)

githubPatch :: (ToJSON a, Show a, FromJSON b, Show b) => GithubAuth -> [String] -> a -> IO (Either Error b)
githubPatch auth paths body =
  githubAPI (BS.pack "PATCH")
            (buildUrl paths)
            (Just auth)
            (Just body)

buildUrl :: [String] -> String
buildUrl paths = "https://api.github.com/" ++ intercalate "/" paths

githubAPI :: (ToJSON a, Show a, FromJSON b, Show b) => BS.ByteString -> String
          -> Maybe GithubAuth -> Maybe a -> IO (Either Error b)
githubAPI apimethod url auth body = do
  result <- doHttps apimethod url auth (encodeBody body)
  case result of
      Left e     -> return (Left (HTTPConnectionError e))
      Right resp -> either Left (\x -> jsonResultToE (LBS.pack (show x))
                                                   (fromJSON x))
                          <$> handleBody resp

  where
    encodeBody = Just . RequestBodyLBS . encode . toJSON

    handleBody resp = either (return . Left) (handleJson resp)
                             (parseJsonRaw (responseBody resp))

    -- This is an "escaping" version of "for", which returns (Right esc) if
    -- the value 'v' is Nothing; otherwise, it extracts the value from the
    -- Maybe, applies f, and return an IO (Either Error b).
    forE :: b -> Maybe a -> (a -> IO (Either Error b))
         -> IO (Either Error b)
    forE = flip . maybe . return . Right

    handleJson resp gotjson@(Array ary) =
        -- Determine whether the output was paginated, and if so, we must
        -- recurse to obtain the subsequent pages, and append those result
        -- bodies to the current one.  The aggregate will then be parsed.
        forE gotjson (lookup "Link" (responseHeaders resp)) $ \l ->
            forE gotjson (getNextUrl (BS.unpack l)) $ \nu ->
                either (return . Left . HTTPConnectionError)
                       (\nextResp -> do
                             nextJson <- handleBody nextResp
                             return $ (\(Array x) -> Array (ary <> x))
                                          <$> nextJson)
                       =<< doHttps apimethod nu auth Nothing
    handleJson _ gotjson = return (Right gotjson)

    getNextUrl l =
        if "rel=\"next\"" `isInfixOf` l
        then let s  = l
                 s' = Data.List.tail $ Data.List.dropWhile (/= '<') s
             in Just (Data.List.takeWhile (/= '>') s')
        else Nothing

doHttps :: BS.ByteString
           -> [Char]
           -> Maybe GithubAuth
           -> Maybe RequestBody
           -> IO (Either E.SomeException (Response LBS.ByteString))
doHttps reqMethod url auth body = do
  let reqBody = fromMaybe (RequestBodyBS $ BS.pack "") body
      reqHeaders = maybe [] getOAuth auth
      Just uri = parseUrl url
      request = uri { method = reqMethod
                    , secure = True
                    , port = 443
                    , requestBody = reqBody
                    , responseTimeout = Just 20000000
                    , requestHeaders = reqHeaders <>
                                       [("User-Agent", "github.hs/0.7.4")]
                                       <> [("Accept", "application/vnd.github.preview")]
                    , checkStatus = successOrMissing
                    }
      authRequest = getAuthRequest auth request

  (getResponse authRequest >>= return . Right) `E.catches` [
      -- Re-throw AsyncException, otherwise execution will not terminate on
      -- SIGINT (ctrl-c).  All AsyncExceptions are re-thrown (not just
      -- UserInterrupt) because all of them indicate severe conditions and
      -- should not occur during normal operation.
      E.Handler (\e -> E.throw (e :: E.AsyncException)),
      E.Handler (\e -> (return . Left) (e :: E.SomeException))
      ]
  where
    getAuthRequest (Just (GithubBasicAuth user pass)) = applyBasicAuth user pass
    getAuthRequest _ = id
    getOAuth (GithubOAuth token) = [(mk (BS.pack "Authorization"),
                                     BS.pack ("token " ++ token))]
    getOAuth _ = []
    getResponse request = withManager $ \manager -> httpLbs request manager
#if MIN_VERSION_http_conduit(1, 9, 0)
    successOrMissing s@(Status sci _) hs cookiejar
#else
    successOrMissing s@(Status sci _) hs
#endif
      | (200 <= sci && sci < 300) || sci == 404 = Nothing
#if MIN_VERSION_http_conduit(1, 9, 0)
      | otherwise = Just $ E.toException $ StatusCodeException s hs cookiejar
#else
      | otherwise = Just $ E.toException $ StatusCodeException s hs
#endif

doHttpsStatus :: BS.ByteString -> String -> GithubAuth -> Maybe RequestBody -> IO (Either Error Status)
doHttpsStatus reqMethod url auth payload = do
  result <- doHttps reqMethod url (Just auth) payload
  case result of
    Left e -> return (Left (HTTPConnectionError e))
    Right resp ->
      let status = responseStatus resp
          headers = responseHeaders resp
      in if status == notFound404
            -- doHttps silently absorbs 404 errors, but for this operation
            -- we want the user to know if they've tried to delete a
            -- non-existent repository
         then return (Left (HTTPConnectionError
                            (E.toException
                             (StatusCodeException status headers
#if MIN_VERSION_http_conduit(1, 9, 0)
                                 (responseCookieJar resp)
#endif
                                 ))))
             else return (Right status)

parseJsonRaw :: LBS.ByteString -> Either Error Value
parseJsonRaw jsonString =
  let parsed = parse json jsonString in
  case parsed of
       Data.Attoparsec.ByteString.Lazy.Done _ jsonResult -> Right jsonResult
       (Fail _ _ e) -> Left $ ParseError e

jsonResultToE :: Show b => LBS.ByteString -> Data.Aeson.Result b
              -> Either Error b
jsonResultToE jsonString result = case result of
    Success s -> Right s
    Error e   -> Left $ JsonError $
                 e ++ " on the JSON: " ++ LBS.unpack jsonString

parseJson :: (FromJSON b, Show b) => LBS.ByteString -> Either Error b
parseJson jsonString = either Left (jsonResultToE jsonString . fromJSON)
                              (parseJsonRaw jsonString)


text:
package net.inference.database;

import com.j256.ormlite.support.ConnectionSource;

/**
 * Date: 12/21/2014
 * Time: 9:33 PM
 *
 * @author xanderblinov
 */
public interface IDatabaseApi
{

	IArticleApi article();

	IAuthorApi author();

	IClusterApi cluster();

	IEvolutionApi evolution();

	IAuthorArticleApi authorArticle();

	IAuthorCompanyApi authorCompany();

	ICompanyApi company();

	IPrimitiveAuthorApi primitiveAuthor();

	IPrimitiveTermApi primterm();

	IPrimitiveTermToPrimitiveTermApi primTermToTerm();

	ITermApi term();

	/**
	 * Init database and table
	 */
	public void onStart();

	/**
	 * release connection etc.
	 */
	public void onStop();

	ConnectionSource getConnection();

}


text:
package ml.iamwhatiam.tao.util;

import org.junit.Assert;
import org.junit.Test;

public class ObjectUtilsTest {

	@Test
	public void testEquals() {
		Object a = new Object();
		Assert.assertEquals(a, a);
		Object b = new Object();
		if(a.equals(b)) {
			Assert.assertEquals(b, a);
			Assert.assertEquals(a.hashCode(), b.hashCode());
		}
		Object c = new Object();
		if(a.equals(b) && b.equals(c)) {
			Assert.assertEquals(a, c);
			Assert.assertEquals(a.hashCode(), c.hashCode());
		}
		Object d = new Object();
		boolean result = a.equals(d);
		int i = 0;
		while(i < 100) {
			Assert.assertTrue(a.equals(d) == result);
			i++;
		}
		if(a != null)
			Assert.assertFalse(a.equals(null));
	}

}


text:
<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| admin\_enabled | Whether the VLAN attachment is enabled or disabled | `bool` | `true` | no |
| bandwidth | Provisioned bandwidth capacity for the interconnect attachment | `string` | `"BPS_10G"` | no |
| candidate\_subnets | Up to 16 candidate prefixes that can be used to restrict the allocation of cloudRouterIpAddress and customerRouterIpAddress for this attachment. All prefixes must be within link-local address space (169.254.0.0/16) and must be /29 or shorter (/28, /27, etc). | `list(string)` | `null` | no |
| description | An optional description of this resource | `string` | `null` | no |
| interconnect | URL of the underlying Interconnect object that this attachment's traffic will traverse through. | `string` | n/a | yes |
| interface | Interface to deploy for this attachment. | `any` | n/a | yes |
| mtu | Maximum Transmission Unit (MTU), in bytes, of packets passing through this interconnect attachment. Currently, only 1440 and 1500 are allowed. If not specified, the value will default to 1440. | `string` | `null` | no |
| name | The name of the interconnect attachment | `string` | n/a | yes |
| peer | BGP Peer for this attachment. | `any` | n/a | yes |
| project | The project ID to deploy to | `string` | n/a | yes |
| region | Region where the attachment resides | `string` | n/a | yes |
| router | Name of the router the attachment resides | `string` | n/a | yes |
| type | The type of InterconnectAttachment you wish to create | `string` | `"DEDICATED"` | no |
| vlan\_tag8021q | The IEEE 802.1Q VLAN tag for this attachment, in the range 2-4094. | `string` | `null` | no |

## Outputs

| Name | Description |
|------|-------------|
| attachment | The created attachment |
| customer\_router\_ip\_address | IPv4 address + prefix length to be configured on the customer router subinterface for this interconnect attachment. |

<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->


text:
package com.diablominer.DiabloMiner;

public class DiabloMinerFatalException extends Exception {
	public DiabloMinerFatalException(DiabloMiner diabloMiner, String reason) {
		super(reason);
		diabloMiner.error(reason);
		diabloMiner.halt();
	}

	private static final long serialVersionUID = -9022549833049053386L;
}


text:
/* tslint:disable:max-file-line-count */
import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';

import { DateFormatter } from './date-formatter';

// const MIN_DATE:Date = void 0;
// const MAX_DATE:Date = void 0;
// const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

/*
 const KEYS = {
 13: 'enter',
 32: 'space',
 33: 'pageup',
 34: 'pagedown',
 35: 'end',
 36: 'home',
 37: 'left',
 38: 'up',
 39: 'right',
 40: 'down'
 };
 */

@Component({
  selector: 'datepicker-inner',
  template: `
    <div *ngIf="datepickerMode" class="well well-sm bg-faded p-a card" role="application" ><!--<!–ng-keydown="keydown($event)"–>-->
      <ng-content></ng-content>
    </div>
  `
})
export class DatePickerInnerComponent implements OnInit, OnChanges {
  @Input() public datepickerMode: string;
  @Input() public startingDay: number;
  @Input() public yearRange: number;

  @Input() public minDate: Date;
  @Input() public maxDate: Date;
  @Input() public minMode: string;
  @Input() public maxMode: string;
  @Input() public showWeeks: boolean;
  @Input() public formatDay: string;
  @Input() public formatMonth: string;
  @Input() public formatYear: string;
  @Input() public formatDayHeader: string;
  @Input() public formatDayTitle: string;
  @Input() public formatMonthTitle: string;
  @Input() public onlyCurrentMonth: boolean;
  @Input() public shortcutPropagation: boolean;
  @Input() public customClass: { date: Date, mode: string, clazz: string }[];
  @Input() public monthColLimit: number;
  @Input() public yearColLimit: number;
  @Input() public dateDisabled: { date: Date, mode: string }[];
  @Input() public initDate: Date;

  @Output() public selectionDone: EventEmitter<Date> = new EventEmitter<Date>(undefined);

  @Output() public update: EventEmitter<Date> = new EventEmitter<Date>(false);

  @Output() public activeDateChange: EventEmitter<Date> = new EventEmitter<Date>(undefined);

  public stepDay: any = {};
  public stepMonth: any = {};
  public stepYear: any = {};

  protected modes: string[] = ['day', 'month', 'year'];
  protected dateFormatter: DateFormatter = new DateFormatter();
  protected uniqueId: string;
  protected _activeDate: Date;
  protected selectedDate: Date;
  protected activeDateId: string;

  protected refreshViewHandlerDay: Function;
  protected compareHandlerDay: Function;
  protected refreshViewHandlerMonth: Function;
  protected compareHandlerMonth: Function;
  protected refreshViewHandlerYear: Function;
  protected compareHandlerYear: Function;

  @Input()
  public get activeDate(): Date {
    return this._activeDate;
  }

  public set activeDate(value: Date) {
    this._activeDate = value;
  }

  // todo: add formatter value to Date object
  public ngOnInit(): void {
    // todo: use date for unique value
    this.uniqueId = 'datepicker-' + '-' + Math.floor(Math.random() * 10000);

    if (this.initDate) {
      this.activeDate = this.initDate;
      this.selectedDate = new Date(this.activeDate.valueOf() as number);
      this.update.emit(this.activeDate);
    } else if (this.activeDate === undefined) {
      this.activeDate = new Date();
    }
  }

  // this.refreshView should be called here to reflect the changes on the fly
  // tslint:disable-next-line:no-unused-variable
  public ngOnChanges(changes: SimpleChanges): void {
    this.refreshView();
    this.checkIfActiveDateGotUpdated(changes['activeDate']);
  }

  // Check if activeDate has been update and then emit the activeDateChange with the new date
  private checkIfActiveDateGotUpdated(activeDate: any): void {
		if (activeDate && !activeDate.firstChange) {
			let previousValue = activeDate.previousValue;
			if (previousValue && previousValue instanceof Date && previousValue.getTime() !== activeDate.currentValue.getTime()) {
				this.activeDateChange.emit(this.activeDate);
			}
		}
  }

  public setCompareHandler(handler: Function, type: string): void {
    if (type === 'day') {
      this.compareHandlerDay = handler;
    }

    if (type === 'month') {
      this.compareHandlerMonth = handler;
    }

    if (type === 'year') {
      this.compareHandlerYear = handler;
    }
  }

  public compare(date1: Date, date2: Date): number | undefined {
    if (date1 === undefined || date2 === undefined) {
      return undefined;
    }

    if (this.datepickerMode === 'day' && this.compareHandlerDay) {
      return this.compareHandlerDay(date1, date2);
    }

    if (this.datepickerMode === 'month' && this.compareHandlerMonth) {
      return this.compareHandlerMonth(date1, date2);
    }

    if (this.datepickerMode === 'year' && this.compareHandlerYear) {
      return this.compareHandlerYear(date1, date2);
    }

    return void 0;
  }

  public setRefreshViewHandler(handler: Function, type: string): void {
    if (type === 'day') {
      this.refreshViewHandlerDay = handler;
    }

    if (type === 'month') {
      this.refreshViewHandlerMonth = handler;
    }

    if (type === 'year') {
      this.refreshViewHandlerYear = handler;
    }
  }

  public refreshView(): void {
    if (this.datepickerMode === 'day' && this.refreshViewHandlerDay) {
      this.refreshViewHandlerDay();
    }

    if (this.datepickerMode === 'month' && this.refreshViewHandlerMonth) {
      this.refreshViewHandlerMonth();
    }

    if (this.datepickerMode === 'year' && this.refreshViewHandlerYear) {
      this.refreshViewHandlerYear();
    }
  }

  public dateFilter(date: Date, format: string): string {
    return this.dateFormatter.format(date, format);
  }

  public isActive(dateObject: any): boolean {
    if (this.compare(dateObject.date, this.activeDate) === 0) {
      this.activeDateId = dateObject.uid;
      return true;
    }

    return false;
  }

  public createDateObject(date: Date, format: string): any {
    let dateObject: any = {};
    dateObject.date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    dateObject.label = this.dateFilter(date, format);
    dateObject.selected = this.compare(date, this.selectedDate) === 0;
    dateObject.disabled = this.isDisabled(date);
    dateObject.current = this.compare(date, new Date()) === 0;
    dateObject.customClass = this.getCustomClassForDate(dateObject.date);
    return dateObject;
  }

  public split(arr: any[], size: number): any[] {
    let arrays: any[] = [];
    while (arr.length > 0) {
      arrays.push(arr.splice(0, size));
    }
    return arrays;
  }

  // Fix a hard-reproducible bug with timezones
  // The bug depends on OS, browser, current timezone and current date
  // i.e.
  // var date = new Date(2014, 0, 1);
  // console.log(date.getFullYear(), date.getMonth(), date.getDate(),
  // date.getHours()); can result in "2013 11 31 23" because of the bug.
  public fixTimeZone(date: Date): Date {
    let hours = date.getHours();
    return new Date(date.getFullYear(), date.getMonth(), date.getDate(), hours === 23 ? hours + 2 : 0);
  }

  public select(date: Date, isManual: boolean = true): void {
    if (this.datepickerMode === this.minMode) {
      if (!this.activeDate) {
        this.activeDate = new Date(0, 0, 0, 0, 0, 0, 0);
      }

      this.activeDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      if (isManual) {
        this.selectionDone.emit(this.activeDate);
      }
    } else {
      this.activeDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      if (isManual) {
        this.datepickerMode = this.modes[this.modes.indexOf(this.datepickerMode) - 1];
      }
    }

    this.selectedDate = new Date(this.activeDate.valueOf() as number);
    this.update.emit(this.activeDate);
    this.refreshView();
  }

  public move(direction: number): void {
    let expectedStep: any;
    if (this.datepickerMode === 'day') {
      expectedStep = this.stepDay;
    }

    if (this.datepickerMode === 'month') {
      expectedStep = this.stepMonth;
    }

    if (this.datepickerMode === 'year') {
      expectedStep = this.stepYear;
    }

    if (expectedStep) {
      let year = this.activeDate.getFullYear() + direction * (expectedStep.years || 0);
      let month = this.activeDate.getMonth() + direction * (expectedStep.months || 0);
      this.activeDate = new Date(year, month, 1);

      this.refreshView();
      this.activeDateChange.emit(this.activeDate);
    }
  }

  public toggleMode(direction: number): void {
    direction = direction || 1;

    if ((this.datepickerMode === this.maxMode && direction === 1) ||
      (this.datepickerMode === this.minMode && direction === -1)) {
      return;
    }

    this.datepickerMode = this.modes[this.modes.indexOf(this.datepickerMode) + direction];
    this.refreshView();
  }

  protected getCustomClassForDate(date: Date): string {
    if (!this.customClass) {
      return '';
    }
    // todo: build a hash of custom classes, it will work faster
    const customClassObject: { date: Date, mode: string, clazz: string } = this.customClass
      .find((customClass: any) => {
        return customClass.date.valueOf() === date.valueOf() &&
          customClass.mode === this.datepickerMode;
      }, this);
    return customClassObject === undefined ? '' : customClassObject.clazz;
  }

  protected compareDateDisabled(date1Disabled: { date: Date, mode: string }, date2: Date): number {
    if (date1Disabled === undefined || date2 === undefined) {
      return undefined;
    }

    if (date1Disabled.mode === 'day' && this.compareHandlerDay) {
      return this.compareHandlerDay(date1Disabled.date, date2);
    }

    if (date1Disabled.mode === 'month' && this.compareHandlerMonth) {
      return this.compareHandlerMonth(date1Disabled.date, date2);
    }

    if (date1Disabled.mode === 'year' && this.compareHandlerYear) {
      return this.compareHandlerYear(date1Disabled.date, date2);
    }

    return undefined;
  }

  protected isDisabled(date: Date): boolean {
    let isDateDisabled: boolean = false;
    if (this.dateDisabled) {
      this.dateDisabled.forEach((disabledDate: { date: Date, mode: string }) => {
        if (this.compareDateDisabled(disabledDate, date) === 0) {
          isDateDisabled = true;
        }
      });
    }

    return (isDateDisabled || (this.minDate && this.compare(date, this.minDate) < 0) ||
      (this.maxDate && this.compare(date, this.maxDate) > 0));
  }
}


text:
import * as gulp from 'gulp'
import * as project from 'ml-project'
import * as s from 'typescript-schema'
import * as m from 'ml-admin'
import {RetailDemo} from './lib/definition'
import * as u from 'ml-uservices'
import * as path from 'path'
var mocha = require('gulp-mocha')
var assign = require('lodash.assign')

////
import {Wirings, generateWiring, resolveWiring} from 'tschuss'
///

gulp.task('build-schema', buildSchema)

gulp.task('build-database', buildDatabase)

gulp.task('clean-database', cleanDatabase)

gulp.task('test', test)

let config = <project.Config>require('../../config.json')
let packageJson = require('../package.json')

export function buildSchema() {
  return gulp
    .src('lib/**/*.ts')
    .pipe(project.buildJson({
      definition: new RetailDemo(config),
      config: config,
      packageName: packageJson.name
    }))
    .pipe(gulp.dest('dist/json'))
}

export function buildDatabase() {
  let rawSchema = <s.RawSchema>(<s.RawSchema>require('./json/schema.json')).concat(require('../../common/dist/json/schema.json'), require('../../app-server/dist/json/schema.json'))
  /*let rawSchema = <s.RawSchema>assign(require('./json/schema.json'), require('../../common/dist/json/schema.json'))
  rawSchema = <s.RawSchema>assign(rawSchema, require('../../app-server/dist/json/schema.json'))*/

  return gulp
    .src(require('../tsconfig.json').files)
    .pipe(project.buildDatabase({
      base: path.join(process.cwd(), 'lib'),
      schema: rawSchema,
      config: config,
      packageName: packageJson.name,
      model: <m.Model>require('./json/database-model.json')
    }))
    .pipe(gulp.dest('dist'))
}

export function cleanDatabase() {
  return gulp
    .src(require('../tsconfig.json').files)
    .pipe(project.cleanDatabase({
      base: path.join(process.cwd(), 'lib'),
      schema: <s.RawSchema>require('./json/schema.json'),
      config: config,
      model: <m.Model>require('./json/database-model.json')
    }))
    .pipe(gulp.dest('dist'))
}

export function test() {
  let rawSchema = <s.RawSchema>(<s.RawSchema>require('./json/schema.json')).concat(require('../../common/dist/json/schema.json'), require('../../app-server/dist/json/schema.json'))

//  let rawSchema = <s.RawSchema>assign(require('./json/schema.json'), require('../../common/dist/json/schema.json'))
//  rawSchema = <s.RawSchema>assign(rawSchema, require('../../app-server/dist/json/schema.json'))
  let schema = s.rawSchemaToSchema(rawSchema)

  console.log(Object.keys(schema))

  /*let gw = generateWiring(schema)
  console.log(gw)
  let wirings = resolveWiring(gw)
  console.log(wirings)*/

//  return gulp.src('./dist/tests/**/*.js', { read: false })
//    .pipe(mocha());
}


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

<title>S-Index</title>
<meta name="date" content="2015-09-01">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

C E F G R S T X

S

S3URIResolver - Class in com.elsevier.spark_xml_utils.xslt

URI Resolver that will be used by XLTProcessor when resolving xsl:import and
 xsl:include statements.

S3URIResolver() - Constructor for class com.elsevier.spark_xml_utils.xslt.S3URIResolver

C E F G R S T X

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
using UnityEngine;
using System.Collections;

/// <summary>
///
/// </summary>
public class StartGame : MonoBehaviour
{
    private GUIStyle centeredStyle;
    public Font font;
    public GameJoltAPIManager api;

    // Use this for initialization
    void Awake()
    {
        api = GameObject.Find("_GameJoltAPIManager").GetComponent<GameJoltAPIManager>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            api.gameStarted = true;
            Application.LoadLevel(1);
        }
    }

    void OnGUI()
    {
        if (!api.gameStarted)
        {
            centeredStyle = GUI.skin.GetStyle("Label");
            centeredStyle.alignment = TextAnchor.UpperCenter;
            centeredStyle.font = font;
            camera.backgroundColor = new Color32(0, 0, 0, 0);

            GUI.Label(new Rect((Screen.width / 2) - 400, Screen.height / 2 - 250, 800, 500), "<color=white><size=100>YOGOB</size></color>", centeredStyle);
            GUI.Label(new Rect((Screen.width / 2) - 400, Screen.height / 2 - 52, 800, 500), "<color=red><size=35>You only got one button</size></color>", centeredStyle);
            GUI.Label(new Rect((Screen.width / 2) - 400, Screen.height / 2 + 200, 800, 500), "<color=white><size=15>Press SPACE to start the game</size></color>", centeredStyle);

            GUI.Label(new Rect((Screen.width / 2) - 400, Screen.height / 2 + 40, 800, 500), "<color=white><size=10>a game made for #LD28 by</size></color>", centeredStyle);
            GUI.Label(new Rect((Screen.width / 2) - 400, Screen.height / 2 + 60, 800, 500), "<color=white><size=10>Zerano & nyrrrr</size></color>", centeredStyle);

            GUI.Label(new Rect((Screen.width / 2) - 400, Screen.height / 2 + 110, 800, 500), "<color=white><size=10>Music by: Tommy Bulpa</size></color>", centeredStyle);
        }
    }
}


text:
#import <Foundation/Foundation.h>

#import "RTCVideoFrame.h"

NS_ASSUME_NONNULL_BEGIN

/**
 * RTCVideoViewShading provides a way for apps to customize the OpenGL(ES shaders
 * used in rendering for the RTCEAGLVideoView/RTCNSGLVideoView.
 */
RTC_OBJC_EXPORT
@protocol RTC_OBJC_TYPE
(RTCVideoViewShading)<NSObject>

    /** Callback for I420 frames. Each plane is given as a texture. */
    - (void)applyShadingForFrameWithWidth : (int)width height : (int)height rotation
    : (RTCVideoRotation)rotation yPlane : (GLuint)yPlane uPlane : (GLuint)uPlane vPlane
    : (GLuint)vPlane;

/** Callback for NV12 frames. Each plane is given as a texture. */
- (void)applyShadingForFrameWithWidth:(int)width
                               height:(int)height
                             rotation:(RTCVideoRotation)rotation
                               yPlane:(GLuint)yPlane
                              uvPlane:(GLuint)uvPlane;

@end

NS_ASSUME_NONNULL_END


text:
package org.apache.carbondata.core.statusmanager;

import java.io.Serializable;
import java.util.Objects;

/**
 * The data file format supported in carbondata project
 */
public class FileFormat implements Serializable {

  public static final FileFormat COLUMNAR_V3 = new FileFormat("COLUMNAR_V3", 0);
  public static final FileFormat ROW_V1 = new FileFormat("ROW_V1", 1);

  private String format;

  private int ordinal;

  public FileFormat(String format) {
    this.format = format.toLowerCase();
  }

  public FileFormat(String format, int ordinal) {
    this.format = format.toLowerCase();
    this.ordinal = ordinal;
  }

  public int ordinal() {
    return ordinal;
  }

  public static FileFormat getByOrdinal(int ordinal) {
    if (ordinal < 0) {
      throw new IllegalArgumentException("Argument [ordinal] is less than 0.");
    }
    switch (ordinal) {
      case 0:
        return COLUMNAR_V3;
      case 1:
        return ROW_V1;
    }

    return COLUMNAR_V3;
  }

  public boolean isCarbonFormat() {
    return (this.format.equalsIgnoreCase("COLUMNAR_V3") ||
        this.format.equalsIgnoreCase("ROW_V1"));
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    FileFormat that = (FileFormat) o;
    return Objects.equals(format, that.format);
  }

  @Override
  public int hashCode() {
    return Objects.hash(format);
  }

  @Override
  public String toString() {
    return format;
  }
}


text:
package edu.ucla.nesl.sensorsafe.auth;

import java.io.IOException;

import javax.annotation.Priority;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.Priorities;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.DynamicFeature;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.glassfish.jersey.server.model.AnnotatedMethod;

/**
 * A {@link DynamicFeature} supporting the {@code javax.annotation.security.RolesAllowed},
 * {@code javax.annotation.security.PermitAll} and {@code javax.annotation.security.DenyAll}
 * on resource methods and sub-resource methods.
 *

 * The {@link javax.ws.rs.core.SecurityContext} is utilized, using the
 * {@link javax.ws.rs.core.SecurityContext#isUserInRole(String) } method,
 * to ascertain if the user is in one
 * of the roles declared in by a {@code @RolesAllowed}. If a user is in none of
 * the declared roles then a 403 (Forbidden) response is returned.
 *

 * If the {@code @DenyAll} annotation is declared then a 403 (Forbidden) response
 * is returned.
 *

 * If the {@code @PermitAll} annotation is declared and is not overridden then
 * this filter will not be applied.
 *
 * @author Paul Sandoz (paul.sandoz at oracle.com)
 * @author Martin Matula (martin.matula at oracle.com)
 */
public class RolesAllowedDynamicFeature implements DynamicFeature {

    @Override
    public void configure(final ResourceInfo resourceInfo, final FeatureContext configuration) {
        AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());

        // DenyAll on the method take precedence over RolesAllowed and PermitAll
        if (am.isAnnotationPresent(DenyAll.class)) {
            configuration.register(new RolesAllowedRequestFilter());
            return;
        }

        // RolesAllowed on the method takes precedence over PermitAll
        RolesAllowed ra = am.getAnnotation(RolesAllowed.class);
        if (ra != null) {
            configuration.register(new RolesAllowedRequestFilter(ra.value()));
            return;
        }

        // PermitAll takes precedence over RolesAllowed on the class
        if (am.isAnnotationPresent(PermitAll.class)) {
            // Do nothing.
            return;
        }

        // DenyAll can't be attached to classes

        // RolesAllowed on the class takes precedence over PermitAll
        ra = resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
        if (ra != null) {
            configuration.register(new RolesAllowedRequestFilter(ra.value()));
        }
    }

    @Priority(Priorities.AUTHORIZATION) // authorization filter - should go after any authentication filters
    private static class RolesAllowedRequestFilter implements ContainerRequestFilter {
        private final boolean denyAll;
        private final String[] rolesAllowed;

        RolesAllowedRequestFilter() {
            this.denyAll = true;
            this.rolesAllowed = null;
        }

        RolesAllowedRequestFilter(String[] rolesAllowed) {
            this.denyAll = false;
            this.rolesAllowed = (rolesAllowed != null) ? rolesAllowed : new String[] {};
        }

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            if (!denyAll) {
                for (String role : rolesAllowed) {
                    if (requestContext.getSecurityContext().isUserInRole(role)) {
                        return;
                    }
                }
            }

            boolean isApikeyExist = false;
            for (String apikeyHeader: AuthenticationFilter.API_KEY_HEADERS) {
            	String value = requestContext.getHeaderString(apikeyHeader);
            	if (value != null) {
            		isApikeyExist = true;
            	}
            }

            // If request doesn't contain any authentication header, make the browser pop up HTTP BASIC login window.
            if (!isApikeyExist && requestContext.getHeaderString(AuthenticationFilter.AUTHORIZATION_HEADER) == null)
            	throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").build());
            else
            	throw new ForbiddenException();
        }
    }
}


text:
CameraType CameraNode::getType() const {
	return this->type;
}

const char* CameraNode::getName() const {
	return this->name;
}

CameraNode::CameraNode( Camera* const camera )
	: NodeLink( camera ), type( camera->getType() ), name( camera->getName() ) { }

CameraNode::~CameraNode() { }


text:
404!

The page you are looking for has not been found!

The page you are looking for might have been removed, or unavailable.

 Maybe you could try a search:

    <form action="#" class="form-horizontal">

            <input type="text" class="form-control typeahead" placeholder="Search for page ">
            <button type="submit" class="btn btn-theme fa fa-search form-control-feedback"></button>

    </form>


text:
package net.meisen.general.genmisc.raster.definition;

/**
 * This enumeration defines the different types of a
 * RasterModelEntry
 *
 * @author pmeisen
 *
 */
public enum RasterModelEntryType {
	/**
	 * The ModelEntry is marked to be a value
	 */
	VALUE,
	/**
	 * The ModelEntry is marked to be a grouping value
	 */
	GROUP,
	/**
	 * The ModelEntry is the start of the interval
	 */
	INTERVALSTART,
	/**
	 * The ModelEntry is the end of the interval
	 */
	INTERVALEND;
}


text:
layout:     post-dark
title:      "ES6 Introduction - Part 1"
subtitle:   "A brief overview to understand new features in ES6, including Strings, Objects, let"
date:       2015-06-09 20:00:00
author:     "Aditya Pratap Singh"
header-img: "img/dist/home-bg.jpg"
---

Better String Support:

The new addition to deck of ES 6 string methods are:

 includes()-  returns true if given text is found anywhere inside the string else false

 startsWith() –  returns true if given text is found at the beginning of the string else false

 endsWith()-  returns true if given text is found at the end of the string else false

 Repeat() -  Accepts a single integer argument for the no of times to repeat the string

Better Object utilities:

Object.is(): Better comparison using Object.is() and avoids the inaccuracy in identically equals operator (===) for below scenarios:

 (===) considers +0 and -0 as equal while Object.is() does not

 (===) returns (NaN === NaN) as false while Object.is treats all NaN as same and returns true

Block Bindings using let:
 In most languages variables are created when declared while in JavaScript variables are hoisted at the top of function regardless of declaration.
variable hoisting in JavaScript causes in bugs if we don't understand the underlying logic of hoisting.

To avoid this scenario and introduce the block level scope, ES 6 has introduced the let keyword.

The let keyword scopes the variable to current code block.

var:

let:

 One of the most important application of let can be observed in for loops where the loop control variable persists, even after the loop ends.

ES5:


text:
package opticnav.ardroid.connection;

import android.os.Handler;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

import java.io.EOFException;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * ServerCommandQueue ensures that server commands are run in sequence. This is meant to prevent race conditions
 * created by executing commands in multiple threads simultaneously.
 */
public final class ServerCommandQueue implements Runnable {
    private static final XLogger LOG = XLoggerFactory.getXLogger(ServerCommandQueue.class);
    private final Handler handler;
    private final FinishedEvent finishedEvent;
    private boolean finishing;

    public interface Command<E> {
        public abstract E background() throws IOException;
        public void ui(E result) throws Exception;
    }

    public interface FinishedEvent {
        public void finished();
    }

    private final BlockingQueue<Command<?>> commands;

    public ServerCommandQueue(Handler handler, final FinishedEvent finishedEvent) {
        this.handler = handler;
        this.commands = new LinkedBlockingDeque<Command<?>>();
        this.finishedEvent = finishedEvent;
        this.finishing = false;
    }

    @Override
    public void run() {
        try {
            while (!finishing && !Thread.currentThread().isInterrupted()) {
                final Command command = this.commands.take();
                LOG.debug("Running background command...: " + command);
                final Object result = command.background();
                LOG.debug("Finished background command: " + command);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            command.ui(result);
                        } catch (Exception e) {
                            // this is fatal. Make the application crash with it.
                            throw new RuntimeException(e);
                        }
                    }
                });
            }
        } catch (InterruptedException e) {
            // do nothing - thread was just interrupted
            LOG.debug("Interrupted");
        } catch (EOFException e) {
            // connection ended, don't worry about it
            LOG.debug("Connection ended");
        } catch (IOException e) {
            LOG.catching(e);
        } finally {
            this.finishedEvent.finished();
        }
    }

    public void enqueue(Command command) {
        try {
            this.commands.put(command);
        } catch (InterruptedException e) {
            // re-interrupt the current thread
            Thread.currentThread().interrupt();
        }
    }

    public void finish() {
        enqueue(new Command<Void>() {
            @Override
            public Void background() throws IOException {
                finishing = true;
                return null;
            }

            @Override
            public void ui(Void result) {
            }
        });
    }
}


text:
package org.tigris.subversion.svnclientadapter.basictests;

import java.io.File;
import java.io.FileOutputStream;

import org.tigris.subversion.svnclientadapter.SVNNodeKind;
import org.tigris.subversion.svnclientadapter.SVNStatusKind;
import org.tigris.subversion.svnclientadapter.testUtils.OneTest;
import org.tigris.subversion.svnclientadapter.testUtils.SVNTest;

public class AddTest extends SVNTest {

	/**
	 * test the basis SVNClient.add functionality with files that should be
	 * ignored
	 * @throws Throwable
	 */
	public void testBasicAddIgnores() throws Throwable
	{
	    // create working copy
	    OneTest thisTest = new OneTest("basicAddIgnores",getGreekTestConfig());

	    // create dir
	    File dir = new File(thisTest.getWorkingCopy(), "dir");
	    dir.mkdir();

	    // create dir/foo.c
	    File fileC = new File(dir, "foo.c");
	    new FileOutputStream(fileC).close();

	    // create dir/foo.o (should be ignored)
	    File fileO = new File(dir, "foo.o");
	    new FileOutputStream(fileO).close();

	    // add dir
	    client.addDirectory(dir, true);
	    thisTest.getExpectedWC().addItem("dir", null);
	    thisTest.getExpectedWC().setItemTextStatus("dir",SVNStatusKind.ADDED);
	    thisTest.getExpectedWC().addItem("dir/foo.c", "");
	    thisTest.getExpectedWC().setItemTextStatus("dir/foo.c",SVNStatusKind.ADDED);
	    thisTest.getExpectedWC().addItem("dir/foo.o", "");
	    thisTest.getExpectedWC().setItemTextStatus("dir/foo.o",SVNStatusKind.IGNORED);
        thisTest.getExpectedWC().setItemNodeKind("dir/foo.o", SVNNodeKind.UNKNOWN);

	    // test the working copy status
	    thisTest.checkStatusesExpectedWC();
	}

}


text:
using System;
using System.Linq;
using Xunit;

namespace FluentCassandra
{
	public class GuidGeneratorTest
	{
		[Fact]
		public void Type1Check()
		{
			// arrange
			var expected = GuidVersion.TimeBased;
			var guid = GuidGenerator.GenerateTimeBasedGuid();

			// act
			var actual = guid.GetUuidVersion();

			// assert
			Assert.Equal(expected, actual);
		}

		[Fact]
		public void SanityType1Check()
		{
			// arrange
			var expected = GuidVersion.TimeBased;
			var guid = Guid.NewGuid();

			// act
			var actual = guid.GetUuidVersion();

			// assert
			Assert.NotEqual(expected, actual);
		}

		[Fact]
		public void GetDateTimeUnspecified()
		{
			// arrange
			var expected = new DateTime(1980, 3, 14, 12, 23, 42, 112, DateTimeKind.Unspecified);
			var guid = GuidGenerator.GenerateTimeBasedGuid(expected);

			// act
			var actual = GuidGenerator.GetDateTime(guid).ToLocalTime();

			// assert
			Assert.Equal(expected, actual);
		}

		[Fact]
		public void GetDateTimeLocal()
		{
			// arrange
			var expected = new DateTime(1980, 3, 14, 12, 23, 42, 112, DateTimeKind.Local);
			var guid = GuidGenerator.GenerateTimeBasedGuid(expected);

			// act
			var actual = GuidGenerator.GetLocalDateTime(guid);

			// assert
			Assert.Equal(expected, actual);
		}

		[Fact]
		public void GetDateTimeUtc()
		{
			// arrange
			var expected = new DateTime(1980, 3, 14, 12, 23, 42, 112, DateTimeKind.Utc);
			var guid = GuidGenerator.GenerateTimeBasedGuid(expected);

			// act
			var actual = GuidGenerator.GetUtcDateTime(guid);

			// assert
			Assert.Equal(expected, actual);
		}

		[Fact]
		public void GetDateTimeOffset()
		{
			// arrange
			var expected = new DateTimeOffset(1980, 3, 14, 12, 23, 42, 112, TimeSpan.Zero);
			var guid = GuidGenerator.GenerateTimeBasedGuid(expected);

			// act
			var actual = GuidGenerator.GetDateTimeOffset(guid);

			// assert
			Assert.Equal(expected, actual);
		}

		[Fact]
		public void DoesNotCreateDuplicateWhenTimeHasNotPassed()
		{
			// arrange
			DateTimeOffset currentTime = DateTimeOffset.UtcNow;

			TimestampHelper.UtcNow = () => currentTime;  //make sure all calls will return the same time
			Guid firstGuid = GuidGenerator.GenerateTimeBasedGuid();

			// act
			Guid secondGuid = GuidGenerator.GenerateTimeBasedGuid();

			// assert
			Assert.True(firstGuid != secondGuid, "first: " + firstGuid + " second: " + secondGuid);
			//Assert.NotEqual(firstGuid,secondGuid);
		}

		[Fact]
		public void ClockSequenceChangesWhenTimeMovesBackward()
		{
			Func<Guid, short> getClockSequence  = (guid) => {
				byte[] clockSequenceBytes = new byte[2];
				Array.Copy(guid.ToByteArray(), 8, clockSequenceBytes, 0, 2);
				return BitConverter.ToInt16(clockSequenceBytes, 0);
			};

			// arrange
			DateTimeOffset currentTime = DateTimeOffset.UtcNow;

			TimestampHelper.UtcNow = () => currentTime;
			Guid firstGuid = GuidGenerator.GenerateTimeBasedGuid();

			// act
			TimestampHelper.UtcNow = () => currentTime.AddTicks(-1);  //make sure clock went backwards
			Guid secondGuid = GuidGenerator.GenerateTimeBasedGuid();

			// assert
			//clock sequence is not equal
			Assert.NotEqual(getClockSequence(firstGuid), getClockSequence(secondGuid));
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- log4j2 config file used when running under Maven -->
<Configuration>
    <Appenders>
        <File name="file" fileName="target/surefire-reports/test.log">
            <PatternLayout>
                <Pattern>%d %-5p %X [%c{1}] - %m{nolookups}%n</Pattern>
            </PatternLayout>
        </File>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="file"/>
        </Root>
    </Loggers>
</Configuration>


text:
======
Mohawk
======
.. image:: https://img.shields.io/pypi/v/mohawk.svg
    :target: https://pypi.python.org/pypi/mohawk
    :alt: Latest PyPI release

.. image:: https://img.shields.io/pypi/dm/mohawk.svg
    :target: https://pypi.python.org/pypi/mohawk
    :alt: PyPI monthly download stats

.. image:: https://travis-ci.org/kumar303/mohawk.svg?branch=master
    :target: https://travis-ci.org/kumar303/mohawk
    :alt: Travis master branch status

.. image:: https://readthedocs.org/projects/mohawk/badge/?version=latest
    :target: https://mohawk.readthedocs.io/en/latest/?badge=latest
    :alt: Documentation status

Mohawk is an alternate Python implementation of the
`Hawk HTTP authorization scheme`_.

Hawk lets two parties securely communicate with each other using
messages signed by a shared key.
It is based on `HTTP MAC access authentication`_ (which
was based on parts of `OAuth 1.0`_).

The Mohawk API is a little different from that of the Node library
(i.e. `the living Hawk spec <https://github.com/hueniverse/hawk>`_).
It was redesigned to be more intuitive to developers, less prone to security problems, and more Pythonic.

Full documentation: https://mohawk.readthedocs.io/

.. _`Hawk HTTP authorization scheme`: https://github.com/hueniverse/hawk
.. _`HTTP MAC access authentication`: http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05
.. _`OAuth 1.0`: http://tools.ietf.org/html/rfc5849


text:
class Package < ActiveRecord::Base
  belongs_to :user
  has_many :stacktraces
  validates_uniqueness_of :package_id
  before_create :generate_secret

private
  def generate_secret
    # When creating Package objects, generate the secret
    if not self.secret or 0 == self.secret.length
      self.secret = SecureRandom.base64(30)
    end
  end
end


text:
package com.google.wave.api.data.converter.v21;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.wave.api.impl.EventMessageBundle;

import junit.framework.TestCase;

import org.waveprotocol.wave.model.conversation.Blips;
import org.waveprotocol.wave.model.conversation.Conversation;
import org.waveprotocol.wave.model.conversation.ConversationBlip;
import org.waveprotocol.wave.model.conversation.ConversationView;
import org.waveprotocol.wave.model.conversation.WaveBasedConversationView;
import org.waveprotocol.wave.model.document.operation.impl.DocInitializationBuilder;
import org.waveprotocol.wave.model.id.IdGenerator;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.testing.BasicFactories;
import org.waveprotocol.wave.model.testing.FakeIdGenerator;
import org.waveprotocol.wave.model.wave.Wavelet;
import org.waveprotocol.wave.model.wave.opbased.ObservableWaveView;

/**
 * Test cases for {@link EventDataConverterV21}.
 *
 */

public class EventDataConverterV21Test extends TestCase {

  private static final WaveId WAVE_ID = WaveId.of("example.com", "123");
  private static final WaveletId WAVELET_ID = WaveletId.of("example.com", "conv+root");

  public void testToBlipDataHandlesBlipWithEmptyDocument() throws Exception {
    Blips.init();

    Conversation conversation = makeConversation();

    Wavelet wavelet = mock(Wavelet.class);
    when(wavelet.getWaveId()).thenReturn(WAVE_ID);
    when(wavelet.getId()).thenReturn(WAVELET_ID);

    EventDataConverterV21 converter = new EventDataConverterV21();
    assertEquals("",
        converter.toBlipData(conversation.getRootThread().getFirstBlip(), wavelet,
            new EventMessageBundle(null, null)).getContent());
  }

  public void testFindBlipParent() {
    Conversation conversation = makeConversation();
    ConversationBlip first = conversation.getRootThread().getFirstBlip();
    ConversationBlip second = conversation.getRootThread().appendBlip();
    ConversationBlip reply = first.addReplyThread().appendBlip();
    ConversationBlip secondReply = reply.getThread().appendBlip();

    EventDataConverterV21 converter = new EventDataConverterV21();
    assertNull(converter.findBlipParent(first));
    assertSame(first, converter.findBlipParent(second));
    assertSame(first, converter.findBlipParent(reply));
    assertSame(reply, converter.findBlipParent(secondReply));
  }

  public void testFindBlipPreviousSibling() {
    Conversation conversation = makeConversation();
    ConversationBlip first = conversation.getRootThread().getFirstBlip();
    ConversationBlip second = conversation.getRootThread().appendBlip();
    ConversationBlip reply = first.addReplyThread().appendBlip();
    ConversationBlip secondReply = reply.getThread().appendBlip();

    assertNull(EventDataConverterV21.findPreviousSibling(first));
    assertSame(first, EventDataConverterV21.findPreviousSibling(second));
    assertNull(EventDataConverterV21.findPreviousSibling(reply));
    assertSame(reply, EventDataConverterV21.findPreviousSibling(secondReply));
  }

  public void testFindBlipNextSibling() {
    Conversation conversation = makeConversation();
    ConversationBlip first = conversation.getRootThread().getFirstBlip();
    ConversationBlip second = conversation.getRootThread().appendBlip();
    ConversationBlip reply = first.addReplyThread().appendBlip();
    ConversationBlip secondReply = reply.getThread().appendBlip();

    assertSame(second, EventDataConverterV21.findNextSibling(first));
    assertNull(EventDataConverterV21.findNextSibling(second));
    assertSame(secondReply, EventDataConverterV21.findNextSibling(reply));
    assertNull(EventDataConverterV21.findNextSibling(secondReply));
  }

  private static Conversation makeConversation() {
    IdGenerator idGenerator = FakeIdGenerator.create();
    ObservableWaveView waveView = BasicFactories.fakeWaveViewBuilder().with(idGenerator).build();
    ConversationView convView = WaveBasedConversationView.create(waveView, idGenerator);
    Conversation conversation = convView.createRoot();
    // Force empty document.
    conversation.getRootThread().appendBlip(new DocInitializationBuilder().build());
    return conversation;
  }
}


text:
{% extends "gentle/base.html" %}
{% load static %}
{% block title %}About{% endblock %}
{% block main %}

Matz Chromatiq

Junior Django programmer

Web Development

Need a website?
             Please hang up and send me a message in the Telegram.

Linux distro (Debian,Redhat,ArchLinux,etc).

Stack: Django, Bootstrap, JS, only Sass,Git.

{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/item_bg"
    android:layout_width="match_parent"
    android:layout_height="184dp"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="180dp">
        <TextView
            android:id="@id/news_item_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <ImageView
            android:id="@+id/type2_iv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:scaleType="fitXY"/>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorGrayTransparent">

            <TextView
                android:id="@+id/type2_title_tv"
                style="@style/item_tv_title"
                android:layout_width="220dp"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="8dp"
                android:layout_marginTop="65dp"
                android:gravity="center"
                android:maxLines="2"
                android:text="123123123123123123"
                android:textColor="@color/colorWhite"/>

            <TextView
                android:id="@+id/type2_game_name_tv"
                style="@style/item_tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/type2_title_tv"
                android:layout_centerInParent="true"
                android:layout_marginTop="8dp"
                android:gravity="center"
                android:text=" ★ ★ "
                android:textColor="@color/colorWhite"/>

            <TextView
                style="@style/item_tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@id/type2_game_name_tv"
                android:layout_marginRight="10dp"
                android:layout_toLeftOf="@id/type2_game_name_tv"
                android:gravity="center"
                android:text="@string/text_type2"
                android:textColor="@color/colorWhite"/>

            <TextView
                style="@style/item_tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@id/type2_game_name_tv"
                android:layout_marginLeft="10dp"
                android:layout_toRightOf="@id/type2_game_name_tv"
                android:gravity="center"
                android:text="@string/text_type2"
                android:textColor="@color/colorWhite"/>

        </RelativeLayout>
    </RelativeLayout>

    <include layout="@layout/divider_line"/>
</LinearLayout>


text:
var Category = require('../models/category').Category;
var ServiceProduct = require('../models/serviceproduct').ServiceProduct;
var Product = require('../models/product').Product;
var util = require('util');
var async = require('async');
var Workshop = require('../models/workshop').Workshop;
var mongoose = require('../lib/mongoose');
var postdata = require('postdata');
exports.get = function(req, res) {
	var type = req.params.type;
	console.log(type);
	if (type == "super") {
	    ServiceProduct.findSuperProducts(function(superproducts){
	        //console.log(superproducts);
	        res.render('managerservice', {
	        	title: "Супертовары",
	        	product: superproducts
	        })
	    })
	}
	if (type == "best") {
		ServiceProduct.findBestProducts(function(superproducts){
	        //console.log(superproducts);
	        res.render('managerservice', {
	        	title: "Лучшие продукты",
	        	product: superproducts
	        })
	    })
	}
	if (type == "highlight") {
		ServiceProduct.findHighProducts(function(superproducts){
	        //console.log(superproducts);
	        res.render('managerservice', {
	        	title: "Хиты",
	        	product: superproducts
	        })
    	})
	}
};
exports.post = function(req, res) {
	postdata(req, res, function (err, data) {
        if (err) {
            console.log(err);
        } else {
            var operation = data.oper;
            console.log(data);
			if (operation == "delete") {
				console.log('Delete');
				var productId = data.productId.replace("\"", "");
				var productId = productId.replace("\"", "");
				console.log(productId);
				ServiceProduct.remove({"productid": mongoose.Types.ObjectId(productId), "type": "super"}, function(err,removed) {
					if (err) {
						console.log(err);
					}
					console.log(removed);
				});
				res.send({});
			}
			if (operation == "addnew") {
				console.log("Add")
				ServiceProduct.createNew(data.productId, data.type, data.enddate, function() {
					console.log('OK')
					res.send({});
				});
			}
    	}
    });
}


text:
#include <aws/servicecatalog/model/ParameterConstraints.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace ServiceCatalog
{
namespace Model
{

ParameterConstraints::ParameterConstraints() :
    m_allowedValuesHasBeenSet(false)
{
}

ParameterConstraints::ParameterConstraints(const JsonValue& jsonValue) :
    m_allowedValuesHasBeenSet(false)
{
  *this = jsonValue;
}

ParameterConstraints& ParameterConstraints::operator =(const JsonValue& jsonValue)
{
  if(jsonValue.ValueExists("AllowedValues"))
  {
    Array<JsonValue> allowedValuesJsonList = jsonValue.GetArray("AllowedValues");
    for(unsigned allowedValuesIndex = 0; allowedValuesIndex < allowedValuesJsonList.GetLength(); ++allowedValuesIndex)
    {
      m_allowedValues.push_back(allowedValuesJsonList[allowedValuesIndex].AsString());
    }
    m_allowedValuesHasBeenSet = true;
  }

  return *this;
}

JsonValue ParameterConstraints::Jsonize() const
{
  JsonValue payload;

  if(m_allowedValuesHasBeenSet)
  {
   Array<JsonValue> allowedValuesJsonList(m_allowedValues.size());
   for(unsigned allowedValuesIndex = 0; allowedValuesIndex < allowedValuesJsonList.GetLength(); ++allowedValuesIndex)
   {
     allowedValuesJsonList[allowedValuesIndex].AsString(m_allowedValues[allowedValuesIndex]);
   }
   payload.WithArray("AllowedValues", std::move(allowedValuesJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace ServiceCatalog
} // namespace Aws