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

<TITLE>
Triple
</TITLE>

<META NAME="date" CONTENT="2014-10-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

eu.newsreader.eventcoreference.objects

Class Triple

java.lang.Object
  eu.newsreader.eventcoreference.objects.Triple

public class Triple
extends java.lang.Object

Created with IntelliJ IDEA.
 User: kyoto
 Date: 10/11/13
 Time: 6:35 PM
 To change this template use File | Settings | File Templates.

Constructor Summary

Triple()

Triple(java.lang.String predicate,
       java.lang.String subject,
       java.lang.String object)

Method Summary

 void
addComment(java.lang.String comment)

 void
addMentions(java.lang.String mention)

 java.lang.String
getComment()

 java.lang.String
getId()

 java.util.ArrayList<java.lang.String>
getMentions()

 java.lang.String
getObject()

 java.lang.String
getPredicate()

 java.lang.String
getSubject()

 void
setComment(java.lang.String comment)

 void
setId(java.lang.String id)

 void
setMentions(java.util.ArrayList<java.lang.String> mentions)

 void
setObject(java.lang.String object)

 void
setPredicate(java.lang.String predicate)

 void
setSubject(java.lang.String subject)

 java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

Triple

public Triple()

Triple

public Triple(java.lang.String predicate,
              java.lang.String subject,
              java.lang.String object)

Method Detail

getComment

public java.lang.String getComment()

setComment

public void setComment(java.lang.String comment)

addComment

public void addComment(java.lang.String comment)

getMentions

public java.util.ArrayList<java.lang.String> getMentions()

setMentions

public void setMentions(java.util.ArrayList<java.lang.String> mentions)

addMentions

public void addMentions(java.lang.String mention)

getObject

public java.lang.String getObject()

setObject

public void setObject(java.lang.String object)

getPredicate

public java.lang.String getPredicate()

setPredicate

public void setPredicate(java.lang.String predicate)

getSubject

public java.lang.String getSubject()

setSubject

public void setSubject(java.lang.String subject)

getId

public java.lang.String getId()

setId

public void setId(java.lang.String id)

toString

public java.lang.String toString()

Overrides:
toString in class java.lang.Object

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package com.udacity.gamedev.cyclicoverlap.client;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.udacity.gamedev.cyclicoverlap.CyclicOverlap;

public class HtmlLauncher extends GwtApplication {

        @Override
        public GwtApplicationConfiguration getConfig () {
                return new GwtApplicationConfiguration(480, 320);
        }

        @Override
        public ApplicationListener getApplicationListener () {
                return new CyclicOverlap();
        }
}

redpajama_set_name: RedPajamaGithub


text:
import os
import re
import json
from data import variables
from collections import OrderedDict

bmc_rec_pattern = '^=(.*)\n(.*)\n(.*)\n(.*)\n(.*)'
bmc_prop_pattern = [r"\w+", r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}", '443']
bmc_rec_prop = ['hostname', 'address', 'port', 'txt']

class Exception(Exception):
    def __init__(self, exc_value):
        self.exc_value = exc_value

    def __str__(self):
        return repr(self.exc_value)

def Check_bmc_record_exists(bmc_records, bmc_ip):
    r"""
    Parse the BMC records to check for passed input.

    Description of arguments:
    bmc_records            Contains the list of discoverd BMC records.
    bmc_ip                 BMC ip address.
    """

    try:
        for bmc_key, bmc_val in bmc_records.items():
            temp_ip = bmc_val.get('address', None)
            if bmc_ip.strip() == temp_ip.strip():
                return True
        else:
            return False
    except Exception as exc_obj:
        return exc_obj

def validate_bmc_properties(bmc_prop_pattern, bmc_prop, bmc_value,
                            bmc_rec_valid):
    r"""
    This function is to check pattern match in bmc properties.

    Description of arguments:
    bmc_prop_pattern       Regex pattern.
    bmc_prop               BMC property (e.g. hostname, address, port).
    bmc_value              BMC property value.
    bmc_rec_valid          Contain BMC properties record.
    """

    try:
        status = \
            [lambda bmc_prop: re.search(bmc_prop_pattern, bmc_prob),
                bmc_value]
        if None in status:
            bmc_rec_valid[bmc_prop] = None
    except Exception as exc_obj:
        return exc_obj
    finally:
        return bmc_rec_valid

def bmc_record_validation(bmc_rec_valid):
    r"""
    Parse the BMC records to validate the data is valid.

    Description of arguments:
    bmc_rec_valid          Contain BMC properties record.
    """

    try:
        for bmc_prop_key, bmc_pattern_val in \
                zip(bmc_rec_prop, bmc_prop_pattern):
            bmc_prop_value = bmc_rec_valid.get(bmc_prop_key, False)
            if bmc_rec_valid[bmc_prop_key] is not False:
                valid_status = validate_bmc_properties(bmc_pattern_val,
                                                       bmc_prop_key,
                                                       bmc_prop_value,
                                                       bmc_rec_valid)
                if None not in bmc_rec_valid.values():
                    return bmc_rec_valid
                else:
                    return None
    except Exception as exc_obj:
        return exc_obj

def bmc_inventory(service_type, bmc_inv_record):
    r"""
    Parse single record of BMC inventory and pack to dictionary form.

    Description of arguments:
    service_type       Service type (e.g. _obmc_rest._tcp, _obmc_redfish._tcp).
    bmc_inv_record     Individual BMC inventory record.

    This function will return this variable i.e.
    bmc_inv in dictionary form as mention below.

    Below are the discovered BMC detail.

    [service]:          _obmc_XXXX._tcp
    [hostname]:         System Name
    [address]:          XXX.XXX.XXX.XXX
    [port]:             XXX
    [txt]:
    """

    try:
        exc_obj = None
        bmc_inv = OrderedDict()
        service_count = 0
        for line in bmc_inv_record.split('\n'):
            if line == "":
                pass
            elif service_type in line:
                bmc_inv['service'] = service_type
                service_count += 1
            elif not line.startswith('=') and service_count == 1:
                bmc_inv[line.split('=')[0].strip()] = \
                    str(line.split('=')[-1].strip())[1:-1]
    except Exception as exc_obj:
        return exc_obj
    finally:
        valid_status = bmc_record_validation(bmc_inv)
        if valid_status is None:
            return None, exc_obj
        else:
            return valid_status, exc_obj

def get_bmc_records(service_type, bmc_records):
    r"""
    Parse the string to filter BMC discovery.

    Description of arguments:
    service_type     Service type (e.g. RESTService, RedfishService).
    bmc_records      Contains the list of discoverd BMC records.

    This function will return this variable i.e.
    bmc_inv_list in dictionary form as mention below.

    Below are the list of discovered BMC details.
    [1]:
        [service]:          _obmc_XXXX._tcp
        [hostname]:         System Name
        [address]:          XXX.XXX.XXX.XXX
        [port]:             XXX
        [txt]:
    [2]:
        [service]:          _obmc_XXXX._tcp
        [hostname]:         System Name
        [address]:          XXX.XXX.XXX.XXX
        [port]:             XXX
        [txt]:
    """

    try:
        count = 0
        exe_obj = None
        bmc_inv_list = OrderedDict()
        for match in re.finditer(bmc_rec_pattern, bmc_records,
                                 re.MULTILINE):
            bmc_record, exc_msg = \
                bmc_inventory(service_type, match.group())
            if bmc_record is not None and exc_msg is None:
                count += 1
                bmc_inv_list[count] = bmc_record
    except Exception as exe_obj:
        return exe_obj
    finally:
        if len(bmc_inv_list) == 0:
            '', exe_obj
        else:
            return bmc_inv_list, exe_obj


text:
from django.conf import settings

def third_party_tracking_ids(request):
    """
    Retrieve 3rd-party tracking IDs from the settings file and add them to the
    request context.
    """
    return {
        'google_analytics_tracking_id': settings.GOOGLE_ANALYTICS_TRACKING_ID,
        'addthis_publisher_id': settings.ADDTHIS_PUBLISHER_ID,
    }


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
       ">

	<!-- 扫描注解Bean -->
	<context:component-scan base-package="com.crsp">
		<!-- 通过exclude-filter 把所有 @Controller注解的表现层控制器组件排除 -->
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- 加载配置文件 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value> classpath:config/jdbc.properties</value>
			</list>
		</property>
	</bean>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${driverClassName}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
	</bean>

	<!-- 可追加配置二级缓存 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan">
			<list>
				<value>com.crsp</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.query.substitutions">true 1, false 0</prop>
				<prop key="hibernate.default_batch_fetch_size">16</prop>
				<prop key="hibernate.max_fetch_depth">1</prop>
				<prop key="hibernate.generate_statistics">true</prop>
				<prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
				<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext
				</prop>
			</props>
		</property>
	</bean>

	<!--事务管理的配置 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 配置那些类的方法进行事务管理,需要aopalliance-1.0.jar和aspectjweaver.jar,当前com.neusoft.leehom.service包中的子包,
		类中所有方法需要,还需要参考tx:advice的设置 -->
	<!-- 需要引入tx的命名空间 -->
	<!-- 这是事务通知操作,使用的事务管理器引用自 transactionManager -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 指定哪些方法需要加入事务,这里懒惰一下全部加入,可以使用通配符来只加入需要的方法 -->
			<!-- <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*"
				propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED"
				/> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method
				name="query*" propagation="REQUIRED" read-only="true" /> -->
			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>
	<!-- 需要引入aop的命名空间 -->
	<aop:config>
		<!-- 切入点指明了在执行Service的所有方法时产生事务拦截操作 -->
		<aop:pointcut id="myPointCut" expression="execution(* com.crsp.service.*.*(..))" />
		<!-- 定义了将采用何种拦截操作,这里引用到 txAdvice -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointCut" />
	</aop:config>
</beans>


text:
use std::borrow::{Cow, IntoCow};
use std::fmt;
use std::iter::{Peekable, self};
use std::path::Path;
use std::str::Lines;

use unicode_width::UnicodeWidthStr;

use {BytePos, Kind, Line, Span};

use self::lexer::{Lexer, Token};

pub mod lexer;

/// Parse errors
#[derive(Clone, Copy, Debug)]
pub enum Error<'a> {
    /// Expected these tokens
    Expected(&'static [Token]),
    /// Used `//~^^^` with too many carets, and the adjusted line doesn't exist
    LineDoesntExist,
    /// Used `//~|`, but there is no annotation in the previous line
    NoPrecedingAnnotation,
    /// Unknown compiler message `kind`
    UnknownKind(&'a str),
    /// No token starts with this character
    UnknownStartOfToken(char),
}

impl<'a> fmt::Display for Error<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Expected(toks) => {
                match toks {
                    [tok] => write!(f, "expected token `{}`", tok),
                    toks => {
                        try!(f.write_str("expected one of "));

                        let mut is_first = true;

                        for &tok in toks {
                            if is_first {
                                is_first = false;
                                try!(write!(f, "`{}`", tok))
                            } else {
                                try!(write!(f, ", `{}`", tok))
                            }
                        }

                        Ok(())
                    }
                }
            },
            Error::LineDoesntExist => f.write_str("adjusted line doesn't exist"),
            Error::NoPrecedingAnnotation => f.write_str("no annotation in previous line"),
            Error::UnknownKind(k) => write!(f, "unknown kind `{}`", k),
            Error::UnknownStartOfToken(c) => write!(f, "unknown start of token `{}`", c),
        }
    }
}

/// Formats parser errors into human readable messages
pub fn format_error(path: &Path, source: &str, span: Span, e: Error) -> String {
    let Span(start, end) = span;

    let mut ln = 1;
    let mut start_of_line = 0;
    for line in source.lines() {
        let length = line.len();

        if start_of_line <= start && start <= start_of_line + length {
            let start = start - start_of_line;
            let end = end - start_of_line;
            let ln = ln.to_string();

            let path = path.to_string_lossy();
            let mut error = format!("{path}:{line}:{start}: {line}:{end} error: {message}\n",
                                    path = path,
                                    line = ln,
                                    start = start.to_string(),
                                    end = end.to_string(),
                                    message = e.to_string());
            error.push_str(&format!("{path}:{line} {source}\n",
                                    path = path,
                                    line = ln,
                                    source = line));
            let ws =
                UnicodeWidthStr::width(&*path) +
                UnicodeWidthStr::width(":") +
                UnicodeWidthStr::width(&*ln) +
                UnicodeWidthStr::width(" ") +
                UnicodeWidthStr::width(&line[..start]);
            let span = UnicodeWidthStr::width(&line[start..end]).checked_sub(1).unwrap_or(0);
            error.push_str(&format!("{whitespace}^{span}",
                                    whitespace = iter::repeat(' ').take(ws).collect::<String>(),
                                    span = iter::repeat('~').take(span).collect::<String>()));

            return error
        }

        start_of_line += length + "\n".len();
        ln += 1;
    }

    // NB we always have *one* error that will be formatted while scanning the lines of the source
    // code. That formatted string will be returned as soon as the error is found, therefore this
    // part is unreachable
    unreachable!();
}

/// A `cfail` annotation parser.
///
/// Annotations can take any of the following forms:
///
/// - An inline annotation, the compiler message points to this line
///
/// ``` text
/// 0.foo();  //~ <kind> <message>
/// ```
///
/// - An adjusted annotation, the compiler message points to a line that's `adjust` lines above
///   this one, where `adjust` is the number of `^`s.
///
/// ``` text
/// 0.foo();
/// //~^ <kind> <message>
/// ```
///
/// - A multi-line annotation.
///
/// ``` text
/// let _: i8 = 0u8;
/// //~^ <kind> <message>
/// //~| <continuation of message>
/// //~| <continuation of message>
/// ```
///
/// - Shared annotations. All these annotations share the same line number.
///
/// ``` text
/// 0.count_zeros();
/// //~^ <kind> <message>
/// //~| <kind> <message>
/// //~| <kind> <message>
/// ```
pub struct Parser<'a> {
    curr_line: Line,
    last_line: Option<usize>,
    last_match: Option<Line>,
    lines: Peekable<Lines<'a>>,
    start_of_line: BytePos,
    state: Result<(), ()>,
}

impl<'a> Parser<'a> {
    /// Creates a parser for this source file
    pub fn new(source: &'a str) -> Parser<'a> {
        Parser {
            curr_line: Line(0),
            last_line: None,
            last_match: None,
            lines: source.lines().peekable(),
            start_of_line: 0,
            state: Ok(()),
        }
    }

    fn fatal<T>(&mut self, span: Span, e: Error<'a>) -> Option<Result<T, (Span, Error<'a>)>> {
        self.state = Err(());
        Some(Err((span + self.start_of_line, e)))
    }

    fn next_line(&mut self) -> Option<&'a str> {
        self.lines.next().map(|line| {
            if let Some(len) = self.last_line {
                self.start_of_line += len + "\n".len();
            }
            self.last_line = Some(line.len());
            self.curr_line = self.curr_line + 1;

            line
        })
    }
}

impl<'a> Iterator for Parser<'a> {
    type Item = Result<(Line, Kind, Cow<'a, str>), (Span, Error<'a>)>;

    fn next(&mut self) -> Option<Result<(Line, Kind, Cow<'a, str>), (Span, Error<'a>)>> {
        // Any kind
        const ANY: Kind = Kind::Error;
        const CARET_WS: &'static [Token] = &[Token::Caret, Token::Whitespace];
        const COLON_OR_WS: &'static [Token] = &[Token::Caret, Token::Or, Token::Whitespace];
        const COLON_WS: &'static [Token] = &[Token::Colon, Token::Whitespace];
        const K: &'static [Token] = &[Token::Kind(ANY)];
        const START: &'static str = "//~";

        if let Err(_) = self.state {
            return None
        }

        while let Some(line) = self.next_line() {
            if let Some(pos) = line.find(START) {
                let start = pos + START.len();
                let mut lexer = Lexer::new(&line[start..], start).peekable();

                let ln = match lexer.next() {
                    None => {
                        let span = Span(start, start);
                        return self.fatal(span, Error::Expected(COLON_OR_WS))
                    },
                    Some((span, Err(e))) => return self.fatal(span, e),
                    // adjusted annotation
                    Some((span, Ok(Token::Caret))) => {
                        let mut adj = 1;

                        loop {
                            match lexer.next() {
                                Some((_, Ok(Token::Caret))) => adj += 1,
                                Some((_, Ok(Token::Whitespace))) => break,
                                Some((span, Err(e))) => return self.fatal(span, e),
                                Some((span, Ok(_))) => {
                                    return self.fatal(span, Error::Expected(CARET_WS))
                                },
                                None => {
                                    let start = match lexer.peek() {
                                        None => line.len(),
                                        Some(&(span, _)) => span.0,
                                    };
                                    let span = Span(start, start);

                                    return self.fatal(span, Error::Expected(CARET_WS))
                                }
                            }
                        }

                        if let Some(ln) = self.curr_line - adj {
                            ln
                        } else {
                            return self.fatal(span, Error::LineDoesntExist)
                        }
                    },
                    // shared annotation
                    Some((span, Ok(Token::Or))) => {
                        if let Some(ln) = self.last_match {
                            ln
                        } else {
                            return self.fatal(span, Error::NoPrecedingAnnotation)
                        }
                    },
                    // inline annotation
                    Some((_, Ok(Token::Whitespace))) => self.curr_line,
                    Some((span, Ok(_))) => return self.fatal(span, Error::Expected(COLON_OR_WS)),
                };

                // eat whitespaces
                while let Some(&(_, Ok(Token::Whitespace))) = lexer.peek() {
                    lexer.next();
                }

                // <kind>
                let kind = match lexer.next() {
                    Some((_, Ok(Token::Kind(kind)))) => kind,
                    Some((span, _)) => return self.fatal(span, Error::Expected(K)),
                    None => {
                        let start = match lexer.peek() {
                            None => line.len(),
                            Some(&(span, _)) => span.0,
                        };

                        return self.fatal(Span(start, start), Error::Expected(K))
                    },
                };

                // optional `:`
                match lexer.peek() {
                    Some(&(_, Ok(Token::Colon))) => {
                        lexer.next();
                    },
                    Some(&(_, Ok(Token::Whitespace))) => {},
                    Some(&(span, _)) => {
                        return self.fatal(span, Error::Expected(COLON_WS))
                    },
                    None => {},
                }

                // eat whitespaces
                while let Some(&(_, Ok(Token::Whitespace))) = lexer.peek() {
                    lexer.next();
                }

                let start = match lexer.peek() {
                    None => line.len(),
                    Some(&(span, _)) => span.0,
                };

                self.last_match = Some(ln);

                let mut message = line[start..].into_cow();

                // check if the message is multi-line
                loop {
                    if let Some(line) = self.lines.peek() {
                        if let Some(pos) = line.find("//~|") {
                            const DUMMY: BytePos = 0;

                            let start = pos + "//~|".len();
                            let line = line[start..].trim();
                            let mut lexer = Lexer::new(line, DUMMY);

                            if let Some((_, Ok(Token::Kind(_)))) = lexer.next() {
                                // not multi-line
                                break
                            } else {
                                message.to_mut().push('\n');
                                message.to_mut().push_str(line);
                            }
                        } else {
                            break
                        }
                    } else {
                        break
                    }

                    self.next_line();
                }

                return Some(Ok((ln, kind, message)))
            } else {
                self.last_match = None;
                continue
            }
        }

        None
    }
}


text:
<?php

return [
    'site-name' => 'Site naam',
    'site-description' => 'Site beschrijving',
    'template' => 'Front-end thema',
    'google-analytics' => 'Google Analytics Code',
    'locales' => 'Site talen',
];


text:
@protocol KHFSelectTopicViewControllerDelegate;

@interface KHFSelectTopicViewController : UITableViewController

@property (strong, nonatomic) NSArray *topics;
// 選択されたトピック
@property (nonatomic) NSString *selectedTopic;
// 処理のデリゲート先の参照
@property (weak, nonatomic) id<KHFSelectTopicViewControllerDelegate> delegate;

// インスタンスを取得する
+ (KHFSelectTopicViewController*)getInstance;
// 表示するために
- (void)setTopics:(NSArray *)newTopics;

@end

@protocol KHFSelectTopicViewControllerDelegate <NSObject>

- (void)applySelectedTopic:(NSString *)topic;

@end


text:
<?php

if (!defined('SMF'))
	die('No direct access...');

/**
 * Config array for chaning the karma settings
 * Accessed  from ?action=admin;area=featuresettings;sa=karma;
 *
 * @param $return_config
 *
 * @return array
 */
function ModifyKarmaSettings($return_config = false)
{
	global $txt, $scripturl, $context, $modSettings;

	if (empty($modSettings['karmaMode']))
		$config_vars = array(
			array('select', 'karmaMode', explode('|', $txt['karma_options'])),
		);
	else
		$config_vars = array(
			// Karma - On or off?
			array('select', 'karmaMode', explode('|', $txt['karma_options'])),
			'',
			// Who can do it.... and who is restricted by time limits?
			array('int', 'karmaMinPosts', 6, 'postinput' => strtolower($txt['posts'])),
			array('float', 'karmaWaitTime', 6, 'postinput' => $txt['hours']),
			array('check', 'karmaTimeRestrictAdmins'),
		);

	call_integration_hook('integrate_karma_settings', array(&$config_vars));

	if ($return_config)
		return $config_vars;

	// Saving?
	if (isset($_GET['save']))
	{
		checkSession();

		call_integration_hook('integrate_save_karma_settings');

		saveDBSettings($config_vars);
		$_SESSION['adm-save'] = true;
		redirectexit('action=admin;area=featuresettings;sa=karma');
	}

	$context['post_url'] = $scripturl . '?action=admin;area=featuresettings;save;sa=karma';
	$context['settings_title'] = $txt['karma'];

	loadLanguage('ManageKarma');
	prepareDBSettingContext($config_vars);
}


text:
package systemtest.com.avalon.mock;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;

import java.io.File;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

import com.avalon.mock.element.HtmlElement;
import com.avalon.mock.factory.HtmlElementFactory;

public class WithoutDTOTest extends AbstractSystemTest {

	@Test
	public void allFieldsShouldBeFilled() throws Exception {
		String url = new File("testSample/sample.html").getAbsolutePath();
		webDriver = new FirefoxDriver();
		webDriver.get(url);

		for (String availableFormElement : availableFormElements) {
			List<WebElement> elements = webDriver.findElements(By.cssSelector(availableFormElement));

			for (WebElement webElement : elements) {
				HtmlElement htmlElement = HtmlElementFactory.getInstanceByFormElement(availableFormElement, webElement, webDriver);
				htmlElement.execute();
			}
		}

		assertThat(StringUtils.isNotEmpty(getElementByName(inputTextName).getAttribute("value")), is(true));

		final String email = getElementByName(inputEmailName).getAttribute("value");
		assertThat(StringUtils.isNotEmpty(email), is(true));
		assertThat(email.matches(EMAIL_REGEX), is(true));

		String checkboxesCheckedCssSelector = String.format(checkboxesCheckedCssSelectorTemplate, checkboxName);
		List<WebElement> checkboxesCheckedList = getElementsByCssSelector(checkboxesCheckedCssSelector);
		assertThat(checkboxesCheckedList.size(), equalTo(3));

		String radiosCheckedCssSelector = String.format(radiosCheckedCssSelectorTemplate, radioName);
		List<WebElement> radiosCheckedList = getElementsByCssSelector(radiosCheckedCssSelector);
		assertThat(radiosCheckedList.size(), equalTo(1));

		String selectCssSelector = String.format(selectCssSelectorTemplate, selectId);
		WebElement selectElement = getElementByCssSelector(selectCssSelector);
		Select select = new Select(selectElement);
		assertThat(select.getAllSelectedOptions().size(), equalTo(1));

	}

}


text:
import {Dialog, log} from 'deepdialog';
import {MainNLP,imageHandler} from './maindialog';

export const YesNoDialog = new Dialog({
  name: 'YesNoDialog',
  description: 'Ask yes or no question, use NLP to handle message - return Yes or No'
});

YesNoDialog.nlpModelName = 'MainNLP';

YesNoDialog.onIntent('yesno_affirmative', async function (session) {
  session.finish('Yes');
});

YesNoDialog.onIntent('yesno_negative', async function (session) {
  session.finish('No');
});

YesNoDialog.onIntent('image_input', async function (session, {entities}, {message}) {
  if (imageHandler(session,message)) {
    session.finish('Yes');
  }
  else {
    await session.send({text: `I\'m so sorry, but I\'m still working on recognizing stickers and images...until I figure it out please use text to speak with me.`});
  }
});

YesNoDialog.onRecovery(async function (session, message) {
  await session.send({text: `I\'m very sorry, I didn\'t understand "${message.text}".`});
});


text:
using tonic::ToDart;

namespace flutter {

IMPLEMENT_WRAPPERTYPEINFO(ui, ImageShader);

void ImageShader::Create(Dart_Handle wrapper) {
  auto res = fml::MakeRefCounted<ImageShader>();
  res->AssociateWithDartWrapper(wrapper);
}

Dart_Handle ImageShader::initWithImage(CanvasImage* image,
                                       SkTileMode tmx,
                                       SkTileMode tmy,
                                       int filter_quality_index,
                                       Dart_Handle matrix_handle) {
  if (!image) {
    return ToDart("ImageShader constructor called with non-genuine Image.");
  }

  image_ = image->image();
  tonic::Float64List matrix4(matrix_handle);
  SkMatrix local_matrix = ToSkMatrix(matrix4);
  matrix4.Release();
  sampling_is_locked_ = filter_quality_index >= 0;
  DlImageSampling sampling =
      sampling_is_locked_ ? ImageFilter::SamplingFromIndex(filter_quality_index)
                          : DlImageSampling::kLinear;
  cached_shader_ = UIDartState::CreateGPUObject(sk_make_sp<DlImageColorSource>(
      image_, ToDl(tmx), ToDl(tmy), sampling, &local_matrix));
  return Dart_Null();
}

std::shared_ptr<DlColorSource> ImageShader::shader(DlImageSampling sampling) {
  if (sampling_is_locked_) {
    return cached_shader_.skia_object()->with_sampling(
        cached_shader_.skia_object()->sampling());
  }
  // It might seem that if the sampling is locked we can just return the
  // cached version, but since we need to hold the cached shader in a
  // Skia GPU wrapper, and that wrapper requires an sk_sp<>, we are holding
  // an sk_sp<> version of the shared object and we need a shared_ptr version.
  // So, either way, we need the with_sampling() method to shared_ptr'ify
  // our copy.
  // If we can get rid of the need for the GPU unref queue, then this can all
  // be simplified down to just a shared_ptr.
  return cached_shader_.skia_object()->with_sampling(sampling);
}

int ImageShader::width() {
  return image_->width();
}

int ImageShader::height() {
  return image_->height();
}

void ImageShader::dispose() {
  cached_shader_.reset();
  image_.reset();
  ClearDartWrapper();
}

ImageShader::ImageShader() = default;

ImageShader::~ImageShader() = default;

}  // namespace flutter


text:
package c

import "./b"

func F() interface{} {
	go func(){}() // make it non-inlineable
	return b.F()
}

func P() interface{} {
	go func(){}() // make it non-inlineable
	return b.P()
}


text:
using NUnit.Framework;
using Plivo.Exception;

namespace Plivo.Test.Resources
{
    [TestFixture]
    public class TestExceptions : BaseTestCase
    {
        [Test]
        public void TestThrowsPlivoValidationException()
        {
            var ex =
                Assert.Throws<PlivoValidationException>(
                    () => Api.Application.Create(
                        appName: ""));
            Assert.That(ex.Message, Is.EqualTo("appName is mandatory, can not be null or empty"));
        }

        [Test]
        public void TestThrowsPlivoException()
        {
            var ex =
                Assert.Throws<PlivoValidationException>(
                    () => Api.Application.Create(
                        appName: "", answerUrl: "http://www.com", answerMethod: null));
            Assert.That(ex.Message, Is.EqualTo("appName is mandatory, can not be null or empty"));
        }

        [Test]
        public void TestLimitException()
        {
            var ex =
                Assert.Throws<PlivoValidationException>(
                    code: () => Api.Call.List(limit: 112));
            Assert.That(ex.Message, Is.EqualTo("limit:112 is out of range [0,20]"));
        }
    }
}


text:
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License. You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<script type="text/javascript">
<!--
function checkConfig()
{
  if (editconnection.port.value != "" && !isInteger(editconnection.port.value))
  {
    alert("$Encoder.bodyJavascriptEscape($ResourceBundle.getString('EmailConnector.PortMustBeIntegerOrBlank'))");
    editconnection.port.focus();
    return false;
  }
  return true;
}

function checkConfigForSave()
{
  if (editconnection.server.value == "")
  {
    alert("$Encoder.bodyJavascriptEscape($ResourceBundle.getString('EmailConnector.EnterAMailServerHostName'))");
    SelectTab("$Encoder.bodyJavascriptEscape($ResourceBundle.getString('EmailConnector.Server'))");
    editconnection.server.focus();
    return false;
  }
  if (editconnection.port.value != "" && !isInteger(editconnection.port.value))
  {
    alert("$Encoder.bodyJavascriptEscape($ResourceBundle.getString('EmailConnector.PortMustBeIntegerOrBlank'))");
    SelectTab("$Encoder.bodyJavascriptEscape($ResourceBundle.getString('EmailConnector.Server'))");
    editconnection.port.focus();
    return false;
  }
  return true;
}

function addProperty()
{
  postFormSetAnchor("property"); //Repost the form and send the browser to property anchor
}

function SpecOp(n, opValue, anchorvalue)
{
  eval("editconnection."+n+".value = \""+opValue+"\"");
  postFormSetAnchor(anchorvalue);
}

function FindDelete(n)
{
  SpecOp("findop_"+n, "Delete", "find_"+n);
}

function FindAdd(n)
{
  if (editconnection.findname.value == "")
  {
    alert("$Encoder.bodyJavascriptEscape($ResourceBundle.getString('EmailConnector.PleaseSelectAConfigurationParameterName'))");
    editconnection.findname.focus();
    return;
  }
  if (editconnection.findvalue.value == "")
  {
    alert("$Encoder.bodyJavascriptEscape($ResourceBundle.getString('EmailConnector.ValueCannotBeBlank'))");
    editconnection.findvalue.focus();
    return;
  }
  SpecOp("findop", "Add", "find_"+n);
}

//-->
</script>


text:
#region Copyright

#endregion

using System;
using System.Collections.Generic;
using System.Windows.Controls;
using Dynamo.Controls;
using Dynamo.Models;
using Dynamo.Wpf;
using ProtoCore.AST.AssociativeAST;
using Wosad.Common.CalculationLogger;
using Wosad.Dynamo.Common;
using Dynamo.Nodes;
using System.Xml;
using Dynamo.Graph;
using Dynamo.Graph.Nodes;

namespace Wosad.Steel.AISC.HSS
{

    /// <summary>
    ///HSS truss connection member type selection
    /// </summary>

    [NodeName("HSS connection member type selection")]
    [NodeCategory("Wosad.Steel.AISC.HSS")]
    [NodeDescription("HSS connection member type selection")]
    [IsDesignScriptCompatible]
    public class HssConnectionMemberTypeSelection : UiNodeBase
    {

        public HssConnectionMemberTypeSelection()
        {

            //OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)"));
            OutPortData.Add(new PortData("HssConnectionMemberType", "Specifies if the connection members are circular HSS (CHS) or rectangular HSS"));
            RegisterAllPorts();
            SetDefaultParameters();
            //PropertyChanged += NodePropertyChanged;
        }

        private void SetDefaultParameters()
        {
            //ReportEntry="";
            HssTrussConnectionMemberType = "Rhs";
        }

        /// <summary>
        ///     Gets the type of this class, to be used in base class for reflection
        /// </summary>
        protected override Type GetModelType()
        {
            return GetType();
        }

        #region Properties

        #region InputProperties

	    #endregion

        #region OutputProperties

		#region HssTrussConnectionMemberTypeProperty

		/// <summary>
		/// HssTrussConnectionMemberType property
		/// </summary>
		/// <value>Specifies if the connection members are circular HSS (CHS) or rectangular HSS</value>
		public string _HssTrussConnectionMemberType;

		public string HssTrussConnectionMemberType
		{
		    get { return _HssTrussConnectionMemberType; }
		    set
		    {
		        _HssTrussConnectionMemberType = value;
		        RaisePropertyChanged("HssTrussConnectionMemberType");
		        OnNodeModified();
		    }
		}
		#endregion

        #region ReportEntryProperty

        /// <summary>
        /// log property
        /// </summary>
        /// <value>Calculation entries that can be converted into a report.</value>

        public string reportEntry;

        public string ReportEntry
        {
            get { return reportEntry; }
            set
            {
                reportEntry = value;
                RaisePropertyChanged("ReportEntry");
                OnNodeModified();
            }
        }

        #endregion

        #endregion
        #endregion

        #region Serialization

        /// <summary>
        ///Saves property values to be retained when opening the node
        /// </summary>
        protected override void SerializeCore(XmlElement nodeElement, SaveContext context)
        {
            base.SerializeCore(nodeElement, context);
            nodeElement.SetAttribute("HssTrussConnectionMemberType", HssTrussConnectionMemberType);
        }

        /// <summary>
        ///Retrieved property values when opening the node
        /// </summary>
        protected override void DeserializeCore(XmlElement nodeElement, SaveContext context)
        {
            base.DeserializeCore(nodeElement, context);
            var attrib = nodeElement.Attributes["HssTrussConnectionMemberType"];
            if (attrib == null)
                return;

            HssTrussConnectionMemberType = attrib.Value;
            //SetComponentDescription();

        }

        #endregion

        /// <summary>
        ///Customization of WPF view in Dynamo UI
        /// </summary>
        public class HssTrussConnectionMemberTypeSelectionViewCustomization : UiNodeBaseViewCustomization,
            INodeViewCustomization<HssConnectionMemberTypeSelection>
        {
            public void CustomizeView(HssConnectionMemberTypeSelection model, NodeView nodeView)
            {
                base.CustomizeView(model, nodeView);

                HssConnectionMemberTypeSelectionView control = new HssConnectionMemberTypeSelectionView();
                control.DataContext = model;

                nodeView.inputGrid.Children.Add(control);
                base.CustomizeView(model, nodeView);
            }

        }
    }
}


text:
class ChromeAppCacheService;
class ExtensionService;
class ExtensionSpecialStoragePolicy;
class FaviconService;
class HostContentSettingsMap;
class PasswordStore;
class PrefProxyConfigTracker;
class PrefService;
class PromoCounter;
class ProtocolHandlerRegistry;
class TestingProfile;
class WebDataService;

namespace android {
class TabContentsProvider;
}

namespace base {
class SequencedTaskRunner;
class Time;
}

namespace chrome_browser_net {
class Predictor;
}

namespace chromeos {
class LibCrosServiceLibraryImpl;
class ResetDefaultProxyConfigServiceTask;
}

namespace content {
class WebUI;
}

namespace fileapi {
class FileSystemContext;
}

namespace history {
class TopSites;
}

namespace net {
class SSLConfigService;
}

namespace user_prefs {
class PrefRegistrySyncable;
}

// Instead of adding more members to Profile, consider creating a
// KeyedService. See
// http://dev.chromium.org/developers/design-documents/profile-architecture
class Profile : public content::BrowserContext {
 public:
  // Profile services are accessed with the following parameter. This parameter
  // defines what the caller plans to do with the service.
  // The caller is responsible for not performing any operation that would
  // result in persistent implicit records while using an OffTheRecord profile.
  // This flag allows the profile to perform an additional check.
  //
  // It also gives us an opportunity to perform further checks in the future. We
  // could, for example, return an history service that only allow some specific
  // methods.
  enum ServiceAccessType {
    // The caller plans to perform a read or write that takes place as a result
    // of the user input. Use this flag when the operation you are doing can be
    // performed while incognito. (ex: creating a bookmark)
    //
    // Since EXPLICIT_ACCESS means "as a result of a user action", this request
    // always succeeds.
    EXPLICIT_ACCESS,

    // The caller plans to call a method that will permanently change some data
    // in the profile, as part of Chrome's implicit data logging. Use this flag
    // when you are about to perform an operation which is incompatible with the
    // incognito mode.
    IMPLICIT_ACCESS
  };

  enum CreateStatus {
    // Profile services were not created due to a local error (e.g., disk full).
    CREATE_STATUS_LOCAL_FAIL,
    // Profile services were not created due to a remote error (e.g., network
    // down during limited-user registration).
    CREATE_STATUS_REMOTE_FAIL,
    // Profile created but before initializing extensions and promo resources.
    CREATE_STATUS_CREATED,
    // Profile is created, extensions and promo resources are initialized.
    CREATE_STATUS_INITIALIZED,
    // Profile creation (managed-user registration, generally) was canceled
    // by the user.
    CREATE_STATUS_CANCELED,
    MAX_CREATE_STATUS  // For histogram display.
  };

  enum CreateMode {
    CREATE_MODE_SYNCHRONOUS,
    CREATE_MODE_ASYNCHRONOUS
  };

  enum ExitType {
    // A normal shutdown. The user clicked exit/closed last window of the
    // profile.
    EXIT_NORMAL,

    // The exit was the result of the system shutting down.
    EXIT_SESSION_ENDED,

    EXIT_CRASHED,
  };

  enum ProfileType {
    REGULAR_PROFILE,  // Login user's normal profile
    INCOGNITO_PROFILE,  // Login user's off-the-record profile
    GUEST_PROFILE,  // Guest session's profile
  };

  class Delegate {
   public:
    virtual ~Delegate();

    // Called when creation of the profile is finished.
    virtual void OnProfileCreated(Profile* profile,
                                  bool success,
                                  bool is_new_profile) = 0;
  };

  // Key used to bind profile to the widget with which it is associated.
  static const char kProfileKey[];

  Profile();
  virtual ~Profile();

  // Profile prefs are registered as soon as the prefs are loaded for the first
  // time.
  static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);

  // Create a new profile given a path. If |create_mode| is
  // CREATE_MODE_ASYNCHRONOUS then the profile is initialized asynchronously.
  static Profile* CreateProfile(const base::FilePath& path,
                                Delegate* delegate,
                                CreateMode create_mode);

  // Returns the profile corresponding to the given browser context.
  static Profile* FromBrowserContext(content::BrowserContext* browser_context);

  // Returns the profile corresponding to the given WebUI.
  static Profile* FromWebUI(content::WebUI* web_ui);

  // content::BrowserContext implementation ------------------------------------

  // Typesafe upcast.
  virtual TestingProfile* AsTestingProfile();

  // Returns sequenced task runner where browser context dependent I/O
  // operations should be performed.
  virtual scoped_refptr<base::SequencedTaskRunner> GetIOTaskRunner() = 0;

  // Returns the name associated with this profile. This name is displayed in
  // the browser frame.
  virtual std::string GetProfileName() = 0;

  // Returns the profile type.
  virtual ProfileType GetProfileType() const = 0;

  // Return the incognito version of this profile. The returned pointer
  // is owned by the receiving profile. If the receiving profile is off the
  // record, the same profile is returned.
  //
  // WARNING: This will create the OffTheRecord profile if it doesn't already
  // exist. If this isn't what you want, you need to check
  // HasOffTheRecordProfile() first.
  virtual Profile* GetOffTheRecordProfile() = 0;

  // Destroys the incognito profile.
  virtual void DestroyOffTheRecordProfile() = 0;

  // True if an incognito profile exists.
  virtual bool HasOffTheRecordProfile() = 0;

  // Return the original "recording" profile. This method returns this if the
  // profile is not incognito.
  virtual Profile* GetOriginalProfile() = 0;

  // Returns whether the profile is managed (see ManagedUserService).
  virtual bool IsManaged() = 0;

  // Returns a pointer to the TopSites (thumbnail manager) instance
  // for this profile.
  virtual history::TopSites* GetTopSites() = 0;

  // Variant of GetTopSites that doesn't force creation.
  virtual history::TopSites* GetTopSitesWithoutCreating() = 0;

  // DEPRECATED. Instead, use ExtensionSystem::extension_service().
  // Retrieves a pointer to the ExtensionService associated with this
  // profile. The ExtensionService is created at startup.
  // TODO(yoz): remove this accessor (bug 104095).
  virtual ExtensionService* GetExtensionService() = 0;

  // Accessor. The instance is created upon first access.
  virtual ExtensionSpecialStoragePolicy*
      GetExtensionSpecialStoragePolicy() = 0;

  // Retrieves a pointer to the PrefService that manages the
  // preferences for this user profile.
  virtual PrefService* GetPrefs() = 0;

  // Retrieves a pointer to the PrefService that manages the preferences
  // for OffTheRecord Profiles.  This PrefService is lazily created the first
  // time that this method is called.
  virtual PrefService* GetOffTheRecordPrefs() = 0;

  // Returns the main request context.
  virtual net::URLRequestContextGetter* GetRequestContext() = 0;

  // Returns the request context used for extension-related requests.  This
  // is only used for a separate cookie store currently.
  virtual net::URLRequestContextGetter* GetRequestContextForExtensions() = 0;

  // Returns the SSLConfigService for this profile.
  virtual net::SSLConfigService* GetSSLConfigService() = 0;

  // Returns the Hostname <-> Content settings map for this profile.
  virtual HostContentSettingsMap* GetHostContentSettingsMap() = 0;

  // Return whether 2 profiles are the same. 2 profiles are the same if they
  // represent the same profile. This can happen if there is pointer equality
  // or if one profile is the incognito version of another profile (or vice
  // versa).
  virtual bool IsSameProfile(Profile* profile) = 0;

  // Returns the time the profile was started. This is not the time the profile
  // was created, rather it is the time the user started chrome and logged into
  // this profile. For the single profile case, this corresponds to the time
  // the user started chrome.
  virtual base::Time GetStartTime() const = 0;

  // Creates the main net::URLRequestContextGetter that will be returned by
  // GetRequestContext(). Should only be called once per ContentBrowserClient
  // object. This function is exposed because of the circular dependency where
  // GetStoragePartition() is used to retrieve the request context, but creation
  // still has to happen in the Profile so the StoragePartition calls
  // ContextBrowserClient to call this function.
  // TODO(ajwong): Remove once http://crbug.com/159193 is resolved.
  virtual net::URLRequestContextGetter* CreateRequestContext(
      content::ProtocolHandlerMap* protocol_handlers,
      content::ProtocolHandlerScopedVector protocol_interceptors) = 0;

  // Creates the net::URLRequestContextGetter for a StoragePartition. Should
  // only be called once per partition_path per ContentBrowserClient object.
  // This function is exposed because the request context is retrieved from the
  // StoragePartition, but creation still has to happen in the Profile so the
  // StoragePartition calls ContextBrowserClient to call this function.
  // TODO(ajwong): Remove once http://crbug.com/159193 is resolved.
  virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
      const base::FilePath& partition_path,
      bool in_memory,
      content::ProtocolHandlerMap* protocol_handlers,
      content::ProtocolHandlerScopedVector protocol_interceptors) = 0;

  // Returns the last directory that was chosen for uploading or opening a file.
  virtual base::FilePath last_selected_directory() = 0;
  virtual void set_last_selected_directory(const base::FilePath& path) = 0;

#if defined(OS_CHROMEOS)
  enum AppLocaleChangedVia {
    // Caused by chrome://settings change.
    APP_LOCALE_CHANGED_VIA_SETTINGS,
    // Locale has been reverted via LocaleChangeGuard.
    APP_LOCALE_CHANGED_VIA_REVERT,
    // From login screen.
    APP_LOCALE_CHANGED_VIA_LOGIN,
    // Source unknown.
    APP_LOCALE_CHANGED_VIA_UNKNOWN
  };

  // Changes application locale for a profile.
  virtual void ChangeAppLocale(
      const std::string& locale, AppLocaleChangedVia via) = 0;

  // Called after login.
  virtual void OnLogin() = 0;

  // Initializes Chrome OS's preferences.
  virtual void InitChromeOSPreferences() = 0;
#endif  // defined(OS_CHROMEOS)

  // Returns the helper object that provides the proxy configuration service
  // access to the the proxy configuration possibly defined by preferences.
  virtual PrefProxyConfigTracker* GetProxyConfigTracker() = 0;

  // Returns the Predictor object used for dns prefetch.
  virtual chrome_browser_net::Predictor* GetNetworkPredictor() = 0;

  // Deletes all network related data since |time|. It deletes transport
  // security state since |time| and it also deletes HttpServerProperties data.
  // Works asynchronously, however if the |completion| callback is non-null, it
  // will be posted on the UI thread once the removal process completes.
  // Be aware that theoretically it is possible that |completion| will be
  // invoked after the Profile instance has been destroyed.
  virtual void ClearNetworkingHistorySince(base::Time time,
                                           const base::Closure& completion) = 0;

  // Returns the home page for this profile.
  virtual GURL GetHomePage() = 0;

  // Returns whether or not the profile was created by a version of Chrome
  // more recent (or equal to) the one specified.
  virtual bool WasCreatedByVersionOrLater(const std::string& version) = 0;

  std::string GetDebugName();

  // Returns whether it is a guest session.
  virtual bool IsGuestSession() const;

  // Did the user restore the last session? This is set by SessionRestore.
  void set_restored_last_session(bool restored_last_session) {
    restored_last_session_ = restored_last_session;
  }
  bool restored_last_session() const {
    return restored_last_session_;
  }

  // Sets the ExitType for the profile. This may be invoked multiple times
  // during shutdown; only the first such change (the transition from
  // EXIT_CRASHED to one of the other values) is written to prefs, any
  // later calls are ignored.
  //
  // NOTE: this is invoked internally on a normal shutdown, but is public so
  // that it can be invoked when the user logs out/powers down (WM_ENDSESSION),
  // or to handle backgrounding/foregrounding on mobile.
  virtual void SetExitType(ExitType exit_type) = 0;

  // Returns how the last session was shutdown.
  virtual ExitType GetLastSessionExitType() = 0;

  // Stop sending accessibility events until ResumeAccessibilityEvents().
  // Calls to Pause nest; no events will be sent until the number of
  // Resume calls matches the number of Pause calls received.
  void PauseAccessibilityEvents() {
    accessibility_pause_level_++;
  }

  void ResumeAccessibilityEvents() {
    DCHECK_GT(accessibility_pause_level_, 0);
    accessibility_pause_level_--;
  }

  bool ShouldSendAccessibilityEvents() {
    return 0 == accessibility_pause_level_;
  }

  // Returns whether the profile is new.  A profile is new if the browser has
  // not been shut down since the profile was created.
  bool IsNewProfile();

  // Checks whether sync is configurable by the user. Returns false if sync is
  // disabled or controlled by configuration management.
  bool IsSyncAccessible();

  // Send NOTIFICATION_PROFILE_DESTROYED for this Profile, if it has not
  // already been sent. It is necessary because most Profiles are destroyed by
  // ProfileDestroyer, but in tests, some are not.
  void MaybeSendDestroyedNotification();

  // Creates an OffTheRecordProfile which points to this Profile.
  Profile* CreateOffTheRecordProfile();

 private:
  bool restored_last_session_;

  // Used to prevent the notification that this Profile is destroyed from
  // being sent twice.
  bool sent_destroyed_notification_;

  // Accessibility events will only be propagated when the pause
  // level is zero.  PauseAccessibilityEvents and ResumeAccessibilityEvents
  // increment and decrement the level, respectively, rather than set it to
  // true or false, so that calls can be nested.
  int accessibility_pause_level_;

  DISALLOW_COPY_AND_ASSIGN(Profile);
};

#if defined(COMPILER_GCC)
namespace BASE_HASH_NAMESPACE {

template<>
struct hash<Profile*> {
  std::size_t operator()(Profile* const& p) const {
    return reinterpret_cast<std::size_t>(p);
  }
};

}  // namespace BASE_HASH_NAMESPACE
#endif

#endif  // CHROME_BROWSER_PROFILES_PROFILE_H_


text:
<?xml version="1.0" encoding="utf-8" ?>
<object name="EventLogListItem"
        connection="EidssConnectionString"
        generator="ObjectGenerator.xslt"
        xmlns="urn:schemas-bv:objectmodel">

	<storage>
		<get name="fn_Event_SelectList" type="fnlist" />
		<count name="spEvent_SelectCount"/>
	</storage>

	<tables>
		<table name="EventLogListItem">
      <properties permissionObject="EventLog"/>
      <help win="EventLogForm"/>
			<searchpanel>
				<item name="datEventDatatime" editor="Date" labelId="datEventDatatime" mandatory="true" range="true"
					  default="DateTime.Today.AddDays(-bv.common.Configuration.BaseSettings.DefaultDateFilter)" />
				<item name="PersonName" editor="Text" labelId="PersonName"/>
				<item name="strInformationString" editor="Text" labelId="strInformationString"/>
				<item name="strNote" editor="Text" labelId="EventLog.strNote"/>

				<item name="idfsEventTypeID" editor="Lookup" labelId="strEventTypeName"	lookupName="EventTypeLookup"
					  lookupType="BaseReference" lookupText="c.name" lookupValue="c.idfsBaseReference"/>
			</searchpanel>

			<grid>
				<item name="idfEventID" key="true" visible="false" />
				<item name="datEventDatatime" format="G" />
				<item name="PersonName"  />
				<item name="strInformationString"/>
				<item name="strNote"/>
				<item name="strEventTypeName"/>
			</grid>
			<labels>
				<item name="strNote" labelId="EventLog.strNote"/>
			</labels>

			<lookups>
				<lookup name="EventType" table="BaseReference"  section="rftEventType" source="idfsEventTypeID" target="idfsBaseReference" />
			</lookups>

			<storage>
				<delete name="spReadOnlyObject_Delete"/>
				<candelete name="spReadOnlyObject_CanDelete"/>
			</storage>

      <actions child="EventLog">
        <standard>
          <remove type="Create"/>
          <remove type="Delete"/>
          <remove type="Edit"/>
          <remove type="Report"/>
        </standard>
        <action name="View" type="Edit">
          <visual alignment="Right" panel="Top">
            <regular caption="strView_Id" tooltip="strView_Id"  icon="View1"/>
          </visual>
          <run>
            <params>
              <param name="key" type="object" />
              <param name="item" type="IObject" />
              <param name="listPanel" type="object" />
            </params>
          </run>
        </action>
      </actions>
      <!--actions child="EventLog">
				<action name="Create" type="Create" visible="false" panel="Top" />
				<action name="Delete" type="Delete" visible="false" panel="Top" />
				<action name="Edit" type="Edit" visible="false" panel="Top" />
				<action name="View" type="Edit" caption="strView_Id" tooltip="strView_Id"  icon="View1"
						alignment="Right" panel="Top" close="false" visible="true" >
					<params>
						<param name="key" type="object" />
						<param name="item" type="IObject" />
						<param name="listPanel" type="object" />
					</params>
					<text>
					</text>
				</action>
				<action name="Report" type="Report" visible="false" />
			</actions-->
		</table>
	</tables>

</object>


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_54c.c
Label Definition File: CWE321_Hard_Coded_Cryptographic_Key__w32.label.xml
Template File: sources-sink-54c.tmpl.c
*/
/*
 * @description
 * CWE: 321 Use of Hard-coded Cryptographic Key
 * BadSource:  Copy a hardcoded value into cryptoKey
 * GoodSource: Read cryptoKey from the console
 * Sink:
 *    BadSink : Hash cryptoKey and use the value to encrypt a string
 * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
 *
 * */

#include "std_testcase.h"

#define CRYPTO_KEY L"Hardcoded"

#include <windows.h>
#include <wincrypt.h>

/* Link with the Advapi32.lib file for Crypt* functions */
#pragma comment (lib, "Advapi32")

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

/* bad function declaration */
void CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_54d_badSink(wchar_t * cryptoKey);

void CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_54c_badSink(wchar_t * cryptoKey)
{
    CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_54d_badSink(cryptoKey);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good function declaration */
void CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_54d_goodG2BSink(wchar_t * cryptoKey);

/* goodG2B uses the GoodSource with the BadSink */
void CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_54c_goodG2BSink(wchar_t * cryptoKey)
{
    CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_54d_goodG2BSink(cryptoKey);
}

#endif /* OMITGOOD */


text:
<?php
/**
 * Widget API: WP_Widget_Tag_Cloud class
 *
 * @package WordPress
 * @subpackage Widgets
 * @since 4.4.0
 */

/**
 * Core class used to implement a Tag cloud widget.
 *
 * @since 2.8.0
 *
 * @see WP_Widget
 */
class WP_Widget_Tag_Cloud extends WP_Widget {

	/**
	 * Sets up a new Tag Cloud widget instance.
	 *
	 * @since 2.8.0
	 */
	public function __construct() {
		$widget_ops = array(
			'description'                 => __( 'A cloud of your most used tags.' ),
			'customize_selective_refresh' => true,
		);
		parent::__construct( 'tag_cloud', __( 'Tag Cloud' ), $widget_ops );
	}

	/**
	 * Outputs the content for the current Tag Cloud widget instance.
	 *
	 * @since 2.8.0
	 *
	 * @param array $args     Display arguments including 'before_title', 'after_title',
	 *                        'before_widget', and 'after_widget'.
	 * @param array $instance Settings for the current Tag Cloud widget instance.
	 */
	public function widget( $args, $instance ) {
		$current_taxonomy = $this->_get_current_taxonomy( $instance );

		if ( ! empty( $instance['title'] ) ) {
			$title = $instance['title'];
		} else {
			if ( 'post_tag' === $current_taxonomy ) {
				$title = __( 'Tags' );
			} else {
				$tax   = get_taxonomy( $current_taxonomy );
				$title = $tax->labels->name;
			}
		}

		$show_count = ! empty( $instance['count'] );

		$tag_cloud = wp_tag_cloud(
			/**
			 * Filters the taxonomy used in the Tag Cloud widget.
			 *
			 * @since 2.8.0
			 * @since 3.0.0 Added taxonomy drop-down.
			 * @since 4.9.0 Added the `$instance` parameter.
			 *
			 * @see wp_tag_cloud()
			 *
			 * @param array $args     Args used for the tag cloud widget.
			 * @param array $instance Array of settings for the current widget.
			 */
			apply_filters(
				'widget_tag_cloud_args',
				array(
					'taxonomy'   => $current_taxonomy,
					'echo'       => false,
					'show_count' => $show_count,
				),
				$instance
			)
		);

		if ( empty( $tag_cloud ) ) {
			return;
		}

		/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );

		echo $args['before_widget'];
		if ( $title ) {
			echo $args['before_title'] . $title . $args['after_title'];
		}

		echo '
';

		echo $tag_cloud;

		echo "
\n";
		echo $args['after_widget'];
	}

	/**
	 * Handles updating settings for the current Tag Cloud widget instance.
	 *
	 * @since 2.8.0
	 *
	 * @param array $new_instance New settings for this instance as input by the user via
	 *                            WP_Widget::form().
	 * @param array $old_instance Old settings for this instance.
	 * @return array Settings to save or bool false to cancel saving.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance             = array();
		$instance['title']    = sanitize_text_field( $new_instance['title'] );
		$instance['count']    = ! empty( $new_instance['count'] ) ? 1 : 0;
		$instance['taxonomy'] = stripslashes( $new_instance['taxonomy'] );
		return $instance;
	}

	/**
	 * Outputs the Tag Cloud widget settings form.
	 *
	 * @since 2.8.0
	 *
	 * @param array $instance Current settings.
	 */
	public function form( $instance ) {
		$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
		$count = isset( $instance['count'] ) ? (bool) $instance['count'] : false;
		?>

			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?>
			<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />

		<?php
		$taxonomies       = get_taxonomies( array( 'show_tagcloud' => true ), 'object' );
		$current_taxonomy = $this->_get_current_taxonomy( $instance );

		switch ( count( $taxonomies ) ) {

			// No tag cloud supporting taxonomies found, display error message.
			case 0:
				?>
				<input type="hidden" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>" value="" />

					<?php _e( 'The tag cloud will not be displayed since there are no taxonomies that support the tag cloud widget.' ); ?>

				<?php
				break;

			// Just a single tag cloud supporting taxonomy found, no need to display a select.
			case 1:
				$keys     = array_keys( $taxonomies );
				$taxonomy = reset( $keys );
				?>
				<input type="hidden" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>" value="<?php echo esc_attr( $taxonomy ); ?>" />
				<?php
				break;

			// More than one tag cloud supporting taxonomy found, display a select.
			default:
				?>

					<label for="<?php echo $this->get_field_id( 'taxonomy' ); ?>"><?php _e( 'Taxonomy:' ); ?>
					<select class="widefat" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>">
					<?php foreach ( $taxonomies as $taxonomy => $tax ) : ?>
						<option value="<?php echo esc_attr( $taxonomy ); ?>" <?php selected( $taxonomy, $current_taxonomy ); ?>>
							<?php echo esc_html( $tax->labels->name ); ?>
						</option>
					<?php endforeach; ?>
					</select>

				<?php
		}

		if ( count( $taxonomies ) > 0 ) {
			?>

				<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" <?php checked( $count, true ); ?> />
				<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Show tag counts' ); ?>

			<?php
		}
	}

	/**
	 * Retrieves the taxonomy for the current Tag cloud widget instance.
	 *
	 * @since 4.4.0
	 *
	 * @param array $instance Current settings.
	 * @return string Name of the current taxonomy if set, otherwise 'post_tag'.
	 */
	public function _get_current_taxonomy( $instance ) {
		if ( ! empty( $instance['taxonomy'] ) && taxonomy_exists( $instance['taxonomy'] ) ) {
			return $instance['taxonomy'];
		}

		return 'post_tag';
	}
}


text:
package com.twitter.finatra.thrift.codegen

import com.twitter.finagle.stats.StatsReceiver
import com.twitter.finagle.{Filter, Service}
import com.twitter.finatra.thrift.ThriftRequest
import com.twitter.finatra.thrift.internal.{ThriftRequestUnwrapFilter, ThriftRequestWrapFilter}
import com.twitter.scrooge.ThriftMethod

case class MethodFilters(
  statsReceiver: StatsReceiver,
  commonFilter: Filter[ThriftRequest, Any, ThriftRequest, Any]) {

  def create[T](
    thriftMethod: ThriftMethod)(
    service: Service[T, thriftMethod.SuccessType]): Service[T, thriftMethod.SuccessType] = {

    new ThriftRequestWrapFilter[T, thriftMethod.SuccessType](thriftMethod.name) andThen
      commonFilter.asInstanceOf[Filter[ThriftRequest, thriftMethod.SuccessType, ThriftRequest, thriftMethod.SuccessType]] andThen
      new ThriftRequestUnwrapFilter[T, thriftMethod.SuccessType] andThen
      service
  }
}


text:
package xc2;

import java.awt.*;
import javax.swing.*;

public class test extends JFrame{

    String test[] = {"Name", "Time", "Verdict"};
    String test2[][] = {{"TripleM", "0:01", "AC"}, {"Elbadry", "0:02", "WA"}};
    private GridBagLayout layout;
    private GridBagConstraints constraints;

    public test(){
        layout = new GridBagLayout();
        constraints = new GridBagConstraints();
        setLayout(layout);
        JComboBox problems = new JComboBox(test);
        JPanel pr = new JPanel();
        pr.add(problems);
        constraints.fill = GridBagConstraints.NORTHWEST;
        pr.setBorder(BorderFactory.createTitledBorder("Select Problems"));
        addComponent( pr, 0, 0, 1, 1 );

        JTextArea code = new JTextArea(50, 20);
        addComponent( code, 1, 0, 1, 1 );

        JButton submit = new JButton("Submit");
        addComponent(submit, 2, 0, 2, 2);
    }

    private void addComponent( Component component,int row, int column, int width, int height ){
        constraints.gridx = column; // set gridx
        constraints.gridy = row; // set gridy
        constraints.gridwidth = width; // set gridwidth
        constraints.gridheight = height; // set gridheight
        layout.setConstraints( component, constraints ); // set constraints
        add( component );
    }

}


text:
<?php

declare(strict_types=1);

namespace Bazinga\GeocoderBundle\ProviderFactory;

use Geocoder\Provider\GeoIP2\GeoIP2;
use Geocoder\Provider\GeoIP2\GeoIP2Adapter;
use Geocoder\Provider\Provider;
use GeoIp2\Database\Reader;
use GeoIp2\ProviderInterface;
use GeoIp2\WebService\Client;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class GeoIP2Factory extends AbstractFactory
{
    protected static $dependencies = [
        ['requiredClass' => GeoIP2::class, 'packageName' => 'geocoder-php/geoip2-provider'],
    ];

    /**
     * @param array{provider: string, provider_service: ?ProviderInterface, model: string, user_id: string|int|null, license_key: string|null, locales: list<string>, webservice_options: array<mixed, mixed>, database_filename: ?string} $config
     */
    protected function getProvider(array $config): Provider
    {
        $provider = $config['provider'];
        if ('webservice' === $provider) {
            $userId = isset($config['user_id']) ? (int) $config['user_id'] : null;

            $provider = new Client($userId, $config['license_key'], $config['locales'], $config['webservice_options']);
        } elseif ('database' === $provider) {
            $provider = new Reader($config['database_filename'], $config['locales']);
        } else {
            $provider = $config['provider_service'];
        }

        $adapter = new GeoIP2Adapter($provider, $config['model']);

        return new GeoIP2($adapter);
    }

    protected static function configureOptionResolver(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'model' => GeoIP2Adapter::GEOIP2_MODEL_CITY,
            'database_filename' => null,
            'user_id' => null,
            'license_key' => null,
            'webservice_options' => [],
            'locales' => ['en'],
            'provider_service' => null,
        ]);

        $resolver->setRequired('provider');
        $resolver->setAllowedTypes('provider', ['string']);
        $resolver->setAllowedTypes('provider_service', [ProviderInterface::class, 'null']);
        $resolver->setAllowedTypes('model', ['string']);
        $resolver->setAllowedTypes('user_id', ['string', 'int', 'null']);
        $resolver->setAllowedTypes('license_key', ['string', 'null']);
        $resolver->setAllowedTypes('locales', ['array']);
        $resolver->setAllowedTypes('webservice_options', ['array']);
        $resolver->setAllowedTypes('database_filename', ['string', 'null']);

        $resolver->setAllowedValues('model', [GeoIP2Adapter::GEOIP2_MODEL_CITY, GeoIP2Adapter::GEOIP2_MODEL_COUNTRY]);
        $resolver->setAllowedValues('provider', ['webservice', 'database', 'service']);
    }
}


text:
package com.alibaba.json.bvt;

import org.junit.Assert;
import junit.framework.TestCase;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class LongFieldTest_primitive extends TestCase {

	public void test_codec() throws Exception {
		V0 v = new V0();
		v.setValue(1001L);

		String text = JSON.toJSONString(v);

		V0 v1 = JSON.parseObject(text, V0.class);

		Assert.assertEquals(v1.getValue(), v.getValue());
	}

	public void test_codec_null() throws Exception {
		V0 v = new V0();

		SerializeConfig mapping = new SerializeConfig();
		mapping.setAsmEnable(false);

		String text = JSON.toJSONString(v, mapping,
				SerializerFeature.WriteMapNullValue);
		Assert.assertEquals("{\"value\":123}", text);

		V0 v1 = JSON.parseObject(text, V0.class);

		Assert.assertEquals(v1.getValue(), v.getValue());
	}

	public void test_codec_null_asm() throws Exception {
		V0 v = new V0();

		SerializeConfig mapping = new SerializeConfig();
		mapping.setAsmEnable(true);

		String text = JSON.toJSONString(v, mapping,
				SerializerFeature.WriteMapNullValue);
		Assert.assertEquals("{\"value\":123}", text);

		ParserConfig config = new ParserConfig();
		config.setAsmEnable(false);

		V0 v1 = JSON.parseObject(text, V0.class, config,
				JSON.DEFAULT_PARSER_FEATURE);

		Assert.assertEquals(v1.getValue(), v.getValue());
	}

	public void test_codec_null_1() throws Exception {
		V0 v = new V0();

		SerializeConfig mapping = new SerializeConfig();
		mapping.setAsmEnable(false);

		String text = JSON.toJSONString(v, mapping,
				SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullNumberAsZero);
		Assert.assertEquals("{\"value\":123}", text);

		V0 v1 = JSON.parseObject(text, V0.class);

		Assert.assertEquals(123, v1.getValue());
	}

	public static class V0 {

		private long value = 123L;

		public long getValue() {
			return value;
		}

		public void setValue(long value) {
			this.value = value;
		}

	}
}


text:
"""set default values

Revision ID: 78af24b0bab1
Revises: 4b6faa5a296b
Create Date: 2017-11-15 15:46:44.253567

"""

# revision identifiers, used by Alembic.
revision = '78af24b0bab1'
down_revision = '4b6faa5a296b'

from alembic import op
from sqlalchemy import false
import sqlalchemy as sa

def upgrade():
    op.alter_column('metrics', 'author_num', server_default=sa.text("1::integer"))
    op.alter_column('metrics', 'citation_num', server_default=sa.text("0::integer"))
    op.alter_column('metrics', 'reference_num', server_default=sa.text("0::integer"))
    op.alter_column('metrics', 'refereed_citation_num', server_default=sa.text("0::integer"))
    op.alter_column('metrics', 'refereed', server_default=false())
    op.execute("ALTER TABLE metrics ALTER COLUMN citations SET DEFAULT array[]::varchar[];")
    op.execute("ALTER TABLE metrics ALTER COLUMN refereed_citations SET DEFAULT array[]::varchar[];")
    op.execute("ALTER TABLE metrics ALTER COLUMN downloads SET DEFAULT array[]::integer[];")
    op.execute("ALTER TABLE metrics ALTER COLUMN reads SET DEFAULT array[]::integer[];")

def downgrade():
    op.alter_column('metrics', 'author_num', server_default=None)
    op.alter_column('metrics', 'citation_num', server_default=None)
    op.alter_column('metrics', 'reference_num', server_default=None)
    op.alter_column('metrics', 'refereed_citation_num', server_default=None)
    op.alter_column('metrics', 'refereed', server_default=None)
    op.execute("ALTER TABLE metrics ALTER COLUMN citations DROP DEFAULT;")
    op.execute("ALTER TABLE metrics ALTER COLUMN refereed_citations DROP DEFAULT;")
    op.execute("ALTER TABLE metrics ALTER COLUMN downloads DROP DEFAULT;")
    op.execute("ALTER TABLE metrics ALTER COLUMN reads DROP DEFAULT;")


text:
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { A } from '@ember/array';

export default Route.extend({
  can: service(),

  model(params) {
    let self = this;
    return this.store
      .query('repository-prefix', {
        'repository-id': this.modelFor('repositories/show').get('id'),
        'prefix-id': params.prefix_id
      })
      .then(function (repositoryPrefixes) {
        return A(repositoryPrefixes).get('firstObject');
      })
      .catch(function (reason) {
        console.debug(reason);

        self.get('flashMessages').warning(reason);
        self.transitionTo('/');
      });
  },

  afterModel(model) {
    if (this.can.cannot('delete prefix', model)) {
      this.transitionTo('index');
    }
  },

  actions: {
    queryParamsDidChange() {
      this.refresh();
    },
    refreshCurrentRoute() {
      this.refresh();
    }
  }
});


text:
package com.javarush.test.level17.lesson10.home02;

/* Comparable
Реализуйте интерфейс Comparable<Beach> в классе Beach, который будет использоваться нитями.
*/

class Beach implements Comparable<Beach> {

  private String name;      //название
  private float distance;   //расстояние
  private int quality;    //качество

  public Beach(String name, float distance, int quality) {
    this.name = name;
    this.distance = distance;
    this.quality = quality;
  }

  @Override
  public synchronized int compareTo(Beach o) {
    int distanceParam = (int) (distance - o.getDistance());
    int qualityParam = quality - o.getQuality();
    return 10000 * name.compareTo(o.getName()) + 100 * distanceParam + qualityParam;

  }

  private synchronized String getName() {
    return name;
  }

  public synchronized void setName(String name) {
    this.name = name;
  }

  private synchronized float getDistance() {
    return distance;
  }

  public synchronized void setDistance(float distance) {
    this.distance = distance;
  }

  private synchronized int getQuality() {
    return quality;
  }

  public synchronized void setQuality(int quality) {
    this.quality = quality;
  }

}


text:
using BenchmarkDotNet.Portability;
using Xunit;

namespace BenchmarkDotNet.Tests.XUnit
{
    public class FactNotLinuxAttribute : FactAttribute
    {
        // ReSharper disable once VirtualMemberCallInConstructor
        public FactNotLinuxAttribute(string linuxSkipReason)
        {
            if (RuntimeInformation.IsLinux())
                Skip = linuxSkipReason;
        }
    }
}


text:
var app = require('../fixtures/bootstrap'),
    vows = require('vows'),
    assert = require('assert'),
    util = require('util'),
    Multi = require('multi'),
    EventEmitter = require('events').EventEmitter,
    fs = require('fs');

var sessionState;

var multi = new Multi(app);

multi.on('pre_exec', app.backupFilters);
multi.on('post_exec', app.restoreFilters);

vows.describe('Static File Server (middleware)').addBatch({

  '': {

    topic: function() {

      // Load static server middleware
      sessionState = app.supports.session;
      app.supports.session = false;
      app.use('static_server', {
        watchOn: [protos.environment]
      });

      var promise = new EventEmitter();

      multi.curl('-i /hello.txt');                    // file in root level
      multi.curl('-i /dir/file.txt');                 // file in subdir, level 1
      multi.curl('-i /dir/subdir/sub.txt');           // file in subdir, level 2
      multi.curl('-i /blog/post.txt');                // file in subdir, matches controller name
      multi.curl('-i /missing.txt');                  // missing file, root level
      multi.curl('-i /this/is/missing.txt');          // missing file, level 1
      multi.curl('-i /this/is/missing/file.txt');     // missing file, level 2
      multi.curl('-i /.missing-file');                // hidden file, root level (nonexistent)
      multi.curl('-i /dir/.missing-file');            // hidden file, level 1 (nonexistent)
      multi.curl('-i /.hidden-file');                 // hidden file, root level
      multi.curl('-i /dir/.hidden-file');             // hidden file, level 1

      // Partial content
      multi.request({                                 // partial file request, valid
        url: app.url('/ranges.txt'),
        headers: { Range: 'bytes=5-10' }
      })

      multi.request({                                 // partial file request, invalid
        url: app.url('/ranges.txt'),
        headers: { Range: 'bytes=10-5' }
      });

      // File download (without attachment name)
      multi.curl('-i /download');

      // File download with attachment name
      multi.curl('-i -G -d "file=hello.txt" /download');

      // Serve static file
      multi.curl('-i -G -d "file=robots1.txt" /serve-static');  // 404
      multi.curl('-i -G -d "file=robots.txt" /serve-static');   // found
      multi.curl('-i -G -d "file=../boot.js" /serve-static');   // 404
      multi.curl('-i -G -d "file=../boot.js" -d "unsafe=true" /serve-static'); // found
      multi.curl('-i -G -d "file=../public/robots.txt" /serve-static'); // 404
      multi.curl('-i -G -d "file=../public/robots.txt" -d "unsafe=true" /serve-static'); // found

      multi.exec(function(err, results) {
        app.supports.session = sessionState;
        if (err) throw err;
        results = results.map(function(r) {
          try { return r.trim().split(/\r\n/); }
          catch(e) { return r; }
        });
        promise.emit('success', err || results);
      });

      return promise;
    },

    'Properly sets cache control headers': function(results) {
      var r = results[0];
      var cc = app.config.cacheControl;
      assert.isTrue(r.indexOf(util.format('Cache-Control: %s, max-age=%d', cc.static, cc.maxAge)) >= 0);
    },

    'Gets files in public/ » root level': function(results) {
      var r = results[0];
      assert.isTrue(r.indexOf('Status: 200 OK') >= 0);
      assert.isTrue(r.indexOf('Content-Length: 11') >= 0);
      assert.isTrue(r.indexOf('Content-Type: text/plain') >= 0);
      assert.equal(r.pop(), '{hello.txt}');
    },

    'Gets files in public/ » 1 level deep': function(results) {
      var r = results[1];
      assert.isTrue(r.indexOf('Status: 200 OK') >= 0);
      assert.isTrue(r.indexOf('Content-Length: 14') >= 0);
      assert.isTrue(r.indexOf('Content-Type: text/plain') >= 0);
      assert.equal(r.pop(), '{dir/file.txt}');
    },

    'Gets files in public/ » 2 levels deep (and up)': function(results) {
      var r = results[2];
      assert.isTrue(r.indexOf('Status: 200 OK') >= 0);
      assert.isTrue(r.indexOf('Content-Length: 20') >= 0);
      assert.isTrue(r.indexOf('Content-Type: text/plain') >= 0);
      assert.equal(r.pop(), '{dir/subdir/sub.txt}');
    },

    'Does not conflict with controllers': function(results) {
      var r = results[3];
      assert.isTrue(r.indexOf('Status: 200 OK') >= 0);
      assert.isTrue(r.indexOf('Content-Length: 15') >= 0);
      assert.isTrue(r.indexOf('Content-Type: text/plain') >= 0);
      assert.equal(r.pop(), '{blog/post.txt}');
    },

    'Responds with 404 for files not found': function(results) {
      var r1 = results[4],
          r2 = results[5],
          r3 = results[6];
      assert.equal(r1[0], 'HTTP/1.1 404 Not Found');
      assert.equal(r2[0], 'HTTP/1.1 404 Not Found');
      assert.equal(r3[0], 'HTTP/1.1 404 Not Found');
    },

    'Denies access to hidden files': function(results) {
      var r1 = results[7],
          r2 = results[8],
          r3 = results[9],
          r4 = results[10];
      assert.equal(r1[0], 'HTTP/1.1 404 Not Found');
      assert.equal(r2[0], 'HTTP/1.1 404 Not Found');
      assert.equal(r3[0], 'HTTP/1.1 404 Not Found');
      assert.equal(r4[0], 'HTTP/1.1 404 Not Found');
    },

    'Responds with 206 for Partial Content requests': function(results) {
      var r1 = results[11], // HTTP/1.1 206 Partial Content
          r2 = results[12]; // HTTP/1.1 416 Requested Range Not Satisfiable
      assert.equal(r1[1], 'fghijk');
      assert.equal(r1[0].headers.status, '206 Partial Content');
      assert.equal(r2[1], '');
      assert.equal(r2[0].headers.status, '416 Requested Range Not Satisfiable');
    },

    'Successfully sends files (forcing download)': function(results) {
      var r1 = results[13],
          r2 = results[14];
      assert.isTrue(r1.indexOf('HTTP/1.1 200 OK') >= 0);
      assert.isTrue(r1.indexOf('Content-Disposition: attachment') >= 0);
      assert.isTrue(r2.indexOf('HTTP/1.1 200 OK') >= 0);
      assert.isTrue(r2.indexOf('Content-Disposition: attachment; filename="hello.txt"') >= 0);
    },

    'Successfully runs res.serveStaticFile': function(results) {

      var r1 = results[15];
          r2 = results[16];
          r3 = results[17];
          r4 = results[18];
          r5 = results[19];
          r6 = results[20];

      var robots = fs.readFileSync(app.fullPath('public/robots.txt'), 'utf8').trim();
      var bootjs = fs.readFileSync(app.fullPath('boot.js'), 'utf8');

      assert.isTrue(r1.indexOf('HTTP/1.1 404 Not Found') >= 0);

      assert.isTrue(r2.indexOf('HTTP/1.1 200 OK') >= 0);
      assert.isTrue(r2.concat([]).pop() === robots);

      assert.isTrue(r3.indexOf('HTTP/1.1 404 Not Found') >= 0);

      assert.isTrue(r4.indexOf('HTTP/1.1 200 OK') >= 0);
      assert.isTrue(r4.concat([]).pop() === bootjs);

      assert.isTrue(r5.indexOf('HTTP/1.1 404 Not Found') >= 0);

      assert.isTrue(r6.indexOf('HTTP/1.1 200 OK') >= 0);
      assert.isTrue(r6.concat([]).pop() === robots);

    }

  }

}).export(module);


text:
import os
import sys
import logging
import subprocess

if __name__ == "__main__":
    if 'posix' in os.name and os.geteuid() == 0:
        from django.core.management.base import CommandError
        raise CommandError("manage.py should not be run as root.")
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zproject.settings")

    from django.conf import settings

    logger = logging.getLogger("zulip.management")
    subprocess.check_call([os.path.join(os.path.dirname(__file__), "bin", "log-management-command"),
                           " ".join(sys.argv)])

    if "--no-traceback" not in sys.argv and len(sys.argv) > 1:
        sys.argv.append("--traceback")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)


text:
package io.sigpipe.sing.dataset.analysis;

import java.util.ArrayList;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;

import io.sigpipe.sing.dataset.feature.Feature;

/**
 * Handles quantization of {@link Feature} values. In other words, a Quantizer
 * instance takes in high-resolution data and outputs low-resolution values that
 * represent subdivisions ("buckets" or "tick marks") in the feature space. Each
 * bucket handles Features for a particular range of values.
 *

 * For example, imagine a Quantizer instance set up for values ranging from 0 to
 * 100, with a step size of 2 (note that each of these values are integers).
 * Inputting values of 24.6f or 25.9999f would return bucket 24, while 99.9d
 * would return 98, and 1 would return 0.
 *

 * Note that the outputs returned by the Quantizer.quantize() method are not
 * meant to be 'closest' to their original values; rather, the output values are
 * simply identifiers for the particular bucket in question.
 *
 * @author malensek
 */
public class Quantizer {

    private NavigableSet<Feature> ticks = new TreeSet<>();

    /**
     * Constructs a Quantizer with a predefined list of Tick marks. For
     * incremental construction of a Quantizer instance, see
     * {@link QuantizerBuilder}.
     *
     * @param ticks collection of tick marks to be used during quantization
     */
    public Quantizer(Feature... ticks) {
        for (Feature tick : ticks) {
            addTick(tick);
        }
    }

    /**
     * Constructs a Quantizer with a predefined collection of Tick marks. For
     * incremental construction of a Quantizer instance, see
     * {@link QuantizerBuilder}.
     *
     * @param ticks collection of tick marks to be used during quantization
     */
    public Quantizer(Iterable<Feature> ticks) {
        for (Feature tick : ticks) {
            addTick(tick);
        }
    }

    /**
     * Constructs a Quantizer with start and end points, as well as an
     * intermediate step size that is used to populate tick marks uniformly
     * between. Primitive types may be used to parameterize this constructor,
     * but note that each parameter must be of the same type to avoid ambiguity
     * during quantization.
     *
     * @param start The beginning of the feature range
     * @param end The end of the feature range
     * @param step Step size to use for populating intermediate tick marks
     */
    public Quantizer(Object start, Object end, Object step) {
        this(
                Feature.fromPrimitiveType(start),
                Feature.fromPrimitiveType(end),
                Feature.fromPrimitiveType(step));
    }

    /**
     * Constructs a Quantizer with start and end points, as well as an
     * intermediate step size that is used to populate tick marks uniformly
     * between. Note that each of these features must be of the same
     * {@link FeatureType} to avoid ambiguity during quantization.
     *
     * @param start The beginning of the feature range
     * @param end The end of the feature range
     * @param step Step size to use for populating intermediate tick marks
     */
    public Quantizer(Feature start, Feature end, Feature step) {
        if (start.sameType(end) == false || start.sameType(step) == false) {
            throw new IllegalArgumentException(
                    "All feature types must be the same");
        }

        Feature tick = new Feature(start);
        while (tick.less(end)) {
            addTick(tick);
            tick = tick.add(step);
        }
    }

    /**
     * Adds a new tick mark value to this Quantizer.
     *
     * @param tick the new tick mark to add
     */
    private void addTick(Feature tick) {
        ticks.add(tick);
    }

    /**
     * Retrieves the number of tick mark subdivisions in this Quantizer.
     *
     * @return number of tick marks
     */
    public int numTicks() {
        return ticks.size();
    }

    /**
     * Quantizes a given Feature based on this Quantizer's tick mark
     * configuration. When quantizing a Feature, a bucket will be retrieved that
     * represents the Feature in question in the tick mark range. Note that the
     * bucket returned is not necessarily closest in value to the Feature, but
     * simply represents its range of values.
     *
     * @param feature The Feature to quantize
     * @return A quantized representation of the Feature
     */
    public Feature quantize(Feature feature) {
        Feature result = ticks.floor(feature);
        if (result == null) {
            return ticks.first();
        }

        return result;
    }

    /**
     * Retrieves the next tick mark value after the given Feature. In other
     * words, this method will return the bucket after the given Feature's
     * bucket. If there is no next tick mark (the specified Feature's bucket is
     * at the end of the range) then this method returns null.
     *
     * @param feature Feature to use to locate the next tick mark bucket in the
     *     range.
     * @return Next tick mark, or null if the end of the range has been reached.
     */
    public Feature nextTick(Feature feature) {
        return ticks.higher(feature);
    }

    /**
     * Retrieves the tick mark value preceding the given Feature. In other
     * words, this method will return the bucket before the given Feature's
     * bucket. If there is no previous tick mark (the specified Feature's bucket
     * is at the beginning of the range) then this method returns null.
     *
     * @param feature Feature to use to locate the previous tick mark bucket in
     *     the range.
     * @return Next tick mark, or null if the end of the range has been reached.
     */
    public Feature prevTick(Feature feature) {
        return ticks.lower(feature);
    }

    @Override
    public String toString() {
        String output = "";
        for (Feature f : ticks) {
            output += f.getString() + System.lineSeparator();
        }
        return output;
    }

    /**
     * Builder that allows incremental creation of a {@link Quantizer}.
     */
    public static class QuantizerBuilder {
        List<Feature> ticks = new ArrayList<>();

        public QuantizerBuilder addTick(Feature tick) {
            this.ticks.add(tick);
            return this;
        }

        public QuantizerBuilder addTicks(Feature... ticks) {
            for (Feature tick : ticks) {
                addTick(tick);
            }
            return this;
        }

        public QuantizerBuilder removeTick(Feature tick) {
            this.ticks.remove(tick);
            return this;
        }

        public List<Feature> getTicks() {
            return new ArrayList<Feature>(ticks);
        }

        public Quantizer build() {
            Quantizer q = new Quantizer();
            for (Feature tick : ticks) {
                q.addTick(tick);
            }

            return q;
        }
    }
}


text:
package elastigo

import (
	"fmt"
)

// 404 Response.
var RecordNotFound = errorf("record not found")

type elastigoError struct {
	s string
}

func errorf(s string, args ...interface{}) elastigoError {
	return elastigoError{s: fmt.Sprintf(s, args...)}
}

func (err elastigoError) Error() string {
	return err.s
}


text:
package fr.openwide.core.basicapp.core.config.spring;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import fr.openwide.core.basicapp.core.BasicApplicationCorePackage;
import fr.openwide.core.spring.config.spring.AbstractApplicationConfig;
import fr.openwide.core.spring.config.spring.annotation.ApplicationDescription;
import fr.openwide.core.spring.config.spring.annotation.ConfigurationLocations;

@Configuration
@ApplicationDescription(name = BasicApplicationCoreCommonConfig.APPLICATION_NAME)
@ConfigurationLocations
@Import({
	BasicApplicationCoreCommonJpaConfig.class,			// configuration de la persistence
	BasicApplicationCoreSecurityConfig.class,			// configuration de la sécurité
	BasicApplicationCoreTaskManagementConfig.class,			// configuration de la gestion des tâches
	BasicApplicationCoreNotificationConfig.class,		// configuration des notifications
	BasicApplicationCoreSchedulingConfig.class,			// configuration des tâches planifiées
	BasicApplicationCoreApplicationPropertyConfig.class	// configuration des propriétés de l'application
})
@ComponentScan(
	basePackageClasses = {
		BasicApplicationCorePackage.class
	},
	// https://jira.springsource.org/browse/SPR-8808
	// on veut charger de manière explicite le contexte ; de ce fait,
	// on ignore l'annotation @Configuration sur le scan de package.
	excludeFilters = @Filter(Configuration.class)
)
// fonctionnement de l'annotation @Transactional
@EnableTransactionManagement(order = BasicApplicationAdviceOrder.TRANSACTION)
public class BasicApplicationCoreCommonConfig extends AbstractApplicationConfig {

	public static final String APPLICATION_NAME = "basic-application";

	public static final String PROFILE_TEST = "test";

}


text:
module Guard
  module ShellexecVersion
    VERSION = "1.0.0"
  end
end


text:
import * as Config from "models/config";

export interface ConfigState {
	muted: boolean;
}

export const INITIAL_CONFIG_STATE: ConfigState = {
	muted: Config.muted(),
};


text:
// $Id$

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BumpVersion.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace BumpVersion.Tests.Tasks
{
	[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
	[TestClass]
	public class ReplaceInFileTests
	{
		[TestMethod]
		public void BumpCustomPatternTest()
		{
			Dictionary<string, string> settings = new Dictionary<string, string>();
			Dictionary<string, string> variables = new Dictionary<string, string>();
			OperationResult result;
			settings.Add( "files", "replace.custom.txt" );
			settings.Add( "search", "Version {0}" );
			settings.Add( "replace", "Version {0}" );

			File.WriteAllText( "replace.custom.txt", "Version 0.1 will be replaced, 0.1 not" );

			ReplaceInFile task = new ReplaceInFile( settings, variables );
			result = task.Bump( new Version( 0, 1 ), new Version( 0, 2 ) );

			string content = File.ReadAllText( "replace.custom.txt" );
			Assert.AreEqual( "Version 0.2 will be replaced, 0.1 not", content );
		}

		[TestMethod]
		public void BumpDefaultTest()
		{
			Dictionary<string, string> settings = new Dictionary<string, string>();
			Dictionary<string, string> variables = new Dictionary<string, string>();
			OperationResult result;
			settings.Add( "files", "replace.default.txt;replace.default2.txt" );

			File.WriteAllText( "replace.default.txt", "This is a test version of 0.1 :)" );
			File.WriteAllText( "replace.default2.txt", "Version 0.1 is replaced. However, Version 1.2 , 0.3 or even 0.1.1 not" );

			ReplaceInFile task = new ReplaceInFile( settings, variables );

			result = task.Bump( new Version( 0, 1 ), new Version( 0, 2 ) );

			Assert.IsTrue( result.IsSuccess );

			string content = File.ReadAllText( "replace.default.txt" );
			Assert.AreEqual( "This is a test version of 0.2 :)", content );

			content = File.ReadAllText( "replace.default2.txt" );
			Assert.AreEqual( "Version 0.2 is replaced. However, Version 1.2 , 0.3 or even 0.1.1 not", content );
		}

		[TestMethod]
		public void BumpExceptionTest()
		{
			Dictionary<string, string> settings = new Dictionary<string, string>();
			Dictionary<string, string> variables = new Dictionary<string, string>();

			settings.Add( "files", "non.existing" );

			ReplaceInFile task = new ReplaceInFile( settings, variables );

			OperationResult result = task.Bump( new Version( 0, 1 ), new Version( 0, 2 ) );

			Assert.IsFalse( result.IsSuccess );
			Assert.IsTrue( result.Errors[0].StartsWith( "non.existing => System.IO.FileNotFoundException" ) );
		}

		[TestMethod]
		public void ValidateTest()
		{
			Dictionary<string, string> settings = new Dictionary<string, string>();
			Dictionary<string, string> variables = new Dictionary<string, string>();
			ReplaceInFile task = new ReplaceInFile( settings, variables );
			OperationResult result = task.Validate();

			Assert.IsFalse( result.IsSuccess );
			Assert.IsTrue( result.Errors.Contains( "No files given" ) );

			settings.Add( "files", "non.existing" );

			task = new ReplaceInFile( settings, variables );
			result = task.Validate();

			Assert.IsFalse( result.IsSuccess );
			Assert.IsTrue( result.Errors.Contains( "File 'non.existing' does not exist" ) );

			File.WriteAllText( "test.txt", "" );
			settings["files"] = "test.txt";

			task = new ReplaceInFile( settings, variables );
			result = task.Validate();
			Assert.IsTrue( result.IsSuccess );
		}
	}
}


text:
package com.beiing.leafchart.support;

import com.beiing.leafchart.bean.Axis;

/**
 * Created by chenliu on 2016/7/15.<br/>
 * 描述:
 * </br>
 */
public interface Chart {

    void setAxisX(Axis axisX);

    void setAxisY(Axis axisY);

    Axis getAxisX();

    Axis getAxisY();
}


text:
namespace _06.CustomEnumAttribute
{
    [Type("Enumeration", "Suit", "Provides suit constants for a Card class.")]
    public enum Suit
    {
        Clubs = 0,
        Diamonds = 13,
        Hearts = 26,
        Spades = 39
    }
}