text:
package com.node.eduoa.controller;

import com.node.eduoa.converters.CustomTimestampEditor;
import com.node.eduoa.entity.*;
import com.node.eduoa.enums.*;
import com.node.eduoa.service.ClassService;
import com.node.eduoa.service.GradeService;
import com.node.eduoa.service.StudentService;
import com.node.eduoa.service.impl.ClassServiceImpl;
import com.node.eduoa.service.impl.StudentServiceImpl;
import com.node.eduoa.utils.model.GradeClassModel;
import com.node.eduoa.utils.model.StudentModel;
import com.node.system.entity.main.Organization;
import com.node.system.log.Log;
import com.node.system.log.LogLevel;
import com.node.system.log.LogMessageObject;
import com.node.system.log.impl.LogUitl;
import com.node.system.service.OrganizationService;
import com.node.system.util.dwz.AjaxObject;
import com.node.system.util.dwz.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.beanvalidator.BeanValidators;
import org.springside.modules.persistence.SearchFilter;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Validator;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * User: linfeng at Administrator
 * Date: 13-7-13
 * Time: 下午2:22
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/management/eduoa/student")
public class StudentController extends BaseFormController {

    @Qualifier("studentServiceImpl")
    @Autowired
    private StudentService studentService;
    @Qualifier("organizationServiceImpl")
    @Autowired
    private OrganizationService organizationService;
    @Qualifier("gradeServiceImpl")
    @Autowired
    private GradeService gradeService;
    @Qualifier("classServiceImpl")
    @Autowired
    private ClassService classService;

    private static final String CREATE = "management/eduoa/student/create";
    private static final String UPDATE = "management/eduoa/student/update";
    private static final String LIST = "management/eduoa/student/list";
    private static final String VIEW = "management/eduoa/student/view";
    private static final String TREE = "management/eduoa/student/treeLookup";
    private static final String TREE_GRADE = "management/eduoa/student/tree_grade";
    private static final String TREE_HEAD_TEACHER = "management/eduoa/student/tree_head_teacher";
    private static final String TEACH_CLASS = "management/eduoa/student/teach_class";
    private static final String GUIDE_CLASS = "management/eduoa/student/guide_class";
    private static final String CLASS_LIST = "management/eduoa/student/class_list";

    @InitBinder
    protected void initBinder(HttpServletRequest request,
                              ServletRequestDataBinder binder) {
        binder.registerCustomEditor(Integer.class, null,
                new CustomNumberEditor(Integer.class, null, true));
        binder.registerCustomEditor(Long.class, null,
                new CustomNumberEditor(Long.class, null, true));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", request.getLocale());
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null,
                new CustomDateEditor(dateFormat, true));
    }

    @Autowired
    private Validator validator;

    @RequiresPermissions("StudentInfo:view")
    @RequestMapping(value = "/tree", method = {RequestMethod.GET, RequestMethod.POST})
    public String tree(Map<String, Object> map) {
        Organization organization = organizationService.getTree();

        map.put("organization", organization);
        return TREE;
    }

    @RequiresPermissions("StudentInfo:view")
    @RequestMapping(value = "/tree_head_teacher", method = {RequestMethod.GET, RequestMethod.POST})
    public String treeHeadTeacher(Map<String, Object> map) {
        Calendar calendar = Calendar.getInstance();
        List<OaGrade> grades = gradeService.findAllByYear(calendar.get(Calendar.YEAR));
        OaGrade grade = new OaGrade();
        grade.setGradeName("根年级");
        grade.setId(-1L);
        grade.setChildren(grades);
        map.put("grade", grade);
        return TREE_HEAD_TEACHER;
    }

    @RequiresPermissions("StudentInfo:view")
    @RequestMapping(value="/tree_grade", method={RequestMethod.GET, RequestMethod.POST})
    public String treeGrade(Map<String, Object> map) {
        Calendar calendar = Calendar.getInstance();
        List<OaGrade> grades = gradeService.findAllByYear(calendar.get(Calendar.YEAR));
        OaGrade grade = new OaGrade();
        grade.setGradeName("根年级");
        grade.setId(-1L);
        grade.setChildren(grades);
        map.put("grade", grade);
        return TREE_GRADE;
    }

    @RequiresPermissions("StudentInfo:save")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String preCreate(Map<String, Object> map) {

        map.put("genderEnum", GenderEnum.values());
        map.put("studentNumber", studentService.getMaxStudentNumber() + 1);

        return CREATE;
    }

    /**
     * LogMessageObject的write用法实例。
     */
    @Log(message = "添加了{0}学生信息。", level = LogLevel.INFO)
    @RequiresPermissions("StudentInfo:save")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public
    @ResponseBody
    String create(StudentModel studentModel) {

        BeanValidators.validateWithException(validator, studentModel.getStudent());
        Calendar calendar = Calendar.getInstance();

        OaContact contact = studentModel.getContact();
        contact.setCreateTime(calendar.getTime());
        contact.setOaStudentByStudentId(studentModel.getStudent());
        List<OaContact> contacts = Arrays.asList(contact);
        studentModel.getStudent().setOaContactsById(contacts);

        if (studentModel.getClassModel() != null && studentModel.getClassModel().getClassId() != null
                && !"".equals(studentModel.getClassModel().getClassId())) {
            OaClass oaClass = classService.get(studentModel.getClassModel().getClassId());
            OaStudentClass studentClass = new OaStudentClass(oaClass, studentModel.getStudent(),
                    studentModel.getClassModel().getStartTime(), studentModel.getClassModel().getEndTime(),
                    calendar.get(Calendar.YEAR));
            List<OaStudentClass> studentClasses = Arrays.asList(studentClass);
            studentModel.getStudent().setOaStudentClassesById(studentClasses);
            studentModel.getStudent().setClassName(oaClass.getClassName());
            studentModel.getStudent().setCategoryName(oaClass.getCategoryName());
        }

        if (studentModel.getClassModel() != null && studentModel.getClassModel().getGradeId() != null
                && !"".equals(studentModel.getClassModel().getGradeId())) {
            OaGrade grade = gradeService.get(studentModel.getClassModel().getGradeId());
            OaStudentGrade studentGrade = new OaStudentGrade(grade, studentModel.getStudent(),
                    studentModel.getClassModel().getStartTime(), studentModel.getClassModel().getEndTime(),
                    calendar.get(Calendar.YEAR));
            List<OaStudentGrade> studentGrades = Arrays.asList(studentGrade);
            studentModel.getStudent().setOaStudentGradesById(studentGrades);
            studentModel.getStudent().setGradeName(studentModel.getClassModel().getGradeName());
        }
        studentModel.getStudent().setCurrentYear(calendar.get(Calendar.YEAR));
        studentModel.getStudent().setCreateTime(calendar.getTime());
        try {
            studentService.save(studentModel.getStudent());
        } catch (Exception e) {
            return AjaxObject.newError(e.getMessage()).setCallbackType("").toString();
        }

        // 加入一个LogMessageObject,该对象的isWritten为true,会记录日志。
        LogUitl.putArgs(LogMessageObject.newWrite().setObjects(new Object[]{studentModel.getStudent().getStudentName()}));
        return AjaxObject.newOk("教师信息添加成功!").toString();
    }

    @RequiresPermissions("StudentInfo:edit")
    @RequestMapping(value="/update/{id}", method=RequestMethod.GET)
    public String preUpdate(@PathVariable Long id, Map<String, Object> map) {
        Calendar calendar = Calendar.getInstance();
        OaStudent student = studentService.get(id);
        GradeClassModel classModel = new GradeClassModel();
        List<OaStudentGrade> studentGrades = student.getOaStudentGradesById();
        if (studentGrades != null && !studentGrades.isEmpty()) {
            for (OaStudentGrade studentGrade: studentGrades) {
                if (studentGrade.getCurrentYear() == calendar.get(Calendar.YEAR)) {
                    classModel.setGradeId(studentGrade.getOaGradeByGradeId().getId());
                    classModel.setGradeName(studentGrade.getOaGradeByGradeId().getGradeName());
                    classModel.setStartTime(studentGrade.getStartTime());
                    classModel.setEndTime(studentGrade.getEndTime());
                    break;
                }
            }
        }

        List<OaStudentClass> studentClasses = student.getOaStudentClassesById();
        if (studentClasses != null && !studentClasses.isEmpty()) {
            for (OaStudentClass studentClass: studentClasses) {
                if (studentClass.getCurrentYear() == calendar.get(Calendar.YEAR)) {
                    classModel.setClassId(studentClass.getOaClassByClassId().getId());
                    classModel.setClassName(studentClass.getOaClassByClassId().getClassName());
                    break;
                }
            }
        }
        List<OaContact> contacts = student.getOaContactsById();
        if (contacts != null && !contacts.isEmpty()) {
            OaContact contact = contacts.get(0);
            map.put("contact", contact);
        }

        map.put("classModel", classModel);
        map.put("student", student);
        map.put("genderEnum", GenderEnum.values());
        return UPDATE;
    }

    @Log(message="修改了{0}同学的信息。")
    @RequiresPermissions("StudentInfo:edit")
    @RequestMapping(value="/update", method=RequestMethod.POST)
    public
    @ResponseBody
    String update(StudentModel studentModel) {
        BeanValidators.validateWithException(validator, studentModel.getStudent());
        Calendar calendar = Calendar.getInstance();

        OaContact contact = studentModel.getContact();
        contact.setUpdateTime(calendar.getTime());
        contact.setOaStudentByStudentId(studentModel.getStudent());
        List<OaContact> contacts = Arrays.asList(contact);
        studentModel.getStudent().setOaContactsById(contacts);

        if (studentModel.getClassModel() != null && studentModel.getClassModel().getClassId() != null
                && !"".equals(studentModel.getClassModel().getClassId())) {
            OaClass oaClass = classService.get(studentModel.getClassModel().getClassId());
            OaStudentClass studentClass = new OaStudentClass(oaClass, studentModel.getStudent(),
                    studentModel.getClassModel().getStartTime(), studentModel.getClassModel().getEndTime(),
                    calendar.get(Calendar.YEAR));
            List<OaStudentClass> studentClasses = Arrays.asList(studentClass);
            studentModel.getStudent().setOaStudentClassesById(studentClasses);
            studentModel.getStudent().setClassName(oaClass.getClassName());
            studentModel.getStudent().setCategoryName(oaClass.getCategoryName());
        }

        if (studentModel.getClassModel() != null && studentModel.getClassModel().getGradeId() != null
                && !"".equals(studentModel.getClassModel().getGradeId())) {
            OaGrade grade = gradeService.get(studentModel.getClassModel().getGradeId());
            OaStudentGrade studentGrade = new OaStudentGrade(grade, studentModel.getStudent(),
                    studentModel.getClassModel().getStartTime(), studentModel.getClassModel().getEndTime(),
                    calendar.get(Calendar.YEAR));
            List<OaStudentGrade> studentGrades = Arrays.asList(studentGrade);
            studentModel.getStudent().setOaStudentGradesById(studentGrades);
            studentModel.getStudent().setGradeName(studentModel.getClassModel().getGradeName());
        }
        studentModel.getStudent().setCurrentYear(calendar.get(Calendar.YEAR));
        studentModel.getStudent().setUpdateTime(calendar.getTime());
        try {
            studentService.save(studentModel.getStudent());
        } catch (Exception e) {
            return AjaxObject.newError(e.getMessage()).setCallbackType("").toString();
        }

        LogUitl.putArgs(LogMessageObject.newWrite().setObjects(new Object[]{studentModel.getStudent().getStudentName()}));
        return AjaxObject.newOk("修改学生成功!").toString();
    }

    @Log(message="删除了{0}同学的信息。")
    @RequiresPermissions("StudentInfo:delete")
    @RequestMapping(value="/delete/{id}", method=RequestMethod.POST)
    public @ResponseBody String delete(@PathVariable Long id) {
        OaStudent student = studentService.get(id);
        studentService.delete(id);
        LogUitl.putArgs(LogMessageObject.newWrite().setObjects(new Object[]{student.getStudentName()}));
        return AjaxObject.newOk("删除学生成功!").setCallbackType("").toString();
    }

    @Log(message="删除了{0}同学的信息。", level=LogLevel.TRACE, override=true)
    @RequiresPermissions("StudentInfo:delete")
    @RequestMapping(value="/delete", method=RequestMethod.POST)
    public @ResponseBody String deleteMany(Long[] ids) {
        String[] titles = new String[ids.length];
        for (int i = 0; i < ids.length; i++) {
            OaStudent student = studentService.get(ids[i]);
            studentService.delete(student.getId());
            titles[i] = student.getStudentName();
        }

        LogUitl.putArgs(LogMessageObject.newWrite().setObjects(new Object[]{Arrays.toString(titles)}));
        return AjaxObject.newOk("学生信息删除成功!").setCallbackType("").toString();
    }

    @RequiresPermissions("StudentInfo:view")
    @RequestMapping(value="/list", method={RequestMethod.GET, RequestMethod.POST})
    public String list(Page page, String keywords,
                       Map<String, Object> map) {
        OaStudent student = new OaStudent();
        List<OaStudent> studentList = null;
        if (StringUtils.isNotBlank(keywords)) {
            Map<String, Object> searchParam = new HashMap<String, Object>();
            searchParam.put(SearchFilter.Operator.LIKE + "_studentName", keywords);
            studentList = studentService.findByStudent(page, student, searchParam);
        } else {
            studentList = studentService.findByStudent(page, student, new HashMap<String, Object>());
        }

        map.put("page", page);
        map.put("studentList", studentList);
        map.put("keywords", keywords);

        return LIST;
    }

    /**
     * @param id
     * @param map
     * @return
     */
    @RequiresPermissions("StudentInfo:view")
    @RequestMapping(value="/view/{id}", method={RequestMethod.GET})
    public String view(@PathVariable Long id, Map<String, Object> map) {
        OaStudent student = studentService.get(id);
        map.put("student", student);
        return VIEW;
    }

}


text:
use crate::schema::{ensure_slice_len_eq, TRANSACTION_CF_NAME};
use anyhow::Result;
use aptos_types::transaction::{Transaction, Version};
use byteorder::{BigEndian, ReadBytesExt};
use schemadb::{
    define_schema,
    schema::{KeyCodec, ValueCodec},
};
use std::mem::size_of;

define_schema!(TransactionSchema, Version, Transaction, TRANSACTION_CF_NAME);

impl KeyCodec<TransactionSchema> for Version {
    fn encode_key(&self) -> Result<Vec<u8>> {
        Ok(self.to_be_bytes().to_vec())
    }

    fn decode_key(mut data: &[u8]) -> Result<Self> {
        ensure_slice_len_eq(data, size_of::<Version>())?;
        Ok(data.read_u64::<BigEndian>()?)
    }
}

impl ValueCodec<TransactionSchema> for Transaction {
    fn encode_value(&self) -> Result<Vec<u8>> {
        bcs::to_bytes(self).map_err(Into::into)
    }

    fn decode_value(data: &[u8]) -> Result<Self> {
        bcs::from_bytes(data).map_err(Into::into)
    }
}

#[cfg(test)]
mod test;

redpajama_set_name: RedPajamaGithub


text:
 {{ email.message.from }}

 {{ email.message.date | date: 'dd/MM/yyyy' }}

 {{ email.message.subject }}

		Reply

		Back

		<textarea ng-model="response" class="email__response-text" placeholder="Enter a reply"></textarea>
		Send


text:
<?php
/**
 * Smarty Internal Plugin Data
 * This file contains the basic classes and methods for template and variable creation
 *
 * @package    Smarty
 * @subpackage Template
 * @author     Uwe Tews
 */

/**
 * Base class with template and variable methods
 *
 * @package    Smarty
 * @subpackage Template
 *
 * @method mixed getConfigVars(string $varName = null, bool $searchParents = true)
 * @method mixed getStreamVariable(string $variable)
 * @method Smarty_Internal_Data clearAssign(mixed $tpl_var)
 * @method Smarty_Internal_Data clearAllAssign()
 * @method Smarty_Internal_Data clearConfig(string $varName = null)
 * @method Smarty_Internal_Data configLoad(string $config_file, mixed $sections = null, string $scope = 'local')
 * @property int $scope
 */
class Smarty_Internal_Data
{
    /**
     * This object type (Smarty = 1, template = 2, data = 4)
     *
     * @var int
     */
    public $_objType = 4;

    /**
     * name of class used for templates
     *
     * @var string
     */
    public $template_class = 'Smarty_Internal_Template';

    /**
     * template variables
     *
     * @var Smarty_Variable[]
     */
    public $tpl_vars = array();

    /**
     * parent template (if any)
     *
     * @var Smarty|Smarty_Internal_Template|Smarty_Internal_Data
     */
    public $parent = null;

    /**
     * configuration settings
     *
     * @var string[]
     */
    public $config_vars = array();

    /**
     * extension handler
     *
     * @var Smarty_Internal_Extension_Handler
     */
    public $ext = null;

    /**
     * Smarty_Internal_Data constructor.
     *
     * Install extension handler
     */
    public function __construct()
    {
        $this->ext = new Smarty_Internal_Extension_Handler();
        $this->ext->objType = $this->_objType;
    }

    /**
     * assigns a Smarty variable
     *
     * @param  array|string $tpl_var the template variable name(s)
     * @param  mixed        $value   the value to assign
     * @param  boolean      $nocache if true any output of this variable will be not cached
     *
     * @return Smarty_Internal_Data current Smarty_Internal_Data (or Smarty or Smarty_Internal_Template) instance for
     *                              chaining
     */
    public function assign($tpl_var, $value = null, $nocache = false)
    {
        if (is_array($tpl_var)) {
            foreach ($tpl_var as $_key => $_val) {
                if ($_key != '') {
                    $this->tpl_vars[$_key] = new Smarty_Variable($_val, $nocache);
                    if ($this->_objType == 2 && $this->scope) {
                        $this->ext->_updateScope->updateScope($this, $_key);
                    }
                }
            }
        } else {
            if ($tpl_var != '') {
                $this->tpl_vars[$tpl_var] = new Smarty_Variable($value, $nocache);
                if ($this->_objType == 2 && $this->scope) {
                    $this->ext->_updateScope->updateScope($this, $tpl_var);
                }
            }
        }
        return $this;
    }

    /**
     * appends values to template variables
     *
     * @api  Smarty::append()
     * @link http://www.smarty.net/docs/en/api.append.tpl
     *
     * @param  array|string $tpl_var                                           the template variable name(s)
     * @param  mixed        $value                                             the value to append
     * @param  bool         $merge                                             flag if array elements shall be merged
     * @param  bool         $nocache                                           if true any output of this variable will
     *                                                                         be not cached
     *
     * @return \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty
     */
    public function append($tpl_var, $value = null, $merge = false, $nocache = false)
    {
        return $this->ext->append->append($this, $tpl_var, $value, $merge, $nocache);
    }

    /**
     * assigns a global Smarty variable
     *
     * @param  string  $varName the global variable name
     * @param  mixed   $value   the value to assign
     * @param  boolean $nocache if true any output of this variable will be not cached
     *
     * @return \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty
     */
    public function assignGlobal($varName, $value = null, $nocache = false)
    {
        return $this->ext->assignGlobal->assignGlobal($this, $varName, $value, $nocache);
    }

    /**
     * appends values to template variables by reference
     *
     * @param  string  $tpl_var the template variable name
     * @param  mixed   &$value  the referenced value to append
     * @param  boolean $merge   flag if array elements shall be merged
     *
     * @return \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty
     */
    public function appendByRef($tpl_var, &$value, $merge = false)
    {
        return $this->ext->appendByRef->appendByRef($this, $tpl_var, $value, $merge);
    }

    /**
     * assigns values to template variables by reference
     *
     * @param string   $tpl_var the template variable name
     * @param          $value
     * @param  boolean $nocache if true any output of this variable will be not cached
     *
     * @return \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty
     */
    public function assignByRef($tpl_var, &$value, $nocache = false)
    {
        return $this->ext->assignByRef->assignByRef($this, $tpl_var, $value, $nocache);
    }

    /**
     * Returns a single or all template variables
     *
     * @api  Smarty::getTemplateVars()
     * @link http://www.smarty.net/docs/en/api.get.template.vars.tpl
     *
     * @param  string                                                 $varName       variable name or null
     * @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $_ptr          optional pointer to data object
     * @param  bool                                                   $searchParents include parent templates?
     *
     * @return mixed variable value or or array of variables
     */
    public function getTemplateVars($varName = null, Smarty_Internal_Data $_ptr = null, $searchParents = true)
    {
        return $this->ext->getTemplateVars->getTemplateVars($this, $varName, $_ptr, $searchParents);
    }

    /**
     * gets the object of a Smarty variable
     *
     * @param  string  $variable       the name of the Smarty variable
     * @param  Smarty_Internal_Data  $_ptr           optional pointer to data object
     * @param  boolean $searchParents search also in parent data
     * @param bool     $error_enable
     *
     * @return Smarty_Variable|Smarty_Undefined_Variable the object of the variable
     * @deprecated since 3.1.28 please use Smarty_Internal_Data::getTemplateVars() instead.
     */
    public function getVariable($variable = null, Smarty_Internal_Data $_ptr = null, $searchParents = true, $error_enable = true){
        return $this->ext->getTemplateVars->_getVariable($this, $variable, $_ptr, $searchParents, $error_enable);
    }

    /**
     * Follow the parent chain an merge template and config variables
     *
     * @param \Smarty_Internal_Data|null $data
     */
    public function _mergeVars(Smarty_Internal_Data $data = null)
    {
        if (isset($data)) {
            if (!empty($this->tpl_vars)) {
                $data->tpl_vars = array_merge($this->tpl_vars, $data->tpl_vars);
            }
            if (!empty($this->config_vars)) {
                $data->config_vars = array_merge($this->config_vars, $data->config_vars);
            }
        } else {
            $data = $this;
        }
        if (isset($this->parent)) {
            $this->parent->_mergeVars($data);
        }
    }

    /**
     * Handle unknown class methods
     *
     * @param string $name unknown method-name
     * @param array  $args argument array
     *
     * @return mixed
     * @throws SmartyException
     */
    public function __call($name, $args)
    {
        return $this->ext->_callExternalMethod($this, $name, $args);
    }
}


text:
from app import app
from database import db
from flask import request
import re

def is_authenticated():
    if 'Authorization' not in request.headers:
        return False

    return app.config['API_KEY'] == request.headers['Authorization'].strip()

regex_address = re.compile("^(.+)@(.+)$", re.IGNORECASE|re.MULTILINE)
def parse_address(email_address):
    """ Parse an email address into local part and domain name"""
    r = regex_address.search(email_address.lower())
    if r and r.groups():
        local = r.group(1)
        domain = r.group(2)
    else:
        return None

    return [ local, domain ]


text:
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings'

from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner

test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)

def runtests(test_labels, verbosity=1,    interactive=True, extra_tests=None,
              **kwargs):
    """Test runner that only runs tests for the apps
    listed in "settings.TEST_APPS".
    """
    extra_tests = extra_tests or []
    app_labels = getattr(settings, 'TEST_APPS', test_labels)
    #return django_test_runner(app_labels, verbosity=verbosity,
    trunner = DjangoTestSuiteRunner()
    return trunner.run_tests(app_labels, verbosity=verbosity,
                              interactive=interactive,
                              extra_tests=extra_tests, **kwargs)

if __name__ == '__main__':
    runtests(['bsblog'])


text:
define(['jquery', './modal-dialog'], function ($, ModalDialog) {

    var CloseConfirmDialog = function (options) {
        this._options = options;
        this._$container = $(_.get(options, 'container', 'body'));
        this._initialized = false;
    };

    CloseConfirmDialog.prototype = Object.create(ModalDialog.prototype);
    CloseConfirmDialog.prototype.constructor = CloseConfirmDialog;

    CloseConfirmDialog.prototype.init = function () {
        if(this._initialized) {
            return;
        }

        var saveBtn = $("<button type='button' class='btn btn-primary btn-file-dialog'>Save</button>");
        var dontSaveBtn = $("<button type='button' class='btn btn-default btn-file-dialog" +
                            " close-file-confirm-dialog-btn'>Don't Save</button>");
        var cancelBtn = $("<button type='button' class='btn btn-default btn-file-dialog'" +
                          " data-dismiss='modal'>Cancel</button>");
        this._saveBtn = saveBtn;
        this._dontSaveBtn = dontSaveBtn;

        this.getFooter().empty();
        this.getFooter().append(dontSaveBtn, saveBtn, cancelBtn);

        this._initialized = true;

        this._$modalContainer.addClass("close-confirm-dialog");
    }

    CloseConfirmDialog.prototype.askConfirmation = function (options) {
        var self = this;
        this.init();

        var name = options.file.getName();
        this.setTitle("Save Changes?");

        var body = this.getBody();
        body.empty();
        body.append($("

File '" + name + "' contains changes, do you want to save them before closing?
Your changes will be lost if you close this file without saving.
"))

        this._saveBtn.unbind('click');
        this._dontSaveBtn.unbind('click');

        this._saveBtn.click(function(e){
            if(_.has(options, 'handleConfirm')){
                self.hide();
                options.handleConfirm(true);
            }
        });

        this._dontSaveBtn.click(function(e){
            if(_.has(options, 'handleConfirm')){
                self.hide();
                options.handleConfirm(false);
            }
        });

        this.show();
    }

    return CloseConfirmDialog;
});


text:
A GraphQL server supports introspection over its schema. This schema is queried
using GraphQL itself, creating a powerful platform for tool-building.

Take an example query for a trivial app. In this case there is a User type with
three fields: id, name, and birthday.

For example, given a server with the following type definition:

```
type User {
  id: String
  name: String
  birthday: Date
}
```

The query

```graphql
{
  __type(name: "User") {
    name
    fields {
      name
      type {
        name
      }
    }
  }
}
```

would return

```js
{
  "__type": {
    "name" : "User",
    "fields": [
      {
        "name": "id",
        "type": { "name": "String" }
      },
      {
        "name": "name",
        "type": { "name": "String" }
      },
      {
        "name": "birthday",
        "type": { "name": "Date" }
      },
    ]
  }
}
```

## General Principles

### Naming conventions

Types and fields required by the GraphQL introspection system that are used in
the same context as user-defined type and fields are prefixed with two
underscores. This in order to avoid naming collisions with user-defined GraphQL
types.  Conversely, GraphQL type system authors must not define any types,
fields, arguments, or any other type system artifact with two leading
underscores.

### Documentation

All types in the introspection system provide a `description` field of type
`String` to allow type designers to publish documentation in addition to
capabilities. A GraphQL server may return the `description` field using Markdown
syntax. Therefore it is recommended that any tool that displays description
use a Markdown renderer.

### Deprecation

To support the management of backwards compatibility, GraphQL fields and enum
values can indicate whether or not they are deprecated (`isDeprecated: Boolean`)
and a description of why it is deprecated (`deprecationReason: String`).

Tools built using GraphQL introspection should respect deprecation by
discouraging deprecated use through information hiding or developer-facing
warnings.

### Type Name Introspection

GraphQL supports type name introspection at any point within a query by the
meta field `__typename: String!` when querying against any Object, Interface,
or Union. It returns the name of the object type currently being queried.

This is most often used when querying against Interface or Union types to
identify which actual type of the possible types has been returned.

This field is implicit and does not appear in the fields list in any defined type.

## Schema Introspection

The schema introspection system is accessible from the meta-fields `__schema`
and `__type` which are accessible from the type of the root of a query
operation.

```
__schema : __Schema!
__type(name: String!) : __Type
```

These fields are implicit and do not appear in the fields list in the root type
of the query operation.

The schema of the GraphQL schema introspection system:

```
type __Schema {
  types: [__Type!]!
  queryType: __Type!
  mutationType: __Type
  directives: [__Directive!]!
}

type __Type {
  kind: __TypeKind!
  name: String
  description: String

  # OBJECT and INTERFACE only
  fields(includeDeprecated: Boolean = false): [__Field!]

  # OBJECT only
  interfaces: [__Type!]

  # INTERFACE and UNION only
  possibleTypes: [__Type!]

  # ENUM only
  enumValues(includeDeprecated: Boolean = false): [__EnumValue!]

  # INPUT_OBJECT only
  inputFields: [__InputValue!]

  # NON_NULL and LIST only
  ofType: __Type
}

type __Field {
  name: String!
  description: String
  args: [__InputValue!]!
  type: __Type!
  isDeprecated: Boolean!
  deprecationReason: String
}

type __InputValue {
  name: String!
  description: String
  type: __Type!
  defaultValue: String
}

type __EnumValue {
  name: String!
  description: String
  isDeprecated: Boolean!
  deprecationReason: String
}

enum __TypeKind {
  SCALAR
  OBJECT
  INTERFACE
  UNION
  ENUM
  INPUT_OBJECT
  LIST
  NON_NULL
}

type __Directive {
  name: String!
  description: String
  args: [__InputValue!]!
  onOperation: Boolean!
  onFragment: Boolean!
  onField: Boolean!
}
```

### The "__Type" Type

`__Type` is at the core of the type introspection system.
It represents scalars, interfaces, object types, unions, enums in the system.

`__Type` also represents type modifiers, which are used to modify a type
that it refers to (`ofType: __Type`). This is how we represent lists,
non-nullable types, and the combinations thereof.

### Type Kinds

There are several different kinds of type. In each kind, different fields are
actually valid. These kinds are listed in the `__TypeKind` enumeration.

#### Scalar

Represents scalar types such as Int, String, and Boolean. Scalars cannot have fields.

A GraphQL type designer should describe the data format and scalar coercion
rules in the description field of any scalar.

Fields

* `kind` must return `__TypeKind.SCALAR`.
* `name` must return a String.
* `description` may return a String or {null}.
* All other fields must return {null}.

#### Object

Object types represent concrete instantiations of sets of fields. The
introspection types (e.g. `__Type`, `__Field`, etc) are examples of objects.

Fields

* `kind` must return `__TypeKind.OBJECT`.
* `name` must return a String.
* `description` may return a String or {null}.
* `fields`: The set of fields query-able on this type.
  * Accepts the argument `includeDeprecated` which defaults to {false}. If
    {true}, deprecated fields are also returned.
* `interfaces`: The set of interfaces that an object implements.
* All other fields must return {null}.

#### Union

Unions are an abstract types where no common fields are declared. The possible
types of a union are explicitly listed out in `possibleTypes`. Types can be
made parts of unions without modification of that type.

Fields

* `kind` must return `__TypeKind.UNION`.
* `name` must return a String.
* `description` may return a String or {null}.
* `possibleTypes` returns the list of types that can be represented within this
  union. They must be object types.
* All other fields must return {null}.

#### Interface

Interfaces is an abstract type where there are common fields declared. Any type
that implements an interface must define all the fields with names and types
exactly matching. The implementations of this interface are explicitly listed
out in `possibleTypes`.

Fields

* `kind` must return `__TypeKind.INTERFACE`.
* `name` must return a String.
* `description` may return a String or {null}.
* `fields`: The set of fields required by this interface.
  * Accepts the argument `includeDeprecated` which defaults to {false}. If
    {true}, deprecated fields are also returned.
* `possibleTypes` returns the list of types that implement this interface.
  They must be object types.
* All other fields must return {null}.

#### Enum

Enums are special scalars that can only have a defined set of values.

Fields

* `kind` must return `__TypeKind.ENUM`.
* `name` must return a String.
* `description` may return a String or {null}.
* `enumValues`: The list of `EnumValue`. There must be at least one and they
  must have unique names.
  * Accepts the argument `includeDeprecated` which defaults to {false}. If
    {true}, deprecated enum values are also returned.
* All other fields must return {null}.

#### Input Object

Input objects are composite types used as inputs into queries defined as a list
of named input values.

For example the input object `Point` could be defined as:

```
type Point {
  x: Int
  y: Int
}
```

Fields

* `kind` must return `__TypeKind.INPUT_OBJECT`.
* `name` must return a String.
* `description` may return a String or {null}.
* `inputFields`: a list of `InputValue`.
* All other fields must return {null}.

#### List

Lists represent sequences of values in GraphQL. A List type is a type modifier:
it wraps another type instance in the `ofType` field, which defines the type of
each item in the list.

Fields

* `kind` must return `__TypeKind.LIST`.
* `ofType`: Any type.
* All other fields must return {null}.

#### Non-null

GraphQL types are nullable. The value {null} is a valid response for field type.

A Non-null type is a type modifier: it wraps another type instance in the
`ofType` field. Non-null types do not allow {null} as a response, and indicate
required inputs for arguments and input object fields.

* `kind` must return `__TypeKind.NON_NULL`.
* `ofType`: Any type except Non-null.
* All other fields must return {null}.

#### Combining List and Non-Null

List and Non-Null can compose, representing more complex types.

If the modified type of a List is Non-Null, then that List may not contain any
{null} items.

If the modified type of a Non-Null is List, then {null} is not accepted,
however an empty list is accepted.

If the modified type of a List is a List, then each item in the first List is
another List of the second List's type.

A Non-Null type cannot modify another Non-Null type.

### The __Field Type

The `__Field` type represents each field in an Object or Interface type.

Fields

* `name` must return a String
* `description` may return a String or {null}
* `args` returns a List of `__InputValue` representing the arguments this
  field accepts.
* `type` must return a `__Type` that represents the type of value returned by
  this field.
* `isDeprecated` returns {true} if this field should no longer be used,
  otherwise {false}.
* `deprecationReason` optionally provides a reason why this field is deprecated.

### The __InputValue Type

The `__InputValue` type represents field and directive arguments as well as the
`inputFields` of an input object.

Fields

* `name` must return a String
* `description` may return a String or {null}
* `type` must return a `__Type` that represents the type this input
  value expects.
* `defaultValue` may return a String encoding (using the GraphQL language) the
  default value used by this input value in the condition a value is not
  provided at runtime. If this input value has no default value, returns {null}.


text:
/**
 * Internal class for handling the priority sorting of ticker handlers.
 *
 * @private
 * @class
 */
export default class TickerListener {
    /**
     * Constructor
     *
     * @param {Function} fn - The listener function to be added for one update
     * @param {Function} [context=null] - The listener context
     * @param {number} [priority=0] - The priority for emitting
     * @param {boolean} [once=false] - If the handler should fire once
     */
    constructor(fn, context = null, priority = 0, once = false) {
        /**
         * The handler function to execute.
         * @member {Function}
         */
        this.fn = fn;

        /**
         * The calling to execute.
         * @member {Function}
         */
        this.context = context;

        /**
         * The current priority.
         * @member {number}
         */
        this.priority = priority;

        /**
         * If this should only execute once.
         * @member {boolean}
         */
        this.once = once;

        /**
         * The next item in chain.
         * @member {TickerListener}
         */
        this.next = null;

        /**
         * The previous item in chain.
         * @member {TickerListener}
         */
        this.previous = null;

        /**
         * `true` if this listener has been destroyed already.
         * @member {boolean}
         * @private
         */
        this._destroyed = false;
    }

    /**
     * Simple compare function to figure out if a function and context match.
     *
     * @param {Function} fn - The listener function to be added for one update
     * @param {Function} context - The listener context
     * @return {boolean} `true` if the listener match the arguments
     */
    match(fn, context) {
        context = context || null;

        return this.fn === fn && this.context === context;
    }

    /**
     * Emit by calling the current function.
     * @param {number} delta_time - time since the last emit.
     * @return {TickerListener} Next ticker
     */
    emit(delta_time) {
        if (this.fn) {
            if (this.context) {
                this.fn.call(this.context, delta_time);
            }
            else {
                this.fn(delta_time);
            }
        }

        const redirect = this.next;

        if (this.once) {
            this.destroy(true);
        }

        // Soft-destroying should remove
        // the next reference
        if (this._destroyed) {
            this.next = null;
        }

        return redirect;
    }

    /**
     * Connect to the list.
     * @param {TickerListener} previous - Input node, previous listener
     */
    connect(previous) {
        this.previous = previous;
        if (previous.next) {
            previous.next.previous = this;
        }
        this.next = previous.next;
        previous.next = this;
    }

    /**
     * Destroy and don't use after this.
     * @param {boolean} [hard = false] `true` to remove the `next` reference, this
     *        is considered a hard destroy. Soft destroy maintains the next reference.
     * @return {TickerListener} The listener to redirect while emitting or removing.
     */
    destroy(hard = false) {
        this._destroyed = true;
        this.fn = null;
        this.context = null;

        // Disconnect, hook up next and previous
        if (this.previous) {
            this.previous.next = this.next;
        }

        if (this.next) {
            this.next.previous = this.previous;
        }

        // Redirect to the next item
        const redirect = this.previous;

        // Remove references
        this.next = hard ? null : redirect;
        this.previous = null;

        return redirect;
    }
}


text:
<?php

/**
 * Automatic scheduler task rule.
 *
 * @category   Zend
 * @package    Zend_Scheduler
 * @copyright  Copyright (c) 2006 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Scheduler_Task_Rule
{
    /** @var Zend_Date Request time */
    protected $_time = null;

    /** @var string Type */
    protected $_type = '';

    /** @var string Rule */
    protected $_rule = '';

    /** @var array Time numeric values */
    protected $_times = array(
        'months'   => Zend_Date::MONTH_SHORT,
        'days'     => Zend_Date::DAY_SHORT,
        'weekdays' => Zend_Date::WEEKDAY_DIGIT,
        'hours'    => Zend_Date::HOUR_SHORT,
        'minutes'  => Zend_Date::MINUTE_SHORT
    );

    /** @var array Time ranges */
    protected $_ranges = array(
        'months'   => array('minimum' => 1, 'maximum' => 12),
        'days'     => array('minimum' => 1, 'maximum' => 31),
        'weekdays' => array('minimum' => 0, 'maximum' => 6),
        'hours'    => array('minimum' => 0, 'maximum' => 23),
        'minutes'  => array('minimum' => 0, 'maximum' => 59)
    );

    /** @var array Months of the year */
    protected $_months = array(
        'Jan' => 1, 'Feb' => 2,  'Mar' => 3,  'Apr' => 4,
        'May' => 5, 'Jun' => 6,  'Jul' => 7,  'Aug' => 8,
        'Sep' => 9, 'Oct' => 10, 'Nov' => 11, 'Dec' => 12
    );

    /** @var array Days of the month */
    protected $_days = array(
        'last' => ''
    );

    /** @var array Days of the week */
    protected $_weekdays = array(
        'Sun' => 0, 'Mon' => 1, 'Tue' => 2, 'Wed' => 3,
        'Thu' => 4, 'Fri' => 5, 'Sat' => 6
    );

    /**
     * Constructor.
     *
     * @param string $type
     * @param string $rule
     */
    public function __construct($type, $rule)
    {
        $type = trim(strtolower($type));
        $rule = trim($rule);

        if (empty($type)) {
            throw new Zend_Scheduler_Exception('Type string expected');
        }
        if (!isset($this->_times[$type])) {
            throw new Zend_Scheduler_Exception("Type '{$type}' was not a valid type");
        }
        if (empty($type)) {
            throw new Zend_Scheduler_Exception('Rule string expected');
        }

        $this->_type = $type;
        $this->_rule = $rule;
    }

    /**
     * Set the time (by default, the request time).  For testing purposes a
     * different time can be passed in.
     *
     * @param Zend_Date $time
     * @return Zend_Scheduler_Task This instance
     */
    public function setTime($time)
    {
        if (!$time instanceof Zend_Date) {
            $time = new Zend_Date($time);
        }
        $this->_time = $time;

        if ($this->_type == 'days') { // Set number of days in the month
            $this->_days['last'] = $time->get(Zend_Date::MONTH_DAYS);
        }

        return $this;
    }

    /**
     * Checks if rule matches the supplied timestamp.
     *
     * @param  string $time
     * @return bool
     */
    public function matches($time = '')
    {
        if ($time) {
            $this->setTime($time);
        }
        if (empty($this->_time)) {
            throw new Zend_Scheduler_Exception('You must supply a time');
        }
        return in_array($this->_getTime(), $this->_parse());
    }

    /**
     * Executes following unserialization.
     */
    public function __wakeup()
    {
        $this->_time = null;
    }

    /**
     * Gets int value for specified type (e.g., 'Dec' equals 12)
     *
     * @return int
     */
    protected function _getTime()
    {
        return $this->_time->get($this->_times[$this->_type]);
    }

    /**
     * Parses the rule.
     *
     * @param  string $rule
     * @return array Expanded values
     */
    protected function _parse()
    {
        $rule = $this->_rule;

        if ($this->_type == 'months' or $this->_type == 'weekdays') {
            if (strpos($rule, '/') !== false) {
                throw new Zend_Scheduler_Exception(ucfirst($this->_type)
                    . ' can only be specified individually or as a range');
            }
        }

        if (preg_match('/[A-Za-z]/', $this->_rule)) {
            $patterns     = array();
            $replacements = array();
            $type         = '_' . $this->_type;
            foreach ($this->$type as $name => $value) {
                $patterns[]     = '/' . $name . '[^,\-\/]*/i';
                $replacements[] = $value;
            }
            $rule = preg_replace($patterns, $replacements, $this->_rule);
        }

        $values = preg_split('/\s*,\s*/', $rule, -1, PREG_SPLIT_NO_EMPTY);

        foreach ($values as $i => $value) {
            if (strpos($value, '-') !== false and strpos($value, '/') !== false) {
                throw new Zend_Scheduler_Exception('Invalid ' . $this->_type . ' value');
            }

            if (strcmp($value, (int) $value) === 0) {
                continue; // Value is an integer; go to next value
            }
            if (preg_match('/\A\d+\s*\-\s*\d+\Z/', $value)) {
                // Parse range (e.g., 5-10)
                list($valueFrom, $valueTo) = preg_split('/\s*\-\s*/', $value);
                if (!$this->_inRange($valueFrom) or !$this->_inRange($valueTo)) {
                    throw new Zend_Scheduler_Exception('Invalid ' . $this->_type . ' range');
                }

                $j = $valueFrom;
                if ($valueFrom > $valueTo) {
                    for (; $j < $this->_getMaximum() + 1; $j++) {
                        $values[] = $j;
                    }
                    $j = $this->_getMinimum();
                }
                for (; $j < $valueTo + 1; $j++) {
                    $values[] = $j;
                }
                unset($values[$i]);
            } else if (preg_match('/\A\d+\s*\/\s*\d+\Z/', $value)) {
                // Parse incremental step (e.g., 5/10)
                list($valueFrom, $valueStep) = preg_split('/\s*\/\s*/', $value);
                $j = $valueFrom;
                while ($this->_inRange($j)) {
                    $values[] = $j;
                    $j += $valueStep;
                }
                unset($values[$i]);
            } else {
                throw new Zend_Scheduler_Exception('Invalid ' . $this->_type . ' value');
            }
        }

        $values = array_unique($values);
        sort($values);

        return $values;
    }

    /**
     * Gets minimally-acceptable value for type.
     *
     * @return int Minimum
     */
    protected function _getMinimum()
    {
        return $this->_ranges[$this->_type]['minimum'];
    }

    /**
     * Gets maximally-acceptable value for type.
     *
     * @return int Maximum
     */
    protected function _getMaximum()
    {
        return $this->_ranges[$this->_type]['maximum'];
    }

    /**
     * Checks if rule value is within the acceptable range.
     *
     * @param  int $value
     * @return bool
     */
    protected function _inRange($value)
    {
        return ($value >= $this->_getMinimum() and $value <= $this->_getMaximum());
    }

    /**
     * Return Rule
     *
     * @return string
     */
    public function getValue()
    {
        return $this->_rule;
    }
}


text:
package org.apache.flink.streaming.python.util.serialization;

import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.util.FlinkRuntimeException;

import org.python.core.PyObject;

import java.io.IOException;

/**
 * A {@link SerializationSchema} for {@link PyObject}s.
 */
public class PythonSerializationSchema implements SerializationSchema<PyObject> {
	private static final long serialVersionUID = -9170596504893036458L;

	private final byte[] serSchema;
	private transient SerializationSchema<PyObject> schema;

	public PythonSerializationSchema(SerializationSchema<PyObject> schema) throws IOException {
		this.serSchema = SerializationUtils.serializeObject(schema);
	}

	@Override
	@SuppressWarnings("unchecked")
	public byte[] serialize(PyObject element) {
		if (this.schema == null) {
			try {
				this.schema = SerializationUtils.deserializeObject(this.serSchema);
			} catch (Exception e) {
				throw new FlinkRuntimeException("Schema could not be deserialized.", e);
			}
		}
		return this.schema.serialize(element);
	}
}


text:
package org.neo4j.server.rest;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

import org.neo4j.server.rest.domain.JsonHelper;
import org.neo4j.server.rest.domain.JsonParseException;
import org.neo4j.test.server.HTTP;

public class RestRequest {

    private final URI baseUri;
    private final static Client DEFAULT_CLIENT = Client.create();
    private final Client client;
    private MediaType accept = MediaType.APPLICATION_JSON_TYPE;
    private Map<String, String> headers=new HashMap<String, String>();

    public RestRequest( URI baseUri ) {
        this( baseUri, null, null );
    }

    public RestRequest( URI baseUri, String username, String password ) {
        this.baseUri = uriWithoutSlash( baseUri );
        if ( username != null )
        {
            client = Client.create();
            client.addFilter( new HTTPBasicAuthFilter( username, password ) );
        }
        else
        {
            client = DEFAULT_CLIENT;
        }
    }

    public RestRequest(URI uri, Client client) {
        this.baseUri = uriWithoutSlash( uri );
        this.client = client;
    }

    public RestRequest() {
        this( null );
    }

    private URI uriWithoutSlash( URI uri ) {
        if (uri == null) return null;
        String uriString = uri.toString();
        return uriString.endsWith( "/" ) ? uri( uriString.substring( 0, uriString.length() - 1 ) ) : uri;
    }

    public static String encode( Object value ) {
        if ( value == null ) return "";
        try {
            return URLEncoder.encode( value.toString(), "utf-8" ).replaceAll( "\\+", "%20" );
        } catch ( UnsupportedEncodingException e ) {
            throw new RuntimeException( e );
        }
    }

    private Builder builder( String path ) {
        return builder( path, accept );
    }

    private Builder builder( String path, final MediaType accept ) {
        WebResource resource = client.resource( uri( pathOrAbsolute( path ) ) );
        Builder builder = resource.accept( accept );
        if ( !headers.isEmpty() ) {
            for ( Map.Entry<String, String> header : headers.entrySet() ) {
                builder = builder.header( header.getKey(),header.getValue() );
            }
        }
        return builder;
    }

    private String pathOrAbsolute( String path ) {
        if ( path.startsWith( "http://" ) ) return path;
        return baseUri + "/" + path;
    }

    public JaxRsResponse get( String path ) {
        return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder( path ).get( ClientResponse.class ) ) );
    }

    public JaxRsResponse get(String path, String data) {
        return get( path, data, MediaType.APPLICATION_JSON_TYPE );
    }

    public JaxRsResponse get( String path, String data, final MediaType mediaType ) {
        Builder builder = builder( path );
        if ( data != null ) {
            builder = builder.entity( data, mediaType);
        } else {
            builder = builder.type( mediaType );
        }
        return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder.get( ClientResponse.class ) ) );
    }

    public JaxRsResponse delete(String path) {
        return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder( path ).delete( ClientResponse.class ) ) );
    }

    public JaxRsResponse post(String path, String data) {
        return post(path, data, MediaType.APPLICATION_JSON_TYPE);
    }

    public JaxRsResponse post(String path, String data, final MediaType mediaType) {
        Builder builder = builder( path );
        if ( data != null ) {
            builder = builder.entity( data, mediaType);
        } else {
            builder = builder.type(mediaType);
        }
        return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder.post( ClientResponse.class ) ) );
    }

    public JaxRsResponse put(String path, String data) {
        Builder builder = builder( path );
        if ( data != null ) {
            builder = builder.entity( data, MediaType.APPLICATION_JSON_TYPE );
        }
        return new JaxRsResponse( HTTP.sanityCheck( builder.put( ClientResponse.class ) ) );
    }

    public Object toEntity( JaxRsResponse JaxRsResponse ) throws JsonParseException {
        return JsonHelper.readJson( entityString( JaxRsResponse ) );
    }

    public Map<?, ?> toMap( JaxRsResponse JaxRsResponse) throws JsonParseException {
        final String json = entityString( JaxRsResponse );
        return JsonHelper.jsonToMap(json);
    }

    private String entityString( JaxRsResponse JaxRsResponse) {
        return JaxRsResponse.getEntity();
    }

    public boolean statusIs( JaxRsResponse JaxRsResponse, Response.StatusType status ) {
        return JaxRsResponse.getStatus() == status.getStatusCode();
    }

    public boolean statusOtherThan( JaxRsResponse JaxRsResponse, Response.StatusType status ) {
        return !statusIs(JaxRsResponse, status );
    }

    public RestRequest with( String uri ) {
        return new RestRequest( uri( uri ), client );
    }

    private URI uri( String uri ) {
        try {
            return new URI( uri );
        } catch ( URISyntaxException e ) {
            throw new RuntimeException( e );
        }
    }

    public URI getUri() {
        return baseUri;
    }

    public JaxRsResponse get() {
        return get( "" );
    }

    public JaxRsResponse get(String path, final MediaType acceptType) {
        Builder builder = builder(path, acceptType);
        return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder.get( ClientResponse.class ) ) );
    }

    public static RestRequest req() {
        return new RestRequest();
    }

    public JaxRsResponse delete(URI location) {
        return delete(location.toString());
    }

    public JaxRsResponse put(URI uri, String data) {
        return put(uri.toString(),data);
    }

    public RestRequest accept( MediaType accept )
    {
        this.accept = accept;
        return this;
    }

    public RestRequest header(String header, String value) {
        this.headers.put(header,value);
        return this;
    }
}


text:
<!doctype html>

    <meta charset="UTF-8">
    <meta name="keywords" content="youtube,display,autoplay,loop,looping,muted,fullscreen">
    <meta name="author" content="Drew Silcock <drew@drewsilcock.co.uk>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Simple fullscreen autoplay looping muted (by default) YouTube wrapper.">
    <title>YouTube Display</title>

    <link rel="stylesheet"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
          crossorigin="anonymous">

    <link rel="stylesheet" href="css/main.css">

YouTube Display

            Generate a link to display looping, autoplaying, muted,
            easily-fullscreenable YouTube videos.

          <input id="yd-js-input" type="text" class="form-control" placeholder="Enter YouTube Video URL">

            <button id="yd-js-fullscreen" class="yd-icon yd-js-tooltip btn btn-default"
                    type="button" data-enabled="true"
                    data-animation="false" data-placement="top" title="Easy fullscreen will be enabled.">

            </button>
            <button id="yd-js-mute" class="yd-icon yd-js-tooltip btn btn-default"
                    type="button" data-muted="true"
                    data-animation="false" data-placement="top" title="Sound will be disabled.">

            </button>
            <button id="yd-js-submit" class="yd-submit btn btn-default" type="button">
              Get Display URL
            </button>

Success

              Your display URL is:

              There was a problem generating the display URL.

Info

                Security restrictions prevent a page going fullscreen without user
                interaction. To go fullscreen, click anywhere on the page. To exit
                fullscreen, press the <Escape> key.


text:
public class Library {
    public boolean someLibraryMethod() {
        return true;
    }
}


text:
package org.apache.camel.component.hazelcast;

import java.util.HashMap;
import java.util.Map;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IAtomicLong;

import org.apache.camel.CamelExecutionException;
import org.apache.camel.builder.RouteBuilder;
import org.junit.After;
import org.junit.Test;
import org.mockito.Mock;

import static org.mockito.Mockito.*;

public class HazelcastAtomicnumberProducerTest extends HazelcastCamelTestSupport {

    @Mock
    private IAtomicLong atomicNumber;

    @Override
    protected void trainHazelcastInstance(HazelcastInstance hazelcastInstance) {
        when(hazelcastInstance.getAtomicLong("foo")).thenReturn(atomicNumber);
    }

    @Override
    protected void verifyHazelcastInstance(HazelcastInstance hazelcastInstance) {
        verify(hazelcastInstance, atLeastOnce()).getAtomicLong("foo");
    }

    @After
    public void verifyAtomicNumberMock() {
        verifyNoMoreInteractions(atomicNumber);
    }

    @Test(expected = CamelExecutionException.class)
    public void testWithInvalidOperationName() {
        template.sendBody("direct:setInvalid", 4711);
    }

    @Test
    public void testSet() {
        template.sendBody("direct:set", 4711);
        verify(atomicNumber).set(4711);
    }

    @Test
    public void testGet() {
        when(atomicNumber.get()).thenReturn(1234L);
        long body = template.requestBody("direct:get", null, Long.class);
        verify(atomicNumber).get();
        assertEquals(1234, body);
    }

    @Test
    public void testIncrement() {
        when(atomicNumber.incrementAndGet()).thenReturn(11L);
        long body = template.requestBody("direct:increment", null, Long.class);
        verify(atomicNumber).incrementAndGet();
        assertEquals(11, body);
    }

    @Test
    public void testDecrement() {
        when(atomicNumber.decrementAndGet()).thenReturn(9L);
        long body = template.requestBody("direct:decrement", null, Long.class);
        verify(atomicNumber).decrementAndGet();
        assertEquals(9, body);
    }

    @Test
    public void testDestroy() throws InterruptedException {
        template.sendBody("direct:destroy", null);
        verify(atomicNumber).destroy();
    }

    @Test
    public void testSetWithOperationNumber() {
        template.sendBody("direct:setWithOperationNumber", 5711);
        verify(atomicNumber).set(5711);
    }

    @Test
    public void testSetWithOperationName() {
        template.sendBody("direct:setWithOperationName", 5711);
        verify(atomicNumber).set(5711);
    }

    @Test
    public void testCompareAndSet() {
        Map<String, Object> headersOk = new HashMap();
        headersOk.put(HazelcastConstants.EXPECTED_VALUE, 1234L);
        when(atomicNumber.compareAndSet(1234L, 1235L)).thenReturn(true);
        when(atomicNumber.compareAndSet(1233L, 1235L)).thenReturn(false);
        boolean result = template.requestBodyAndHeaders("direct:compareAndSet", 1235L, headersOk, Boolean.class);
        verify(atomicNumber).compareAndSet(1234L, 1235L);
        assertEquals(true, result);
        Map<String, Object> headersKo = new HashMap();
        headersKo.put(HazelcastConstants.EXPECTED_VALUE, 1233L);
        result = template.requestBodyAndHeaders("direct:compareAndSet", 1235L, headersKo, Boolean.class);
        verify(atomicNumber).compareAndSet(1233L, 1235L);
        assertEquals(false, result);
    }

    @Test
    public void testGetAndAdd() {
        when(atomicNumber.getAndAdd(12L)).thenReturn(13L);
        long result = template.requestBody("direct:getAndAdd", 12L, Long.class);
        verify(atomicNumber).getAndAdd(12L);
        assertEquals(13L, result);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                from("direct:setInvalid").setHeader(HazelcastConstants.OPERATION, constant("invalid"))
                        .to(String.format("hazelcast-%sfoo", HazelcastConstants.ATOMICNUMBER_PREFIX));

                from("direct:set").setHeader(HazelcastConstants.OPERATION, constant(HazelcastOperation.SET_VALUE))
                        .to(String.format("hazelcast-%sfoo", HazelcastConstants.ATOMICNUMBER_PREFIX));

                from("direct:get").setHeader(HazelcastConstants.OPERATION, constant(HazelcastOperation.GET)).to(String.format("hazelcast-%sfoo", HazelcastConstants.ATOMICNUMBER_PREFIX));

                from("direct:increment").setHeader(HazelcastConstants.OPERATION, constant(HazelcastOperation.INCREMENT)).to(
                        String.format("hazelcast-%sfoo", HazelcastConstants.ATOMICNUMBER_PREFIX));

                from("direct:decrement").setHeader(HazelcastConstants.OPERATION, constant(HazelcastOperation.DECREMENT)).to(
                        String.format("hazelcast-%sfoo", HazelcastConstants.ATOMICNUMBER_PREFIX));

                from("direct:destroy").setHeader(HazelcastConstants.OPERATION, constant(HazelcastOperation.DESTROY)).to(
                        String.format("hazelcast-%sfoo", HazelcastConstants.ATOMICNUMBER_PREFIX));

                from("direct:compareAndSet").setHeader(HazelcastConstants.OPERATION, constant(HazelcastOperation.COMPARE_AND_SET)).to(
                        String.format("hazelcast-%sfoo", HazelcastConstants.ATOMICNUMBER_PREFIX));

                from("direct:getAndAdd").setHeader(HazelcastConstants.OPERATION, constant(HazelcastOperation.GET_AND_ADD)).to(
                        String.format("hazelcast-%sfoo", HazelcastConstants.ATOMICNUMBER_PREFIX));

                from("direct:setWithOperationNumber").toF("hazelcast-%sfoo?operation=%s", HazelcastConstants.ATOMICNUMBER_PREFIX, HazelcastOperation.SET_VALUE);
                from("direct:setWithOperationName").toF("hazelcast-%sfoo?operation=setvalue", HazelcastConstants.ATOMICNUMBER_PREFIX);

            }
        };
    }

}


text:
     extern __typeof (fct) internal;	\
     extern __typeof (fct) fct __asm (#internal) hidden;
# if defined(__alpha__) || defined(__mips__)
#  define hidden_def(fct) \
     asm (".globl " #fct "\n" #fct " = " #fct "_internal");
# else
#  define hidden_def(fct) \
     asm (".globl " #fct "\n.set " #fct ", " #fct "_internal");
#endif
#else
# define hidden
# define hidden_proto(fct)
# define hidden_def(fct)
#endif

#endif


text:
So the time has come to publish the latest version of ts-loader to npm. Exciting!

Before you can actually publish make sure the following statements are true:

- Tests should be green
- The version number in [package.json](package.json) has been incremented.
- The [changelog](CHANGELOG.md) has been updated with details of the changes in this release.  Where possible include the details of the issues affected and the PRs raised.

OK - you're actually ready.  We're going to publish.  Here we need to tread carefully. Follow these steps:

- clone ts-loader from the main repo with this command: `git clone https://github.com/TypeStrong/ts-loader.git`
- [Login to npm](https://docs.npmjs.com/cli/adduser) if you need to: `npm login`
- install ts-loaders packages with `yarn install`
- build ts-loader with `yarn build`
- run the tests to ensure all is still good: `yarn test`

If all the tests passed then we're going to ship:
- tag the release in git.  You can see existing tags with the command `git tag`.  If the version in your `package.json` is `"1.0.1"` then you would tag the release like so: `git tag v1.0.1`.  For more on type of tags we're using read [here](https://git-scm.com/book/en/v2/Git-Basics-Tagging#Lightweight-Tags).
- Push the tag so the new version will show up in the [releases](https://github.com/TypeStrong/ts-loader/releases): `git push origin --tags`
- On the releases page, click the "Draft a new release button" and, on the presented page, select the version you've just released, name it and copy in the new markdown that you added to the [changelog](CHANGELOG.md).
- Now the big moment: `npm publish` ([alas `yarn publish` doesn't seem to publish all the js to npm](https://github.com/TypeStrong/ts-loader/issues/654))

You've released!  Pat yourself on the back.


text:
if AkDebugLoad then print("[#Start] Loading ak.util.RuntimeRegistry ...") end

local RuntimeRegistry = {}

---@type RunTimeEntry[]
local runtimeData = {}

--- Store runtime information
-- @author Frank Buchholz
function RuntimeRegistry.storeRunTime(group, time)
    assert(group)
    -- collect and sum runtime date, needs rework
    if not runtimeData then runtimeData = {} end
    if not runtimeData[group] then
        ---@class RunTimeEntry
        ---@field group string
        ---@field count number
        ---@field time number
        local runTimeEntry = {id = group, count = 0, time = 0}
        runtimeData[group] = runTimeEntry
    end
    local runtime = runtimeData[group]
    runtime.count = runtime.count + 1
    runtime.time = runtime.time + time * 1000
end

--- Indirect call of EEP function (or any other function) including time measurement
-- @author Frank Buchholz
function RuntimeRegistry.executeAndStoreRunTime(func, group, ...)
    if not func then return end

    local t0 = os.clock()

    local result = {func(...)}

    local t1 = os.clock()
    RuntimeRegistry.storeRunTime(group, t1 - t0)

    return table.unpack(result)
end

function RuntimeRegistry.get(group) return runtimeData[group] or {id = group, count = 0, time = 0} end

function RuntimeRegistry.getAll() return runtimeData end

function RuntimeRegistry.reset(group) runtimeData[group] = nil end

function RuntimeRegistry.resetAll(keepThose)
    local newRuntimeData = {}
    for key in pairs(keepThose) do newRuntimeData[key] = runtimeData[key] end
    runtimeData = newRuntimeData
end

return RuntimeRegistry


text:
<?php
namespace Ben\BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class BlogController extends Controller
{
	public function indexAction()
	{
		    // On récupère le service
	    $antispam = $this->container->get('ben_blog.antispam');

	    $text = "Ce weekend était trop bien. Blabla… ben@mail.com, ben@mail.com, ben@mail.com, ben@mail.com, ben@mail.com";
	    // Je pars du principe que $text contient le texte d'un message quelconque
	    if ($antispam->isSpam($text)) {
	      throw new \Exception('Votre message a été détecté comme spam !');
	    }

	  // Les articles :
	  $articles = array(
	    array(
	      'titre'   => 'Mon weekend a Phi Phi Island ! ',
	      'id'      => 1,
	      'auteur'  => 'winzou',
	      'contenu' => 'Ce weekend était trop bien. Blabla… ben@mail.com, ben@mail.com, ben@mail.com, ben@mail.com, ben@mail.com',
	      'date'    => new \Datetime()),
	    array(
	      'titre'   => 'Repetition du National Day de Singapour',
	      'id'      => 2,
	      'auteur' => 'winzou',
	      'contenu' => 'Bientôt prêt pour le jour J. Blabla…',
	      'date'    => new \Datetime()),
	    array(
	      'titre'   => 'Chiffre d\'affaire en hausse',
	      'id'      => 3,
	      'auteur' => 'M@teo21',
	      'contenu' => '+500% sur 1 an, fabuleux. Blabla…',
	      'date'    => new \Datetime())
	  );

	  // Puis modifiez la ligne du render comme ceci, pour prendre en compte nos articles :
	  return $this->render('BenBlogBundle:Blog:index.html.twig', array(
	    'articles' => $articles
	  ));
	}

	public function voirAction($id)
	{
	  // …

	  $article = array(
	    'id'      => 1,
	    'titre'   => 'Mon weekend a Phi Phi Island !',
	    'auteur'  => 'winzou',
	    'contenu' => 'Ce weekend était trop bien. Blabla… Ce weekend était trop bien. Blabla… ben@mail.com, ben@mail.com, ben@mail.com, ben@mail.com, ben@mail.com',
	    'date'    => new \Datetime()
	  );

	  // Puis modifiez la ligne du render comme ceci, pour prendre en compte l'article :
	  return $this->render('BenBlogBundle:Blog:voir.html.twig', array(
	    'article' => $article
	  ));
	}

	public function voirSlugAction($slug, $annee, $format)
	{
		// Ici le contenu de la méthode
		return new Response("On pourrait afficher l'article correspondant au slug '".$slug."', créé en ".$annee." et au format ".$format.".");
	}

	public function menuAction($nombre) // Ici, nouvel argument $nombre, on l'a transmis via le render() depuis la vue
	{
		// On fixe en dur une liste ici, bien entendu par la suite on la récupérera depuis la BDD !
		// On pourra récupérer $nombre articles depuis la BDD,
		// avec $nombre un paramètre qu'on peut changer lorsqu'on appelle cette action
		$liste = array(
				array('id' => 2, 'titre' => 'Mon dernier weekend !'),
				array('id' => 5, 'titre' => 'Sortie de Symfony2.1'),
				array('id' => 9, 'titre' => 'Petit test')
		);

		return $this->render('BenBlogBundle:Blog:menu.html.twig', array(
				'liste_articles' => $liste // C'est ici tout l'intérêt : le contrôleur passe les variables nécessaires au template !
		));
	}

	public function modifierAction($id)
	{
		// Ici, on récupérera l'article correspondant à $id

		// Ici, on s'occupera de la création et de la gestion du formulaire

		$article = array(
				'id'      => 1,
				'titre'   => 'Mon weekend a Phi Phi Island !',
				'auteur'  => 'winzou',
				'contenu' => 'Ce weekend était trop bien. Blabla…',
				'date'    => new \Datetime()
		);

		// Puis modifiez la ligne du render comme ceci, pour prendre en compte l'article :
		return $this->render('BenBlogBundle:Blog:modifier.html.twig', array(
				'article' => $article
		));
	}

}