text:
/*******************************************************
 *   Enrico Fucile
 ******************************************************/

#include "grib_api_internal.h"

/*
   This is used by make_class.pl

   START_CLASS_DEF
   CLASS      = accessor
   SUPER      = grib_accessor_class_gen
   IMPLEMENTS = unpack_double;pack_double
   IMPLEMENTS = unpack_string;pack_string;string_length
   IMPLEMENTS = unpack_long;pack_long;destroy
   IMPLEMENTS = init;dump;value_count;get_native_type
   IMPLEMENTS = compare
    END_CLASS_DEF

 */

/* START_CLASS_IMP */

/*

Don't edit anything between START_CLASS_IMP and END_CLASS_IMP
Instead edit values between START_CLASS_DEF and END_CLASS_DEF
or edit "accessor.class" and rerun ./make_class.pl

*/

static int  get_native_type(grib_accessor*);
static int pack_double(grib_accessor*, const double* val,size_t *len);
static int pack_long(grib_accessor*, const long* val,size_t *len);
static int pack_string(grib_accessor*, const char*, size_t *len);
static int unpack_double(grib_accessor*, double* val,size_t *len);
static int unpack_long(grib_accessor*, long* val,size_t *len);
static int unpack_string (grib_accessor*, char*, size_t *len);
static size_t string_length(grib_accessor*);
static int value_count(grib_accessor*,long*);
static void destroy(grib_context*,grib_accessor*);
static void dump(grib_accessor*, grib_dumper*);
static void init(grib_accessor*,const long, grib_arguments* );
static void init_class(grib_accessor_class*);
static int compare(grib_accessor*, grib_accessor*);

typedef struct grib_accessor_concept {
    grib_accessor          att;
/* Members defined in gen */
/* Members defined in concept */
} grib_accessor_concept;

extern grib_accessor_class* grib_accessor_class_gen;

static grib_accessor_class _grib_accessor_class_concept = {
    &grib_accessor_class_gen,                      /* super                     */
    "concept",                      /* name                      */
    sizeof(grib_accessor_concept),  /* size                      */
    0,                           /* inited */
    &init_class,                 /* init_class */
    &init,                       /* init                      */
    0,                  /* post_init                      */
    &destroy,                    /* free mem                       */
    &dump,                       /* describes himself         */
    0,                /* get length of section     */
    &string_length,              /* get length of string      */
    &value_count,                /* get number of values      */
    0,                 /* get number of bytes      */
    0,                /* get offset to bytes           */
    &get_native_type,            /* get native type               */
    0,                /* get sub_section                */
    0,               /* grib_pack procedures long      */
    0,               /* grib_pack procedures long      */
    &pack_long,                  /* grib_pack procedures long      */
    &unpack_long,                /* grib_unpack procedures long    */
    &pack_double,                /* grib_pack procedures double    */
    &unpack_double,              /* grib_unpack procedures double  */
    &pack_string,                /* grib_pack procedures string    */
    &unpack_string,              /* grib_unpack procedures string  */
    0,                 /* grib_pack procedures bytes     */
    0,               /* grib_unpack procedures bytes   */
    0,            /* pack_expression */
    0,              /* notify_change   */
    0,                /* update_size   */
    0,            /* preferred_size   */
    0,                    /* resize   */
    0,      /* nearest_smaller_value */
    0,                       /* next accessor    */
    &compare,                    /* compare vs. another accessor   */
    0,     /* unpack only ith value          */
    0,     /* unpack a subarray         */
    0,             		/* clear          */
};

grib_accessor_class* grib_accessor_class_concept = &_grib_accessor_class_concept;

static void init_class(grib_accessor_class* c)
{
	c->next_offset	=	(*(c->super))->next_offset;
	c->byte_count	=	(*(c->super))->byte_count;
	c->byte_offset	=	(*(c->super))->byte_offset;
	c->sub_section	=	(*(c->super))->sub_section;
	c->pack_missing	=	(*(c->super))->pack_missing;
	c->is_missing	=	(*(c->super))->is_missing;
	c->pack_bytes	=	(*(c->super))->pack_bytes;
	c->unpack_bytes	=	(*(c->super))->unpack_bytes;
	c->pack_expression	=	(*(c->super))->pack_expression;
	c->notify_change	=	(*(c->super))->notify_change;
	c->update_size	=	(*(c->super))->update_size;
	c->preferred_size	=	(*(c->super))->preferred_size;
	c->resize	=	(*(c->super))->resize;
	c->nearest_smaller_value	=	(*(c->super))->nearest_smaller_value;
	c->next	=	(*(c->super))->next;
	c->unpack_double_element	=	(*(c->super))->unpack_double_element;
	c->unpack_double_subarray	=	(*(c->super))->unpack_double_subarray;
	c->clear	=	(*(c->super))->clear;
}

/* END_CLASS_IMP */

#define MAX_CONCEPT_STRING_LENGTH 255

GRIB_INLINE static int grib_inline_strcmp(const char* a,const char* b)
{
    if (*a != *b) return 1;
    while((*a!=0 && *b!=0) &&  *(a) == *(b) ) {a++;b++;}
    return (*a==0 && *b==0) ? 0 : 1;
}

static void init(grib_accessor* a, const long len , grib_arguments* args )
{
    a->length = 0;
}

static void dump(grib_accessor* a, grib_dumper* dumper)
{
    grib_dump_string(dumper,a,NULL);
}

static int pack_double(grib_accessor* a, const double* val, size_t *len)
{
    return GRIB_NOT_IMPLEMENTED;
}

static int pack_long(grib_accessor* a, const long* val, size_t *len)
{
    char buf[80];
    size_t s;
    sprintf(buf,"%ld",*val);
#if 0
    if(*len > 1)
        return GRIB_NOT_IMPLEMENTED;
#endif
    s = strlen(buf)+1;
    return pack_string(a,buf,&s);
}

static int unpack_double(grib_accessor* a, double* val, size_t *len)
{
    /*
     * If we want to have a condition which contains tests for paramId as well
     * as a floating point key, then need to be able to evaluate paramId as a
     * double. E.g.
     *   if (referenceValue > 0 && paramId == 129)
     */
    /*return GRIB_NOT_IMPLEMENTED*/
    long lval = 0;
    int ret = unpack_long(a, &lval, len);
    if (ret == GRIB_SUCCESS) {
        *val = lval;
    }
    return ret;
}

static int unpack_long(grib_accessor* a, long* val, size_t *len)
{
    /* TODO properly calling grib_concept_evaluate_long ! */
    const char *p = grib_concept_evaluate(a->parent->h,a->creator);

    if(!p) {
        if (a->creator->defaultkey)
            return grib_get_long_internal(a->parent->h,a->creator->defaultkey,val);

        return GRIB_NOT_FOUND;
    }

    *val = atol(p);
    *len = 1;

    return GRIB_SUCCESS;
}

static int get_native_type(grib_accessor* a)
{
    int type=GRIB_TYPE_STRING;
    if (a->flags & GRIB_ACCESSOR_FLAG_LONG_TYPE)
        type=GRIB_TYPE_LONG;

    return type;
}

static void destroy(grib_context* c,grib_accessor* a)
{
    /*
     * grib_accessor_concept *self = (grib_accessor_concept*)a;
     * grib_context_free(c,self->cval);
     */
}

static int unpack_string (grib_accessor* a, char* val, size_t *len)
{
    size_t slen ;
    const char *p = grib_concept_evaluate(a->parent->h,a->creator);

    if(!p) {
        if (a->creator->defaultkey)
            return grib_get_string_internal(a->parent->h,a->creator->defaultkey,val,len);

        return GRIB_NOT_FOUND;
    }

    slen = strlen(p) +1;
    if(*len < slen)
    {
        grib_context_log(a->parent->h->context, GRIB_LOG_ERROR, "Variable unpack_string Wrong size for %s it is %d bytes big (len=%d)", a->name , slen ,*len);
        *len = slen;
        return GRIB_BUFFER_TOO_SMALL;
    }
    strcpy(val,p);
    *len = slen;
    return GRIB_SUCCESS;
}

static int pack_string(grib_accessor* a, const char* val, size_t *len)
{
    return  grib_concept_apply(a->parent->h,a->creator,val);
}

static size_t string_length(grib_accessor* a)
{
    return MAX_CONCEPT_STRING_LENGTH;
}

static int value_count(grib_accessor* a,long* count)
{
    *count=1;
    return 0;
}

static int compare(grib_accessor* a,grib_accessor* b)
{
    int retval=0;
    char *aval=0;
    char *bval=0;

    size_t alen = 0;
    size_t blen = 0;
    int err=0;
    long count=0;

    err=grib_value_count(a,&count);
    if (err) return err;
    alen=count;

    err=grib_value_count(b,&count);
    if (err) return err;
    blen=count;

    if (alen != blen) return GRIB_COUNT_MISMATCH;

    aval=(char*)grib_context_malloc(a->parent->h->context,alen*sizeof(char));
    bval=(char*)grib_context_malloc(b->parent->h->context,blen*sizeof(char));

    grib_unpack_string(a,aval,&alen);
    grib_unpack_string(b,bval,&blen);

    retval = GRIB_SUCCESS;
    if (!aval || !bval || grib_inline_strcmp(aval,bval)) retval = GRIB_STRING_VALUE_MISMATCH;

    grib_context_free(a->parent->h->context,aval);
    grib_context_free(b->parent->h->context,bval);

    return retval;
}


text:
package io.github.orionhealth.xbdd.dev;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Profile;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * This is a filter for dev environments only. It allows us to bypass cors issues.
 */
@Profile("dev")
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {

	@Override
	public void init(final FilterConfig fc) throws ServletException {
	}

	@Override
	public void doFilter(final ServletRequest req, final ServletResponse resp,
			final FilterChain chain) throws IOException, ServletException {

		final HttpServletResponse response = (HttpServletResponse) resp;
		final HttpServletRequest request = (HttpServletRequest) req;

		final String scheme = request.isSecure() ? "https" : "http";
		response.setHeader("Access-Control-Allow-Origin", String.format("%s://localhost:3000", scheme));
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "authorization, content-type");

		if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
			response.setStatus(HttpServletResponse.SC_OK);
		} else {
			chain.doFilter(req, resp);
		}

	}

	@Override
	public void destroy() {
	}

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Mail Normalizer</title>
    <link rel="stylesheet" href="http://bootswatch.com/cosmo/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">

          <form class="form-signin" role="form">

Mail Normalizer

            <input type="text" id="normalizer" class="form-control" placeholder="Email to normalize..." required autofocus>
            <button class="btn btn-lg btn-primary btn-block" type="submit">Parse it!</button>
            <input type="email" id="result" class="form-control" placeholder="...the result!" required>
          </form>

by @Kikobeats


text:
import base64
import httplib
import logging
import os
import socket

import celery.exceptions as celery_exceptions
import pyvirtualdisplay
import selenium.common.exceptions
import selenium.webdriver.chrome.service as chrome_service
import shodan
from celery import Task
from selenium import webdriver

from eagleeye_ce import API_KEY
from eagleeye_ce import celery

logger = logging.getLogger(__name__)

socket.setdefaulttimeout(25)

# set up the xvfb display
display = pyvirtualdisplay.Display(visible=0, size=(600, 600))
display.start()

# Set up the webdriver options
options = webdriver.ChromeOptions()
options.add_argument('--start-maximized')
options.add_argument('--disable-java')
options.add_argument('--incognito')
options.add_argument('--use-mock-keychain')
#options.add_argument('--kiosk')
# http://peter.sh/experiments/chromium-command-line-switches/

class WebDriverTask(Task):
    abstract = True
    _driver = None
    _service = None

    @property
    def service(self):
        if self._service is None:
            self._service = chrome_service.Service('chromedriver')
            self._service.start()
        return self._service

    @property
    def driver(self):
        if self._driver is None:
            self._driver = webdriver.Remote(
                self.service.service_url,
                desired_capabilities=options.to_capabilities())
        return self._driver

    def terminate_driver(self):
        """ Things go wrong with the webdriver; we want to recover robustly """
        logger.info('Terminating webdriver.')

        # Don't quit the driver here because it often hangs
        self._driver = None

        if self._service is not None:
            try:
                self._service.stop()
            except Exception:
                # This is really bad...
                pass
        # throw away the old one no matter what
        self._service = None

@celery.task(base=WebDriverTask, soft_time_limit=300, time_limit=600)
def get_shodan_result(query, page=1):
    logger.info("Fetching shodan results query: %s page: %s", query, page)
    api = shodan.WebAPI(API_KEY)
    try:
        res = api.search(query, page=page)
    except shodan.api.WebAPIError:
        logger.info('Finished shodan results with %s page(s).', page - 1)
    else:
        if res:
            get_shodan_result.apply_async(args=[query],
                                           kwargs={'page': page + 1},
                                           queue='get_shodan_result')
        for r in res.get('matches', []):
            get_screenshot.apply_async(args=[r], queue='get_screenshot')
        return res

def dismiss_alerts(driver):
    # handle any possible blocking alerts because selenium is stupid
    alert = driver.switch_to_alert()
    try:
        alert.dismiss()
        logger.info(
            'Closed alert for %s: %s', driver.current_url, alert.text)
    except selenium.common.exceptions.NoAlertPresentException:
        pass

@celery.task(base=WebDriverTask)
def get_screenshot(result):
    ip = result['ip']
    logger.info('Loading %s %s', get_screenshot.request.id, ip)
    try:
        driver = get_screenshot.driver
        driver.get('http://%s' % ip)
        dismiss_alerts(driver)
        logger.info('Loaded %s: %s' % (ip, driver.title))

        write_screenshot.apply_async(
            args=[driver.get_screenshot_as_base64(), ip],
            queue='write_screenshot')

        # try going to a blank page so we get an error now if we can't
        driver.get('about:blank')
    except (celery_exceptions.SoftTimeLimitExceeded,
            socket.timeout):
        logger.info('Terminating overtime process: %s %s',
                    get_screenshot.request.id, ip)
        get_screenshot.terminate_driver()
    except (selenium.common.exceptions.WebDriverException,
            httplib.BadStatusLine):
        # just kill it, alright?
        get_screenshot.terminate_driver()
    except Exception as e:
        print repr(e)
        print 'MAJOR PROBLEM: ', ip, e
        get_screenshot.terminate_driver()

@celery.task
def write_screenshot(screenshot, ip):
    """ Separate task (and queue: write_screenshot) for writing the
    screenshots to disk, so it can be run wherever the results are
    desired.
    """
    binary_screenshot = base64.b64decode(screenshot)
    f = open(os.path.join(os.getcwd(), 'out/%s.png' % ip), 'w')
    f.write(binary_screenshot)
    f.close()


text:
<?php

namespace Koalamon\DefaultBundle\Controller;

use Koalamon\IncidentDashboardBundle\Controller\ProjectAwareController;
use Koalamon\IncidentDashboardBundle\Entity\Project;
use Koalamon\IncidentDashboardBundle\Entity\System;
use Koalamon\IncidentDashboardBundle\Entity\Tool;
use Koalamon\IncidentDashboardBundle\Entity\Translation;
use Koalamon\IncidentDashboardBundle\Entity\UserRole;
use Koalamon\IncidentDashboardBundle\Util\Severity;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class ToolController extends ProjectAwareController
{
    public function adminAction()
    {
        $this->assertUserRights(UserRole::ROLE_ADMIN);
        $tools = $this->getDoctrine()->getRepository('KoalamonIncidentDashboardBundle:Tool')->findByProject($this->getProject(), false);

        return $this->render('KoalamonDefaultBundle:Tool:admin.html.twig', array('tools' => $tools, 'roles' => UserRole::getRoles()));
    }

    public function inheritAction()
    {
        $this->assertUserRights(UserRole::ROLE_ADMIN);
        $tools = $this->getDoctrine()->getRepository('KoalamonIncidentDashboardBundle:Tool')->findByProject($this->getProject(), true);

        $severities = Severity::getSeverities();

        return $this->render('KoalamonDefaultBundle:Tool:inherit.html.twig', array('tools' => $tools, 'severities' => $severities));
    }

    public function storeInheritAction(Request $request)
    {
        $this->assertUserRights(UserRole::ROLE_ADMIN);

        $inheritTools = (array)$request->get('tool');
        $inheritToolsIds = array_keys($inheritTools);

        /** @var Tool[] $tools */
        $tools = $this->getDoctrine()->getRepository('KoalamonIncidentDashboardBundle:Tool')->findByProject($this->getProject(), false);

        /** @var Tool[] $withParents */
        $withParents = [];

        foreach ($tools as $tool) {
            if ($tool->hasParent()) {
                $withParents[$tool->getId()] = $tool;
            }
        }

        $em = $this->getDoctrine()->getManager();

        foreach ($inheritToolsIds as $inheritToolsId) {
            $tool = $em->getRepository('KoalamonIncidentDashboardBundle:Tool')->find($inheritToolsId);

            if ($tool->hasParent()) {
                $tool->setName($inheritTools[$tool->getId()]['name']);
                $tool->setDescription($inheritTools[$tool->getId()]['description']);
                $tool->setErrorsInARow($inheritTools[$tool->getId()]['errorsInARow']);
                $tool->setSeverity($inheritTools[$tool->getId()]['severity']);
                $tool->setActive(true);

                unset($withParents[$tool->getId()]);

                $em->persist($tool);
            } else {

                $child = $this->getDoctrine()->getRepository('KoalamonIncidentDashboardBundle:Tool')->findOneBy(['project' => $this->getProject(), 'parent' => $tool]);

                if (!$child) {
                    $child = new Tool();
                }

                $child->setIdentifier($tool->getIdentifier());
                $child->setName($inheritTools[$tool->getId()]['name']);
                $child->setDescription($inheritTools[$tool->getId()]['description']);
                $child->setErrorsInARow($inheritTools[$tool->getId()]['errorsInARow']);
                $child->setSeverity($inheritTools[$tool->getId()]['severity']);
                $child->setActive(true);
                $child->setParent($tool);
                $child->setProject($this->getProject());

                $em->persist($child);
            }
        }

        foreach ($withParents as $withParent) {
            if ($withParent->hasParent()) {
                $withParent->setActive(false);

                $em->persist($withParent);
            }
        }

        $em->flush();

        $this->addFlash('success', 'Tools successfully stored.');

        return $this->redirectToRoute('koalamon_default_tool_admin_inherit', ['project' => $this->getProject()->getIdentifier()]);
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function storeAction(Request $request)
    {
        $this->assertUserRights(UserRole::ROLE_ADMIN);

        $tool = $request->get('tool');

        if (array_key_exists("id", $tool)) {
            $toolObject = $this->getDoctrine()
                ->getRepository('KoalamonIncidentDashboardBundle:Tool')
                ->find($tool["id"]);
        } else {
            $toolObject = new Tool();
            $toolObject->setProject($this->getProject());
        }

        if (array_key_exists('identifier', $tool)) {
            $existingTool = $this->getDoctrine()
                ->getRepository('KoalamonIncidentDashboardBundle:Tool')
                ->findOneBy(['identifier' => $tool["identifier"], 'project' => $this->getProject()]);

            if ($existingTool) {
                if (!array_key_exists('id', $tool) || $existingTool->getId() != $tool['id']) {
                    $this->addFlash('notice', 'The parameter "identifier" already exists.');
                    return $this->redirect($this->generateUrl('koalamon_default_tool_admin', ['project' => $this->getProject()->getIdentifier()]));
                }
            }
        }

        if ($tool["identifier"] != "") {
            $toolObject->setIdentifier($tool["identifier"]);
        } else {
            $this->addFlash('notice', 'The parameter "identifier" is required');
            return $this->redirect($this->generateUrl('koalamon_default_tool_admin', ['project' => $this->getProject()->getIdentifier()]));
        }

        if ($tool["name"] != "") {
            $toolObject->setName($tool["name"]);
        } else {
            $this->addFlash('notice', 'The parameter "name" is required');
            return $this->redirect($this->generateUrl('koalamon_default_tool_admin', ['project' => $this->getProject()->getIdentifier()]));
        }

        $toolObject->setDescription($tool["description"]);

        if (array_key_exists('active', $tool)) {
            $toolObject->setActive(true);
        } else {
            $toolObject->setActive(false);
        }

        if (array_key_exists('notify', $tool)) {
            $toolObject->setNotify(true);
        } else {
            $toolObject->setNotify(false);
        }

        if (array_key_exists('systemSpecific', $tool)) {
            $toolObject->setSystemSpecific(true);
        } else {
            $toolObject->setSystemSpecific(false);
        }

        $em = $this->getDoctrine()->getManager();
        $em->persist($toolObject);
        $em->flush();

        $this->addFlash('success', 'Tool "' . $toolObject->getName() . '" successfully saved.');
        return $this->redirect($this->generateUrl('koalamon_default_tool_admin', ['project' => $this->getProject()->getIdentifier()]));
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction(Request $request)
    {
        $this->assertUserRights(UserRole::ROLE_ADMIN);

        $toolObject = $this->getDoctrine()
            ->getRepository('KoalamonIncidentDashboardBundle:Tool')
            ->find($request->get("id"));

        if ($toolObject->hasEventIdentifiers()) {
            $this->addFlash('notice', 'Tool "' . $toolObject->getName() . '" cannot be deleted.');
        } else {
            $em = $this->getDoctrine()->getManager();
            $em->remove($toolObject);
            $em->flush();

            $this->addFlash('success', 'Tool "' . $toolObject->getName() . '" successfully deleted.');
        }
        return $this->redirect($this->generateUrl('koalamon_default_tool_admin', ['project' => $this->getProject()->getIdentifier()]));
    }

    public function showThresholdAction()
    {
        return $this->render('@KoalamonDefault/Tool/threshold.html.twig');
    }

    public function storeThresholdAction(Request $request)
    {
        $tools = $request->get('tool');

        $em = $this->getDoctrine()->getManager();

        foreach ($tools as $toolId => $options) {

            $tool = $this->getDoctrine()->getRepository('KoalamonIncidentDashboardBundle:Tool')->find($toolId);

            if (array_key_exists('active', $options)) {
                if (!array_key_exists('direction', $options) || $options['value'] == "") {
                    return new JsonResponse([
                        'status' => 'failure',
                        'message' => 'Threshold not defined correct for ' . $tool->getName() . ' (' . $tool->getIdentifier() . ').']);
                }

                $tool->setThreshold($options['direction'], $options['value']);
                $tool->setThresholdActive(true);
            } else {
                $tool->setThreshold('', 0);
                $tool->setThresholdActive(false);
            }

            $em->persist($tool);
        }

        $em->flush();

        return new JsonResponse(['status' => 'success', 'message' => 'Thresholds successfully stored']);
    }
}


text:
<?php
class Language {
	private $code = '';
	private $text = [];

	public function __construct($code) {
		$this->code = $code;
	}

	#===============================================================================
	# Return the language code
	#===============================================================================
	public function getCode() {
		return $this->code;
	}

	#===============================================================================
	# Load another language file
	#===============================================================================
	public function load($filename) {
		if(file_exists($filename) AND is_readable($filename)) {
			require $filename;
			$this->text = array_merge($this->text, $LANGUAGE ?? []);
		}
	}

	#===============================================================================
	# Set language string
	#===============================================================================
	public function set($name, $value) {
		return $this->text[$name] = $value;
	}

	#===============================================================================
	# Return language string with included arguments
	#===============================================================================
	public function text($name, $arguments = NULL): string {
		if(!isset($this->text[$name])) {
			return "{{$name}}";
		}

		return vsprintf($this->text[$name], $arguments);
	}

	#===============================================================================
	# DEPRECATED: This method will be removed in the future!
	#===============================================================================
	public function template($name, $params = FALSE): string {
		return $this->text($name, $params);
	}
}


text:
layout: post
title:  Volunteer to Help Run a Trial
date:   2015-12-01 14:36
image:  images/articles/volunteer.jpg
excerpt:  The Survival Trial Evaluator is the backbone of every ST Arena...

categories: about
tags: survival trial, about, training, volunteer, evaluator
author: Jon Weiler
comments:  true
---

Become a Volunteer for Survival Trial!

The Survival Trial Evaluator is the backbone of every ST Arena.  If you are interested in competing in a future Trial or just enjoy being outdoors with like-minded Individuals, volunteer and join us in the next Survival Trial!

#Download the Evaluator Registration Form:

[![Volunteer Form]({{ site.url }}/images/articles/pdf.jpg)](http://survivaltrial.com/images/articles/Survival%20Trial%20Evaluator%20Registration.pdf)

##What to expect as an Evaluator:

1. Direct Interaction with the Competitors

* The Evaluator is overall in charge of the Shooting Scenario or Physical Obstacle

* Evaluators will have a scoring packet that includes:

	* Safety Brief

	* Situation Script

	* Scenario/Obstacle Procedures

	* Scoring Procedures

	* Emergency Procedures

	* Radio/Communication Procedures

2. Training for the Survival Trial

	* Scenario Safety Procedures are provided and mandatory during the ST Arena Acclimation,
	the day prior to the start of the Survival Trial

	* No Evaluator will be in a position where they do not feel comfortable and confident

	* All Scenarios/Obstacles will be run by two-person Evaluator Teams

3. Radio/Communication Devices will be provided

4. What is not provided for as an Evaluator:

* Transportation

* Housing

* Meals

#Directions to the NRA Whittington Center:

##From Colorado:

Take I-25 S until Exit 446.Off the exit, take Highway 64 for approximately 4 miles.Turn right at the NRA Whittington Center front Gate.

##From Albuquerque:

Take I-25 N until Exit 446.Off the exit, take Highway 64 for approximately 4 miles.Turn right at the NRA Whittington Center front Gate.

The Survival Trial is a life-changing experience for both Competitors and Evaluators.We want you to come and experience the challenge that is life; the challenge that is the Survival Trial.Evaluators are also a major part of the ST Arena, and you will be highlighted in all Survival Trial and sponsored media. You may also be featured in National Televised Media.

#NRA Whittington Center Map:

<iframe src="https://www.google.com/maps/d/embed?mid=z155o1OMXysM.k-hqxpL98zDs" width="640" height="480"></iframe>


text:
@protocol SHStripeMenuDelegate <NSObject>

@required
- (void)itemSelected:(SHMenuItem *)item;
- (void)hideMenu;

@end

@interface SHStripeMenuViewController : UIViewController

@property (nonatomic, assign) id <SHStripeMenuDelegate> delegate;
- (void)setTableView;

@end


text:
using BlobService.Core.Helpers;
using BlobService.Core.Models;
using BlobService.Core.Services;
using BlobService.Core.Stores;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BlobService.Core.Controllers
{
    public class BlobsController : Controller
    {
        protected readonly BlobServiceOptions _options;
        protected readonly ILogger<BlobsController> _logger;
        protected readonly IStorageService _storageService;
        protected readonly IBlobStore _blobStore;
        protected readonly IBlobMetaDataStore _blobMetaDataStore;
        protected readonly IContainerStore _containerStore;

        public BlobsController(
            BlobServiceOptions options,
            ILoggerFactory loggerFactory,
            IStorageService storageService,
            IBlobStore blobStore,
            IBlobMetaDataStore blobMetaDataStore,
            IContainerStore containerStore)
        {
            _options = options ?? throw new ArgumentNullException(nameof(options));
            _logger = loggerFactory?.CreateLogger<BlobsController>() ?? throw new ArgumentNullException(nameof(loggerFactory));
            _storageService = storageService ?? throw new ArgumentNullException(nameof(storageService));
            _blobStore = blobStore ?? throw new ArgumentNullException(nameof(blobStore));
            _blobMetaDataStore = blobMetaDataStore ?? throw new ArgumentNullException(nameof(blobMetaDataStore));
            _containerStore = containerStore ?? throw new ArgumentNullException(nameof(containerStore));
        }

        [HttpGet("/blobs/{id}")]
        public async Task<IActionResult> GetBlobByIdAsync(string id)
        {
            if (string.IsNullOrEmpty(id)) return NotFound();

            var blob = await _blobStore.GetByIdAsync(id);

            if (blob == null) return NotFound();

            var blobMetaData = await _blobMetaDataStore.GetAllFromBlobAsync(blob.Id);

            var blobModel = ModelMapper.ToViewModel(blob);
            blobModel.MetaData = ModelMapper.ToViewModelList(blobMetaData);

            return Ok(blobModel);
        }

        [HttpGet("/blobs/{id}/raw")]
        public async Task<IActionResult> RawBlobAsync(string id)
        {
            if (string.IsNullOrEmpty(id)) return NotFound();

            var blob = await _blobStore.GetByIdAsync(id);

            if (blob == null) return NotFound();

            var blobContent = await _storageService.GetBlobAsync(blob.ContainerId, blob.StorageSubject);

            if (blobContent == null) return NotFound();

            return File(blobContent, blob.MimeType, blob.OrigFileName);
        }

        [HttpPost("/containers/{containerId}/blobs")]
        // TODO add uploading by chunks
        // TODO refactor
        public async Task<IActionResult> AddBlobAsync(string containerId, IFormFile file, List<BlobMetaDataCreateModel> MetaData = null)
        {
            if (file == null) return BadRequest();

            var container = await _containerStore.GetAsync(containerId);

            if (container == null) return NotFound();

            if (FileLengthExceedAllowed(file)) return BadRequest();

            var contentType = file.ContentType;
            var fileName = file.FileName;
            var buffer = await file.ToByteArrayAsync();

            var subject = await _storageService.AddBlobAsync(containerId, buffer);

            if (string.IsNullOrEmpty(subject)) return StatusCode(500);

            string mimeType = MimeMapping.GetMimeMapping(fileName);

            var blob = await _blobStore.AddAsync(new BlobCreateModel()
            {
                ContainerId = containerId,
                OrigFileName = fileName,
                MimeType = mimeType,
                StorageSubject = subject,
                SizeInBytes = buffer.Length
            });

            var blobModel = ModelMapper.ToViewModel(blob);

            if (MetaData != null)
            {
                foreach (var singleMetaData in MetaData)
                {
                    await _blobMetaDataStore.AddAsync(blob.Id, singleMetaData);
                }

                blobModel.MetaData = ModelMapper.ToViewModelList(await _blobMetaDataStore.GetAllFromBlobAsync(blob.Id));
            }

            return Ok(blobModel);
        }

        [HttpPut("/blobs/{id}")]
        // TODO add uploading by chunks
        // TODO refactor
        public async Task<IActionResult> UpdateBlobAsync(string id, IFormFile file)
        {
            if (file == null) return BadRequest();

            var blob = await _blobStore.GetByIdAsync(id);

            if (blob == null) return NotFound();

            if (FileLengthExceedAllowed(file)) return BadRequest();

            var contentType = file.ContentType;
            var fileName = file.FileName;
            var buffer = await file.ToByteArrayAsync();

            var subject = await _storageService.UpdateBlobAsync(blob.ContainerId, blob.StorageSubject, buffer);

            if (string.IsNullOrEmpty(subject)) return StatusCode(500);

            blob.MimeType = MimeMapping.GetMimeMapping(fileName);
            blob.SizeInBytes = buffer.Length;
            blob.StorageSubject = subject;
            blob.OrigFileName = fileName;

            await _blobStore.UpdateAsync(blob.Id, blob);

            var blobModel = ModelMapper.ToViewModel(blob);

            return Ok(blobModel);
        }

        [HttpDelete("blobs/{id}")]
        public async Task<IActionResult> DeleteBlobAsync(string id)
        {
            if (string.IsNullOrEmpty(id)) return NotFound();

            var blob = await _blobStore.GetByIdAsync(id);

            if (blob == null) return NotFound();

            await _blobStore.RemoveAsync(id);

            await _storageService.DeleteBlobAsync(blob.ContainerId, blob.StorageSubject);

            return Ok();
        }

        internal bool FileLengthExceedAllowed(IFormFile file)
        {
            int fileLengthInMb = (int)(file.Length / 1024 / 1024);

            if (fileLengthInMb > _options.MaxBlobSizeInMB)
                return true;

            return false;
        }
    }
}


text:
<?php

require_once 'src/SunnyPortal.php';

$username = ''; // Set your Login Username
$password = ''; // Set your Login Password

$plantOID = ''; // Set your Plant OID

$portal = new \GunnaPHP\SMA\SunnyPortal([
  'username' => $username,
  'password' => $password
]);

if ( empty($plantOID) ) {
/**
 * Get a List of all Plants
 */
  $plants = $portal->getPlantList();

  foreach ($plants AS $plantOID=>$plantName) {

    echo $plantName.': '.$plantOID.PHP_EOL;

  }

  exit();

}

$portal->setPlant($plantOID);

while (true)
{
  $data = $portal->liveData();
  echo 'PV Generation: '.$data->PV.'kW'.PHP_EOL;
  echo 'Grid Consumption: '.$data->GridConsumption.'kW'.PHP_EOL;
  sleep(15);
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE176_Improper_Handling_of_Unicode_Encoding__w32_61b.c
Label Definition File: CWE176_Improper_Handling_of_Unicode_Encoding__w32.label.xml
Template File: sources-sinks-61b.tmpl.c
*/
/*
 * @description
 * CWE: 176 Improper Handling of Unicode Encoding
 * BadSource:  Initialize data as a large unicode string
 * GoodSource: Initialize data as a small unicode string
 * Sinks:
 *    GoodSink: Ensure the array index is valid
 *    BadSink : Improperly check the array index by not checking the upper bound
 * Flow Variant: 61 Data flow: data returned from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>
#pragma comment( lib, "advapi32" )

#ifndef OMITBAD

wchar_t * CWE176_Improper_Handling_of_Unicode_Encoding__w32_61b_badSource(wchar_t * data)
{
    /* POTENTIAL FLAW: Initialize data as a large unicode string that will cause a buffer overflow in the bad sink */
    wcscpy(data, L"\\u9580\\u961c\\u9640\\u963f\\u963b\\u9644\\u9580\\u961c\\u9640\\u963f\\u963b\\u9644");
    return data;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
wchar_t * CWE176_Improper_Handling_of_Unicode_Encoding__w32_61b_goodG2BSource(wchar_t * data)
{
    /* FIX: Initialize data as a small unicode string that will NOT cause a buffer overflow in the bad sink */
    wcscpy(data, L"\\u9580");
    return data;
}

/* goodB2G() uses the BadSource with the GoodSink */
wchar_t * CWE176_Improper_Handling_of_Unicode_Encoding__w32_61b_goodB2GSource(wchar_t * data)
{
    /* POTENTIAL FLAW: Initialize data as a large unicode string that will cause a buffer overflow in the bad sink */
    wcscpy(data, L"\\u9580\\u961c\\u9640\\u963f\\u963b\\u9644\\u9580\\u961c\\u9640\\u963f\\u963b\\u9644");
    return data;
}

#endif /* OMITGOOD */


text:
package org.antlr.v4.runtime.misc;

import org.antlr.v4.runtime.Token;

import java.util.List;

/**
 * A generic set of integers.
 *
 * @see IntervalSet
 */
public interface IntSet {
	/**
	 * Adds the specified value to the current set.
	 *
	 * @param el the value to add
	 *
	 * @exception IllegalStateException if the current set is read-only
	 */
	void add(int el);

	/**
	 * Modify the current {@link IntSet} object to contain all elements that are
	 * present in itself, the specified {@code set}, or both.
	 *
	 * @param set The set to add to the current set. A {@code null} argument is
	 * treated as though it were an empty set.
	 * @return {@code this} (to support chained calls)
	 *
	 * @exception IllegalStateException if the current set is read-only
	 */

	IntSet addAll(IntSet set);

	/**
	 * Return a new {@link IntSet} object containing all elements that are
	 * present in both the current set and the specified set {@code a}.
	 *
	 * @param a The set to intersect with the current set. A {@code null}
	 * argument is treated as though it were an empty set.
	 * @return A new {@link IntSet} instance containing the intersection of the
	 * current set and {@code a}. The value {@code null} may be returned in
	 * place of an empty result set.
	 */

	IntSet and(IntSet a);

	/**
	 * Return a new {@link IntSet} object containing all elements that are
	 * present in {@code elements} but not present in the current set. The
	 * following expressions are equivalent for input non-null {@link IntSet}
	 * instances {@code x} and {@code y}.
	 *
	 *

	 *
{@code x.complement(y)}

	 *
{@code y.subtract(x)}

	 *

	 *
	 * @param elements The set to compare with the current set. A {@code null}
	 * argument is treated as though it were an empty set.
	 * @return A new {@link IntSet} instance containing the elements present in
	 * {@code elements} but not present in the current set. The value
	 * {@code null} may be returned in place of an empty result set.
	 */

	IntSet complement(IntSet elements);

	/**
	 * Return a new {@link IntSet} object containing all elements that are
	 * present in the current set, the specified set {@code a}, or both.
	 *
	 *

	 * This method is similar to {@link #addAll(IntSet)}, but returns a new
	 * {@link IntSet} instance instead of modifying the current set.

	 *
	 * @param a The set to union with the current set. A {@code null} argument
	 * is treated as though it were an empty set.
	 * @return A new {@link IntSet} instance containing the union of the current
	 * set and {@code a}. The value {@code null} may be returned in place of an
	 * empty result set.
	 */

	IntSet or(IntSet a);

	/**
	 * Return a new {@link IntSet} object containing all elements that are
	 * present in the current set but not present in the input set {@code a}.
	 * The following expressions are equivalent for input non-null
	 * {@link IntSet} instances {@code x} and {@code y}.
	 *
	 *

	 *
{@code y.subtract(x)}

	 *
{@code x.complement(y)}

	 *

	 *
	 * @param a The set to compare with the current set. A {@code null}
	 * argument is treated as though it were an empty set.
	 * @return A new {@link IntSet} instance containing the elements present in
	 * {@code elements} but not present in the current set. The value
	 * {@code null} may be returned in place of an empty result set.
	 */

	IntSet subtract(IntSet a);

	/**
	 * Return the total number of elements represented by the current set.
	 *
	 * @return the total number of elements represented by the current set,
	 * regardless of the manner in which the elements are stored.
	 */
	int size();

	/**
	 * Returns {@code true} if this set contains no elements.
	 *
	 * @return {@code true} if the current set contains no elements; otherwise,
	 * {@code false}.
	 */
	boolean isNil();

	/**
	 * {@inheritDoc}
	 */
	@Override
	boolean equals(Object obj);

	/**
	 * Returns the single value contained in the set, if {@link #size} is 1;
	 * otherwise, returns {@link Token#INVALID_TYPE}.
	 *
	 * @return the single value contained in the set, if {@link #size} is 1;
	 * otherwise, returns {@link Token#INVALID_TYPE}.
	 */
	int getSingleElement();

	/**
	 * Returns {@code true} if the set contains the specified element.
	 *
	 * @param el The element to check for.
	 * @return {@code true} if the set contains {@code el}; otherwise {@code false}.
	 */
	boolean contains(int el);

	/**
	 * Removes the specified value from the current set. If the current set does
	 * not contain the element, no changes are made.
	 *
	 * @param el the value to remove
	 *
	 * @exception IllegalStateException if the current set is read-only
	 */
	void remove(int el);

	/**
	 * Return a list containing the elements represented by the current set. The
	 * list is returned in ascending numerical order.
	 *
	 * @return A list containing all element present in the current set, sorted
	 * in ascending numerical order.
	 */

	List<Integer> toList();

	/**
	 * {@inheritDoc}
	 */
	@Override
	String toString();
}


text:
var fs = require('fs');
var common = require('./common.js');
/**
 * Piping stream
 */
common.createTestOutputDir();
var readerPipeStream = fs.createReadStream('piping_input.txt');
var writerPipeStream = fs.createWriteStream('test_output/piping_output.txt');
readerPipeStream.pipe(writerPipeStream);
readerPipeStream.on('end', function(){
    writerPipeStream.end();
});
writerPipeStream.on('finish', function(){
    console.log('piping finish.');
});


text:
<?php

namespace DevLdn\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest
{
    //
}


text:
public class Test {
    public static void main() {
        int xxx = 3;
        Integer i = new <caret>MyInteger(xxx);
    }
}


text:
void deleteFileAtFat(unsigned char *VhdPtr,int blockNo){

    FAT * fat1 = (FAT *)getBlockPtrByBlockNo(VhdPtr,BLOCK_INDEX_FAT1);

    int current = blockNo;
    int next;
    while(TRUE){
        next = fat1[current].id;
        fat1[current].id = VHD_BLOCK_FREE;
        if(next != VHD_BLOCK_FILE_END){
            current = next;
        }else{
            fat1[next].id = VHD_BLOCK_FREE;
            break;
        }
    }
}


text:
"""
tests.test_logger
~~~~~~~~~~~~~~~~~~

Tests logger component.
"""
from collections import namedtuple
import logging
import unittest

from homeassistant.components import logger

RECORD = namedtuple('record', ('name', 'levelno'))

class TestUpdater(unittest.TestCase):
    """ Test logger component. """

    def setUp(self):
        """ Create default config """
        self.log_config = {'logger':
                           {'default': 'warning', 'logs': {'test': 'info'}}}

    def tearDown(self):
        """ Reset logs """
        del logging.root.handlers[-1]

    def test_logger_setup(self):
        """ Uses logger to create a logging filter """
        logger.setup(None, self.log_config)

        self.assertTrue(len(logging.root.handlers) > 0)
        handler = logging.root.handlers[-1]

        self.assertEqual(len(handler.filters), 1)
        log_filter = handler.filters[0].logfilter

        self.assertEqual(log_filter['default'], logging.WARNING)
        self.assertEqual(log_filter['logs']['test'], logging.INFO)

    def test_logger_test_filters(self):
        """ Tests resulting filter operation """
        logger.setup(None, self.log_config)

        log_filter = logging.root.handlers[-1].filters[0]

        # blocked default record
        record = RECORD('asdf', logging.DEBUG)
        self.assertFalse(log_filter.filter(record))

        # allowed default record
        record = RECORD('asdf', logging.WARNING)
        self.assertTrue(log_filter.filter(record))

        # blocked named record
        record = RECORD('test', logging.DEBUG)
        self.assertFalse(log_filter.filter(record))

        # allowed named record
        record = RECORD('test', logging.INFO)
        self.assertTrue(log_filter.filter(record))


text:
<?php

namespace Phunk\Collaborator;

class Head implements \Phunk\Collaborator
{
    /**
     * @static
     * @param callable $app
     * @param array $options
     * @return callable
     */
    static function collaborate(callable $app, array $options = array())
    {
        return function($env) use ($app)
        {
            $res = $app($env);
            if ('HEAD' === $env['REQUEST_METHOD']) {
                $res[2] = '';
            }
            return $res;
        };
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: hat.dao
 * Date: 10/22/2014
 * Time: 9:55 AM
 */

namespace Api\Controller\Papertask;

use Zend\View\Model\JsonModel;

use Application\Controller\AbstractRestfulController;

class TranslationtmController extends AbstractRestfulController{
    public function getList(){
        $data = [
            'translationTM' => $this->getAllData('\Admin\Entity\ProfileServiceTranslationTM')
        ];

        return new JsonModel($data);
    }

    public function update($id, $data){
        $entityManager = $this->getEntityManager();
        $translationTM = $entityManager->find('\Admin\Entity\ProfileServiceTranslationTM', (int)$id);

        $translationTM->setData($data);

        $entityManager->merge($translationTM);
        $entityManager->flush();

        return new JsonModel([]);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;

namespace OpenDis.Dis1995
{
    /// <summary>
    /// Section 5.2.33. Three floating point values, x, y, and z
    /// </summary>
    [Serializable]
    [XmlRoot]
    public partial class Vector3Float
    {
        /// <summary>
        /// X value
        /// </summary>
        private float _x;

        /// <summary>
        /// y Value
        /// </summary>
        private float _y;

        /// <summary>
        /// Z value
        /// </summary>
        private float _z;

        /// <summary>
        /// Initializes a new instance of the <see cref="Vector3Float"/> class.
        /// </summary>
        public Vector3Float()
        {
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="left">The left operand.</param>
        /// <param name="right">The right operand.</param>
        /// <returns>
        /// 	<c>true</c> if operands are not equal; otherwise, <c>false</c>.
        /// </returns>
        public static bool operator !=(Vector3Float left, Vector3Float right)
        {
            return !(left == right);
        }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="left">The left operand.</param>
        /// <param name="right">The right operand.</param>
        /// <returns>
        /// 	<c>true</c> if both operands are equal; otherwise, <c>false</c>.
        /// </returns>
        public static bool operator ==(Vector3Float left, Vector3Float right)
        {
            if (object.ReferenceEquals(left, right))
            {
                return true;
            }

            if (((object)left == null) || ((object)right == null))
            {
                return false;
            }

            return left.Equals(right);
        }

        public virtual int GetMarshalledSize()
        {
            int marshalSize = 0;

            marshalSize += 4;  // this._x
            marshalSize += 4;  // this._y
            marshalSize += 4;  // this._z
            return marshalSize;
        }

        /// <summary>
        /// Gets or sets the X value
        /// </summary>
        [XmlElement(Type = typeof(float), ElementName = "x")]
        public float X
        {
            get
            {
                return this._x;
            }

            set
            {
                this._x = value;
            }
        }

        /// <summary>
        /// Gets or sets the y Value
        /// </summary>
        [XmlElement(Type = typeof(float), ElementName = "y")]
        public float Y
        {
            get
            {
                return this._y;
            }

            set
            {
                this._y = value;
            }
        }

        /// <summary>
        /// Gets or sets the Z value
        /// </summary>
        [XmlElement(Type = typeof(float), ElementName = "z")]
        public float Z
        {
            get
            {
                return this._z;
            }

            set
            {
                this._z = value;
            }
        }

        /// <summary>
        /// Occurs when exception when processing PDU is caught.
        /// </summary>
        public event EventHandler<PduExceptionEventArgs> ExceptionOccured;

        /// <summary>
        /// Called when exception occurs (raises the <see cref="Exception"/> event).
        /// </summary>
        /// <param name="e">The exception.</param>
        protected void RaiseExceptionOccured(Exception e)
        {
            if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
            {
                this.ExceptionOccured(this, new PduExceptionEventArgs(e));
            }
        }

        /// <summary>
        /// Marshal the data to the DataOutputStream.  Note: Length needs to be set before calling this method
        /// </summary>
        /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
        public virtual void Marshal(DataOutputStream dos)
        {
            if (dos != null)
            {
                try
                {
                    dos.WriteFloat((float)this._x);
                    dos.WriteFloat((float)this._y);
                    dos.WriteFloat((float)this._z);
                }
                catch (Exception e)
                {
                    if (PduBase.TraceExceptions)
                    {
                        Trace.WriteLine(e);
                        Trace.Flush();
                    }

                    this.RaiseExceptionOccured(e);

                    if (PduBase.ThrowExceptions)
                    {
                        throw e;
                    }
                }
            }
        }

        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
        public virtual void Unmarshal(DataInputStream dis)
        {
            if (dis != null)
            {
                try
                {
                    this._x = dis.ReadFloat();
                    this._y = dis.ReadFloat();
                    this._z = dis.ReadFloat();
                }
                catch (Exception e)
                {
                    if (PduBase.TraceExceptions)
                    {
                        Trace.WriteLine(e);
                        Trace.Flush();
                    }

                    this.RaiseExceptionOccured(e);

                    if (PduBase.ThrowExceptions)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// This allows for a quick display of PDU data.  The current format is unacceptable and only used for debugging.
        /// This will be modified in the future to provide a better display.  Usage:
        /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
        /// where pdu is an object representing a single pdu and sb is a StringBuilder.
        /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
        /// </summary>
        /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
        public virtual void Reflection(StringBuilder sb)
        {
            sb.AppendLine("<Vector3Float>");
            try
            {
                sb.AppendLine("<x type=\"float\">" + this._x.ToString(CultureInfo.InvariantCulture) + "</x>");
                sb.AppendLine("<y type=\"float\">" + this._y.ToString(CultureInfo.InvariantCulture) + "</y>");
                sb.AppendLine("<z type=\"float\">" + this._z.ToString(CultureInfo.InvariantCulture) + "</z>");
                sb.AppendLine("</Vector3Float>");
            }
            catch (Exception e)
            {
                    if (PduBase.TraceExceptions)
                    {
                        Trace.WriteLine(e);
                        Trace.Flush();
                    }

                    this.RaiseExceptionOccured(e);

                    if (PduBase.ThrowExceptions)
                    {
                        throw e;
                    }
            }
        }

        /// <summary>
        /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
        /// <returns>
        /// 	<c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        public override bool Equals(object obj)
        {
            return this == obj as Vector3Float;
        }

        /// <summary>
        /// Compares for reference AND value equality.
        /// </summary>
        /// <param name="obj">The object to compare with this instance.</param>
        /// <returns>
        /// 	<c>true</c> if both operands are equal; otherwise, <c>false</c>.
        /// </returns>
        public bool Equals(Vector3Float obj)
        {
            bool ivarsEqual = true;

            if (obj.GetType() != this.GetType())
            {
                return false;
            }

            if (this._x != obj._x)
            {
                ivarsEqual = false;
            }

            if (this._y != obj._y)
            {
                ivarsEqual = false;
            }

            if (this._z != obj._z)
            {
                ivarsEqual = false;
            }

            return ivarsEqual;
        }

        /// <summary>
        /// HashCode Helper
        /// </summary>
        /// <param name="hash">The hash value.</param>
        /// <returns>The new hash value.</returns>
        private static int GenerateHash(int hash)
        {
            hash = hash << (5 + hash);
            return hash;
        }

        /// <summary>
        /// Gets the hash code.
        /// </summary>
        /// <returns>The hash code.</returns>
        public override int GetHashCode()
        {
            int result = 0;

            result = GenerateHash(result) ^ this._x.GetHashCode();
            result = GenerateHash(result) ^ this._y.GetHashCode();
            result = GenerateHash(result) ^ this._z.GetHashCode();

            return result;
        }
    }
}


text:
"""heritago URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from heritages import views
from django.contrib.auth.views import password_reset

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r"api/v1/heritages/", include("heritages.urls")),
    # url(r"api/v1/annotations/", views.AnnotationListView.as_view()),
    # url(r"api/v1/annotations/(?P<pk>\d+)$", views.AnnotationView.as_view()),

    # user auth urls
    # url(r'^$', views.diary, name='home'),
    url(r'^login/$', views.login, name='login'),
    url(r'^auth/$', views.auth_view, name='auth_view'),
    url(r'^logout/$', views.logout, name='logout'),
    url(r'^invalid/$', views.invalid_login, name='invalid_login'),
    url(r'^register/$', views.register_user, name='register_user'),
    url(r'^profile/$', views.user_profile, name='user_profile'),
    url(r'^change_password/$', views.change_password , name='password-change'),
]


text:
@class SWTableViewCell;

typedef NS_ENUM(NSInteger, SWCellState)
{
    kCellStateCenter,
    kCellStateLeft,
    kCellStateRight,
};

@protocol SWTableViewCellDelegate <NSObject>

@optional
- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerLeftUtilityButtonWithIndex:(NSInteger)index;
- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index;
- (void)swipeableTableViewCell:(SWTableViewCell *)cell scrollingToState:(SWCellState)state;
- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell;
- (BOOL)swipeableTableViewCell:(SWTableViewCell *)cell canSwipeToState:(SWCellState)state;
- (void)swipeableTableViewCellDidEndScrolling:(SWTableViewCell *)cell;

@end

@interface SWTableViewCell : UITableViewCell

@property (nonatomic) CGFloat innerMargin;
@property (nonatomic, assign) SWCellState cellState; // The state of the cell within the scroll view, can be left, right or middle

@property (nonatomic, copy) NSArray *leftUtilityButtons;
@property (nonatomic, copy) NSArray *rightUtilityButtons;

@property (nonatomic, weak) id <SWTableViewCellDelegate> delegate;

- (void)setRightUtilityButtons:(NSArray *)rightUtilityButtons WithButtonWidth:(CGFloat) width;
- (void)setLeftUtilityButtons:(NSArray *)leftUtilityButtons WithButtonWidth:(CGFloat) width;
- (void)hideUtilityButtonsAnimated:(BOOL)animated;
- (void)showLeftUtilityButtonsAnimated:(BOOL)animated;
- (void)showRightUtilityButtonsAnimated:(BOOL)animated;

- (BOOL)isUtilityButtonsHidden;

@end


text:
class CoreStatus():
    """The status register flags"""

    def __init__(self):
        """S - Sign flag: this is set if the result of an operation is
        negative, cleared if positive.
        """
        self.s = False

        """V - Overflow flag: when an arithmetic operation produces a result
        too large to be represented in a byte, V is set.
        """
        self.v = False

        """Bit 4 - B: this is set when a software interrupt (BRK instruction) is
        executed.
        """
        self.b = False

        """D: this is the decimal mode status flag. When set, and an Add with
        Carry or Subtract with Carry instruction is executed, the source values are
        treated as valid BCD (Binary Coded Decimal, eg. 0x00-0x99 = 0-99) numbers.
        The result generated is also a BCD number.
        """
        self.d = False

        """I: this is an interrupt enable/disable flag. If it is set,
        interrupts are disabled. If it is cleared, interrupts are enabled.
        """
        self.i = False

        """Z - Zero flag: this is set to 1 when any arithmetic or logical
        operation produces a zero result, and is set to 0 if the result is
        non-zero.
        """
        self.z = False

        """C - Carry flag: this holds the carry out of the most significant
        bit in any arithmetic operation. In subtraction operations however, this
        flag is cleared - set to 0 - if a borrow is required, set to 1 - if no
        borrow is required. The carry flag is also used in shift and rotate
        logical operations.
        """
        self.c = False


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>This</title>
</head>
<body>
<script>
    // Explicitly setting the this reference
    function setVar(arg) {
        this.var = arg;
    }
    var obj = Object.create(null);
    obj.setVar = setVar;
    obj.setVar('hello');
    console.log(obj.var); // => 'hello'

    // Setting the this reference using "call" or "apply"
    // using call
    function setVar2(arg) {
        this.var = arg;
    }
    var obj2 = Object.create(null);
    setVar2.call(obj2,'hello2');
    console.log(obj2.var); // => 'hello2'

    // using apply
    function setVar3(arg) {
        this.var = arg;
    }
    var obj3 = Object.create(null);
    setVar3.apply(obj3,['hello3']);
    console.log(obj3.var); // => 'hello3'

    // Inside every function call, the this reference is reset.
    function outer() {
        this.foo = 'blah';
        function inner() {
            console.log(this.foo);
        }
        inner();
    }
    var obj4 = Object.create(null);
    outer.call(obj4); // undefined
    // The this reference in outer is set to obj since we are explicitly doing this by the call() function.
    // However, in inner() the this reference points to a different object, which is why logging the foo property of this in inner() resulted in undefined.

    // capture the this reference
    function outer2() {
        var that = this;
        that.foo = 'blah';
        function inner() {
            console.log(that.foo);
        }
        inner();
    }
    var obj5 = Object.create(null);
    outer2.call(obj5);

    // Using the bind function
    function setFoo() {
        this.foo = 'bar';
    }
    var obj6 = Object.create(null);
    var boundSetFoo = setFoo.bind(obj6);
    boundSetFoo();
    console.log(obj6.foo); // 'bar'

</script>
</body>
</html>


text:
<?php
namespace SlimBootstrap\Endpoint;

/**
 * This interface represents the basic structure for the collection endpoints.
 *
 * @package SlimBootstrap\Endpoint
 */
interface CollectionPut
{
    /**
     * This function is called on a PUT request to get all data for this
     * endpoint and put them in a usable format.
     *
     * @param array $filters array of key => value pairs to filter the result
     * @param array $data    The parameters for the endpoint from the PUT
     *                       request.
     *
     * @return array
     */
    public function put(array $filters, array $data);
}


text:
package edu.northwestern.bioinformatics.studycalendar.service;

import edu.northwestern.bioinformatics.studycalendar.dao.ActivityDao;
import edu.northwestern.bioinformatics.studycalendar.dao.ActivityTypeDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Activity;
import edu.northwestern.bioinformatics.studycalendar.domain.ActivityType;
import edu.northwestern.bioinformatics.studycalendar.core.Fixtures;
import edu.northwestern.bioinformatics.studycalendar.domain.Source;
import edu.northwestern.bioinformatics.studycalendar.core.DaoTestCase;

import java.util.List;
import java.util.ArrayList;

/**
 * @author Saurabh Agrawal
 */
public class SourceServiceIntegrationTest extends DaoTestCase {
    private static final String TARGET_SOURCE = "targetSource";
    private static final String SOURCE = "source";

    private SourceService sourceService = (SourceService) getApplicationContext().getBean("sourceService");

    private Source targetSource;
    private Source source;
    private ActivityDao activityDao = (ActivityDao) getApplicationContext().getBean("activityDao");
    private ActivityTypeDao activityTypeDao = (ActivityTypeDao) getApplicationContext().getBean("activityTypeDao");
    List<Activity> activitiesToAddAndRemove;

    private Activity activity, anotherActivity, activityToUpdate, activityToDelete;
    private ActivityType activityType;
    protected void setUp() throws Exception {
        super.setUp();

        source = Fixtures.createSource(SOURCE);
        targetSource = Fixtures.createSource(TARGET_SOURCE);

        activitiesToAddAndRemove = new ArrayList<Activity>();

        activityType = Fixtures.createActivityType("LAB_TEST");
        activityTypeDao.save(activityType);

        activity = Fixtures.createActivity("activity1", "code", null, activityType);
        anotherActivity = Fixtures.createActivity("anotherActivity", "code2", null, activityType);
        activityToUpdate = Fixtures.createActivity("activityToUpdate", "CS", null, activityType);
        activityToDelete = Fixtures.createActivity("activityToDelete", "CS", null, activityType);

        activitiesToAddAndRemove.add(activity);
        activitiesToAddAndRemove.add(anotherActivity);
    }

    public void testUpdateSourceDeleteExistingActivitiesAndAddNewActivity() {

        source = sourceService.getByName("ICD9");
        assertNotNull("source must not be null", source);
        assertEquals("source must have 3 activities", Integer.valueOf(4), Integer.valueOf(source.getActivities().size()));
        sourceService.updateSource(source, activitiesToAddAndRemove);

        interruptSession();
        source = sourceService.getByName("ICD9");
        assertEquals("source must have only 2 activities now", Integer.valueOf(2), Integer.valueOf(activityDao.getBySourceId(source.getId()).size()));

    }

    public void testUpdateSourceForUpdateAndDeleteActivity() {

        activitiesToAddAndRemove.add(activityToUpdate);
        source = sourceService.getByName("ICD9");
        assertNotNull("source must not be null", source);
        assertEquals("source must have 3 activities", Integer.valueOf(4), Integer.valueOf(source.getActivities().size()));
        sourceService.updateSource(source, activitiesToAddAndRemove);

        interruptSession();
        source = sourceService.getByName("ICD9");
        assertEquals("source must have only 3 activities ", Integer.valueOf(3), Integer.valueOf(source.getActivities().size()));
    }
}


text:
<manifest
  package="software.sitb.react.canvas">

</manifest>