text:
package com.ottogroup.bi.streaming.operator.json.filter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.Function;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.sling.commons.json.JSONObject;
import org.flinkspector.core.quantify.OutputMatcher;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;

import com.ottogroup.bi.streaming.operator.json.JsonContentReference;
import com.ottogroup.bi.streaming.operator.json.JsonContentType;
import com.ottogroup.bi.streaming.operator.json.filter.cfg.FieldConditionCombinerConfiguration;
import com.ottogroup.bi.streaming.operator.json.filter.cfg.FieldConditionConfiguration;
import com.ottogroup.bi.streaming.operator.json.filter.cfg.FieldConditionOperator;
import com.ottogroup.bi.streaming.operator.json.filter.cfg.JsonContentFilterConfiguration;
import com.ottogroup.bi.streaming.testing.MatchJSONContent;

/**
 * Filters an incoming {@link JSONObject} for specific content. All non-matching messages are rejected, all messages
 * that evaluate to true are passed on to the next {@link Function} for further processing.
 *

 * Internally the filter is based on Hamcrest matchers {@link http://hamcrest.org} which allow to create pretty complex
 * matcher hierarchies. The implementation tries to cover this complexity and provide features for creating filters like
 *

 *
messages must match AT LEAST two conditions of (A, B, C, D)

 *
messages must match AT MOST two conditions of (A, B, C, D)

 *
messages must match EXACTLY two conditions of (A, B, C, D)

 *
messages must match ALL conditions of (A, B, C, D)

 *
messages must match ANY conditions of (A, B, C, D) (similar to must match at least one)

 *
any AND combined conditions of the examples shown above ((AT LEAST one of (A, B, C)) AND (AT MOST two of (C, D, E)))

 *

 * Conditions are bound to selected fields referenced by a {@link JsonContentReference} located inside the {@link FieldConditionConfiguration}.

 * The filter configuration is split into two parts: field conditions and condition combiners. The first section lists conditions to be applied
 * per field:
 *

 * { ...
 *   "fieldConditions" : {
 *    "f1" : {
 *      "contentRef" : {
 *        "path" : [ "path", "to", "element" ],
 *        "contentType" : "STRING",
 *        "conversionPattern" : null,
 *        "required" : true
 *      },
 *      "operator" : "IS",
 *      "value" : "test"
 *    }
 *   }..
 * }
 *

 * The example defines a condition to be applied on field {@code path.to.element} where it expects to find the value test. For example,
 * the following JSON would evaluate to true
 *

 * {
 *   "path": {
 *     "to": {
 *       "element": "test"
 *     }
 *   }
 * }
 *

 * If a simple list of field conditions is provided, the filter assumes that all of them must hold for an incoming message in order to
 * return true.

 * For further refinement the filter allows to combine a sub-set of conditions and assign specific requirements to that list, eg. all
 * conditions must hold or at least three of them (see above for more examples). The following JSON shows an example configuration:
 *

 * {
 *   "fieldConditions" : {
 *     "f1" : {
 *       "contentRef" : {
 *         "path" : [ "path", "to", "element" ],
 *         "contentType" : "STRING",
 *         "conversionPattern" : null,
 *         "required" : true
 *       },
 *       "operator" : "IS",
 *       "value" : "test"
 *     },
 *     "f2" : {
 *       "contentRef" : {
 *         "path" : [ "another", "path", "into", "structure" ],
 *         "contentType" : "INTEGER",
 *         "conversionPattern" : null,
 *         "required" : true
 *       },
 *       "operator" : "LESS_THAN",
 *       "value" : "10"
 *     }
 *   },
 *   "fieldConditionCombiners" : [
 *     {
 *       "fieldConditionRefs" : [ "f1", "f2" ],
 *       "combiner" : "AT_LEAST",
 *       "n" : 1
 *     }, {
 *       "fieldConditionRefs" : [ "f1" ],
 *       "combiner" : "ANY",
 *       "n" : 1
 *     }
 *   ]
 * }
 *

 * If any field condition combiner is provided, the filter does not require all field conditions to hold for each message any more (see above). Instead
 * some field conditions are combined (fieldConditionRefs) by referencing them inside a combiner element. For each combined set of conditions a type
 * must be specified: AT_LEAST, AT_MOST or ALL. The type defines the circumstances under which the combined conditions return true for
 * an incoming message. The n parameter provides further information when selecting a combiner like AT_LEAST which requires the number of
 * conditions that must hold at minimum. Supported types are:
 *

 *
ALL
all conditions must hold in order to return true on an incoming message

 *
ANY
any/at least one condition must hold in order to return true on an incoming message

 *
AT_LEAST
at least n conditions must hold in order to return true on an incoming message

 *
AT_MOST
at most n conditions must hold in order to return true on an incoming message

 *
EXACTLY
exactly n conditions must hold in order to return true on an incoming message

 *

 * Each incoming message is provided to all combined field conditions. The filter implementation requires all combined field conditions to hold in order
 * to return true for a message:
 *

 *   (AT LEAST one of (A, B, C)) AND (AT MOST two of (C, D, E)) must hold
 *

 * @author mnxfst
 * @since Jan 12, 2016
 */
public class JsonContentFilter extends RichFilterFunction<JSONObject> {

	private static final long serialVersionUID = 4503194679586417037L;

	private JsonContentFilterConfiguration cfg = null;

	// matcher instance later used for evaluating incoming messages
	private transient Matcher<?> jsonContentMatcher = null;

	/**
	 * Initializes the filter without any configuration. As the semantics of the filter is defined as
	 * "if the matcher evaluates a message to true for a provided set of validation rules the message is passed on"
	 * a filter without configuration blocks away all incoming messages
	 */
	public JsonContentFilter() {
	}

	public JsonContentFilter(final JsonContentFilterConfiguration cfg) throws NoSuchMethodException, IllegalArgumentException, ParseException {
		this.cfg = cfg;
	}

	public void open(Configuration parameters) throws Exception {
		this.jsonContentMatcher = buildMatcher(cfg);
	}

	/**
	 * @see org.apache.flink.api.common.functions.RichFilterFunction#filter(java.lang.Object)
	 */
	public boolean filter(JSONObject jsonObject) throws Exception {
		// if no matcher was provided the filter simply returns false as the messages does not comply with anything
		return this.jsonContentMatcher != null ? this.jsonContentMatcher.matches(Arrays.asList(jsonObject)) : false;
	}

	/**
	 * Builds a {@link Matcher} instance that is used by {@link #filter(JSONObject)} to decide upon whether a message complies
	 * with the configured filter configuration
	 * @param cfg
	 * 		The {@link JsonContentFilterConfiguration} holding all configuration options required for setting up the {@link Matcher} instance
	 * @return
	 * 		The {@link Matcher} instance
	 * @throws NoSuchMethodException
	 * 		Thrown in case a requested {@link FieldConditionOperator} is currently not supported
	 * @throws IllegalArgumentException
	 * 		Thrown in case a required input is missing
	 * @throws ParseException
	 * 		Thrown in case parsing out content failed for any reason - specifically thrown in conjunction with invalid timestamp formats
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected Matcher<?> buildMatcher(final JsonContentFilterConfiguration cfg) throws NoSuchMethodException, IllegalArgumentException, ParseException {

		///////////////////////////////////////////////////////////////////////
		// validate provided input - more in-depth validation is done by
		// subsequent methods to reduce code and check where it is necessary
		if(cfg == null)
			throw new IllegalArgumentException("Missing required configuration");
		if(cfg.getFieldContentMatchers() == null || cfg.getFieldContentMatchers().isEmpty())
			throw new IllegalArgumentException("Missing required field content matchers");
		///////////////////////////////////////////////////////////////////////

		MatchJSONContent matchJsonContent = new MatchJSONContent();

		// no combiners found: append all matchers to a single json matcher and require that all must validate to true
		// in case to accept a json document
		if(cfg.getFieldContentMatcherCombiners() == null || cfg.getFieldContentMatcherCombiners().isEmpty()) {
			for(final FieldConditionConfiguration contentMatcherCfg : cfg.getFieldContentMatchers().values()) {
				matchJsonContent = addMatcher(matchJsonContent, contentMatcherCfg);
			}
			return matchJsonContent.onEachRecord();
		}

		// otherwise create a combiner for each combiner configuration and attach the generated output matcher
		// to a list for further use
		List<OutputMatcher<JSONObject>> matchers = new ArrayList<>();
		for(final FieldConditionCombinerConfiguration combinerCfg : cfg.getFieldContentMatcherCombiners()) {
			matchers.add(buildCombiner(combinerCfg, cfg.getFieldContentMatchers()));
		}

		// combine all output matchers such that all of them must evaluate to true
		// TODO provide more detailed configurations like grouping
		return Matchers.allOf((Iterable)matchers);
	}

	/**
	 * Builds a {@link MatchJSONContent} which combines different {@link Matcher} and requires a subset of them to meet them
	 * @param combinerConfiguration
	 * @param fieldContentMatcherConfiguration
	 * @return
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws ParseException
	 */
	protected OutputMatcher<JSONObject> buildCombiner(final FieldConditionCombinerConfiguration combinerConfiguration, final Map<String, FieldConditionConfiguration> fieldContentMatcherConfiguration) throws NoSuchMethodException, IllegalArgumentException, ParseException {

		///////////////////////////////////////////////////////////////////////
		// validate provided input
		if(combinerConfiguration == null)
			throw new IllegalArgumentException("Missing required matcher combiner configuration");
		if(combinerConfiguration.getCombiner() == null)
			throw new IllegalArgumentException("Missing required matcher combiner type");
		if(combinerConfiguration.getFieldConditionRefs() == null || combinerConfiguration.getFieldConditionRefs().isEmpty())
			throw new IllegalArgumentException("Missing required references into matcher configurations");
		if(fieldContentMatcherConfiguration == null || fieldContentMatcherConfiguration.isEmpty())
			throw new IllegalArgumentException("Missing required field content matchers");
		///////////////////////////////////////////////////////////////////////

		MatchJSONContent matchJSONContent = new MatchJSONContent();
		for(final String matcherId : combinerConfiguration.getFieldConditionRefs()) {
			final FieldConditionConfiguration matcherCfg = fieldContentMatcherConfiguration.get(matcherId);
			if(matcherCfg == null)
				throw new IllegalArgumentException("Missing required field content matcher configuration for ref '"+matcherId+"'");
			matchJSONContent = addMatcher(matchJSONContent, matcherCfg);
		}

		switch(combinerConfiguration.getCombiner()) {
			case ANY: {
				return matchJSONContent.anyOfThem().onEachRecord();
			}
			case AT_LEAST: {
				if(combinerConfiguration.getN() < 0 || combinerConfiguration.getN() > fieldContentMatcherConfiguration.size())
					throw new IllegalArgumentException("Negative values or values that exceed the number of available matcher configurations are not permitted for combiner parameter 'n'");
				return matchJSONContent.atLeastNOfThem(combinerConfiguration.getN()).onEachRecord();
			}
			case AT_MOST: {
				if(combinerConfiguration.getN() < 0 || combinerConfiguration.getN() > fieldContentMatcherConfiguration.size())
					throw new IllegalArgumentException("Negative values or values that exceed the number of available matcher configurations are not permitted for combiner parameter 'n'");
				return matchJSONContent.atMostNOfThem(combinerConfiguration.getN()).onEachRecord();
			}
			case EXACTLY: {
				if(combinerConfiguration.getN() < 0 || combinerConfiguration.getN() > fieldContentMatcherConfiguration.size())
					throw new IllegalArgumentException("Negative values or values that exceed the number of available matcher configurations are not permitted for combiner parameter 'n'");
				return matchJSONContent.exactlyNOfThem(combinerConfiguration.getN()).onEachRecord();
			}
			case ALL: {
				return matchJSONContent.onEachRecord();
			}
			default: {
				return matchJSONContent.onEachRecord();
			}

		}
	}

	/**
	 * Adds a {@link Matcher} to an existing/newly created {@link MatchJSONContent} instance according to the give {@link FieldConditionConfiguration}
	 * @param matchJsonContent
	 * 			The {@link MatchJSONContent} instance to add a new {@link Matcher} to. If null is provided a new {@link MatchJSONContent} is created
	 * @param cfg
	 * 			The configuration to use for matcher instantiation
	 * @return
	 * 			The {@link MatchJSONContent} instance holding the newly created {@link Matcher}
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws ParseException
	 */
	protected MatchJSONContent addMatcher(MatchJSONContent matchJsonContent, final FieldConditionConfiguration cfg) throws NoSuchMethodException, IllegalArgumentException, ParseException {

		///////////////////////////////////////////////////////////////////////
		// validate provided input
		if(cfg == null)
			throw new IllegalArgumentException("Missing required configuration");
		if(cfg.getOperator() == null)
			throw new IllegalArgumentException("Missing required matcher type");
		if(cfg.getContentRef() == null)
			throw new IllegalArgumentException("Missing required content reference");
		if(cfg.getContentRef().getContentType() == null)
			throw new IllegalArgumentException("Missing required content type");
		if(cfg.getContentRef().getPath() == null || cfg.getContentRef().getPath().length < 1)
			throw new IllegalArgumentException("Missing required content path");
		if(cfg.getContentRef().getContentType() == JsonContentType.TIMESTAMP && StringUtils.isBlank(cfg.getContentRef().getConversionPattern()))
			throw new IllegalArgumentException("Missing required conversion pattern for content type '"+JsonContentType.TIMESTAMP+"'");
		///////////////////////////////////////////////////////////////////////

		if(matchJsonContent == null)
			matchJsonContent = new MatchJSONContent();

		switch(cfg.getContentRef().getContentType()) {
			case BOOLEAN: {
				return matchJsonContent.assertBoolean(String.join(".", cfg.getContentRef().getPath()),
						matcher(cfg.getOperator(),
								(StringUtils.isNotBlank(cfg.getValue()) ? Boolean.parseBoolean(cfg.getValue()) : null), cfg.getContentRef().getContentType()));
			}
			case DOUBLE: {
				return matchJsonContent.assertDouble(String.join(".", cfg.getContentRef().getPath()),
						matcher(cfg.getOperator(),
								(StringUtils.isNotBlank(cfg.getValue()) ? Double.parseDouble(cfg.getValue()) : null), cfg.getContentRef().getContentType()));
			}
			case INTEGER: {
				return matchJsonContent.assertInteger(String.join(".", cfg.getContentRef().getPath()),
						matcher(cfg.getOperator(),
								(StringUtils.isNotBlank(cfg.getValue()) ? Integer.parseInt(cfg.getValue()) : null), cfg.getContentRef().getContentType()));
			}
			case STRING: {
				return matchJsonContent.assertString(String.join(".", cfg.getContentRef().getPath()), matcher(cfg.getOperator(), cfg.getValue(), cfg.getContentRef().getContentType()));
			}
			case TIMESTAMP: {
				if(StringUtils.isNotBlank(cfg.getValue())) {
					final SimpleDateFormat sdf = new SimpleDateFormat(cfg.getContentRef().getConversionPattern());
					return matchJsonContent.assertTimestamp(String.join(".", cfg.getContentRef().getPath()), cfg.getContentRef().getConversionPattern(),
							matcher(cfg.getOperator(), sdf.parse(cfg.getValue()), cfg.getContentRef().getContentType()));
				}
				return matchJsonContent.assertTimestamp(String.join(".", cfg.getContentRef().getPath()), cfg.getContentRef().getConversionPattern(),
						matcher(cfg.getOperator(), null, cfg.getContentRef().getContentType()));
			}
			default:
				return matchJsonContent;

		}

	}

	/**
	 * Returns a {@link Matcher} instance depending on the provided input
	 * @param matcherType
	 * @param value
	 * @param type
	 * @return
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 */
	protected <T extends Comparable<T>> Matcher<T> matcher(final FieldConditionOperator matcherType, final T value, final JsonContentType type) throws NoSuchMethodException, IllegalArgumentException {

		///////////////////////////////////////////////////////////////////////
		// validate provided input
		if(matcherType == null)
			throw new IllegalArgumentException("Missing required matcher type");
		if(type == null)
			throw new IllegalArgumentException("Missing required content type");
		///////////////////////////////////////////////////////////////////////

		switch(matcherType) {
			case GREATER_THAN: {
				return Matchers.greaterThan(value);
			}
			case IS: {
				return Matchers.is(value);
			}
			case IS_EMPTY: {
				throw new NoSuchMethodException("is_empty is currently not supported");
			}
			case LESS_THAN: {
				return Matchers.lessThan(value);
			}
			case LIKE: {
				return RegularExpressionMatcher.matchesPattern((value != null ? value.toString() : null));
			}
			case NOT: {
				return Matchers.not(value);
			}
			case NOT_EMPTY: {
				throw new NoSuchMethodException("not_empty is not supported");
			}
			default:
				throw new NoSuchMethodException(matcherType + " is currently not supported");
		}

	}

}


text:
<?php get_template_part('templates/blog', 'header'); ?>
<?php while (have_posts()) : the_post(); ?>
<article <?php post_class('singlepost'); ?>>

        <?php if ( get_field('hasdate')==0 ) : ?>
          <?php get_template_part('templates/entry-meta'); ?>

<?php the_title(); ?>

        <?php else: ?>

<?php the_title(); ?>

          <?php get_template_part('templates/entry-meta'); ?>
        <?php endif; ?>

          <?php
          global $more; $more = 0;
          the_excerpt();
          ?>

        <?php if ( has_post_thumbnail() ) : ?>

          <?php the_post_thumbnail(large); ?>

<?php the_title(); ?>

      <?php endif; ?>
        <?php $more=1; the_content('', TRUE); ?>

        <?php wp_link_pages(['before' => '
' . __('Pages:', 'bikram'), 'after' => '
']); ?>

  <?php //comments_template('/templates/comments.php'); ?>

<?php endwhile; ?>
<?php get_template_part('templates/sticky', 'block'); ?>

redpajama_set_name: RedPajamaGithub


text:
var STRING: string;
var STRING1: string[] = ["", "abc"];

function foo(): string { return "abc"; }

class A {
    public a: string;
    static foo() { return ""; }
}
module M {
    export var n: string;
}

var objA = new A();

// string type var
var ResultIsAny1 = void STRING;
var ResultIsAny2 = void STRING1;

// string type literal
var ResultIsAny3 = void "";
var ResultIsAny4 = void { x: "", y: "" };
var ResultIsAny5 = void { x: "", y: (s: string) => { return s; } };

// string type expressions
var ResultIsAny6 = void objA.a;
var ResultIsAny7 = void M.n;
var ResultIsAny8 = void STRING1[0];
var ResultIsAny9 = void foo();
var ResultIsAny10 = void A.foo();
var ResultIsAny11 = void (STRING + STRING);
var ResultIsAny12 = void STRING.charAt(0);

// multiple void  operators
var ResultIsAny13 = void void STRING;
var ResultIsAny14 = void void void (STRING + STRING);

// miss assignment operators
void "";
void STRING;
void STRING1;
void foo();
void objA.a,M.n;


text:
using System;

namespace Patterns.Structural.Bridge
{
    ///
    /// Abstraction - абстракция
    ///
    /// <remarks>
    ///

    /// <lu>определяем интерфейс абстракции;</lu>
    /// <lu>хранит ссылку на объект <see cref="Implementor"/></lu>
    ///

    /// </remarks>
    class Abstraction
    {
        protected Implementor implementor;

        // Property
        public Implementor Implementor
        {
            get { return implementor; }
            set { implementor = value; }
        }

        public virtual void Operation()
        {
            implementor.Operation();
        }
    }

    ///
    /// Implementor - реализатор
    ///
    /// <remarks>
    ///

    /// <lu>определяет интерфейс для классов реализации. Он не обязан точно
    /// соотведствовать интерфейсу класса <see cref="Abstraction"/>. На самом деле оба
    /// интерфейса могут быть совершенно различны. Обычно интерфейс класса
    /// <see cref="Implementor"/> представляет только примитивные операции, а класс
    /// <see cref="Abstraction"/> определяет операции более высокого уровня,
    /// базирующиеся на этих примитивах;</lu>
    ///

    /// </remarks>
    abstract class Implementor
    {
        public abstract void Operation();
    }

    ///
    /// RefinedAbstraction - уточненная абстракция
    ///
    /// <remarks>
    ///

    /// <lu>расширяет интерфейс, определенный абстракцией <see cref="Abstraction"/></lu>
    ///

    /// </remarks>
    class RefinedAbstraction : Abstraction
    {
        public override void Operation()
        {
            implementor.Operation();
        }
    }

    ///
    /// ConcreteImplementor - конкретный реализатор
    ///
    /// <remarks>
    ///

    /// <lu>содержит конкретную реализацию интерфейса <see cref="Implementor"/></lu>
    ///

    /// </remarks>
    class ConcreteImplementorA : Implementor
    {
        public override void Operation()
        {
            Console.WriteLine("ConcreteImplementorA Operation");
        }
    }

    // "ConcreteImplementorB"

    class ConcreteImplementorB : Implementor
    {
        public override void Operation()
        {
            Console.WriteLine("ConcreteImplementorB Operation");
        }
    }
}


text:
package com.example.jimyzak.myapplication;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by marwen on 13/12/15.
 */
public class MenuItems extends BaseAdapter {
    Context context;
    ArrayList<Menu> menuArrayList;

    public MenuItems(Context context, ArrayList<Menu> menuArrayList) {
        this.context = context;
        this.menuArrayList = menuArrayList;
    }

    @Override
    public int getCount() {
        return menuArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return menuArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        MonitorViewMenu monitorViewMenu = new MonitorViewMenu();
        while (view == null) {
            view = View.inflate(context, R.layout.content_liste_menu, null);
            monitorViewMenu.libelleMenu = (TextView) view.findViewById(R.id.libelleMenu);
            view.setTag(monitorViewMenu);
        }

        monitorViewMenu = (MonitorViewMenu) view.getTag();
        monitorViewMenu.libelleMenu.setText((int) menuArrayList.get(position).getPrice());
        return view;
    }

    @Override
    public int getItemViewType(int position) {
        return 0;
    }

    @Override
    public int getViewTypeCount() {
        return 0;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }
}


text:
These scripts are for automatically configuring the REV7 and REV10 into sets for production.

config_rev7:     Sets the primary building key (encryption key) and the set back lockout and records the node IDs for use with the REV10.
rev10-config.py: Sets primary building key (encryption key) and the node IDs of associated REV7s.


text:
from oslo_log import log as logging

from cinder.api import common

LOG = logging.getLogger(__name__)

class ViewBuilder(common.ViewBuilder):
    """Model consistencygroup API responses as a python dictionary."""

    _collection_name = "consistencygroups"

    def __init__(self):
        """Initialize view builder."""
        super(ViewBuilder, self).__init__()

    def summary_list(self, request, consistencygroups):
        """Show a list of consistency groups without many details."""
        return self._list_view(self.summary, request, consistencygroups)

    def detail_list(self, request, consistencygroups):
        """Detailed view of a list of consistency groups ."""
        return self._list_view(self.detail, request, consistencygroups)

    def summary(self, request, consistencygroup):
        """Generic, non-detailed view of a consistency group."""
        return {
            'consistencygroup': {
                'id': consistencygroup.id,
                'name': consistencygroup.name
            }
        }

    def detail(self, request, consistencygroup):
        """Detailed view of a single consistency group."""
        if consistencygroup.volume_type_id:
            volume_types = consistencygroup.volume_type_id.split(",")
            volume_types = [type_id for type_id in volume_types if type_id]
        else:
            volume_types = []

        return {
            'consistencygroup': {
                'id': consistencygroup.id,
                'status': consistencygroup.status,
                'availability_zone': consistencygroup.availability_zone,
                'created_at': consistencygroup.created_at,
                'name': consistencygroup.name,
                'description': consistencygroup.description,
                'volume_types': volume_types,
            }
        }

    def _list_view(self, func, request, consistencygroups):
        """Provide a view for a list of consistency groups."""
        consistencygroups_list = [
            func(request, consistencygroup)['consistencygroup']
            for consistencygroup in consistencygroups]
        cg_links = self._get_collection_links(request,
                                              consistencygroups,
                                              self._collection_name)
        consistencygroups_dict = dict(consistencygroups=consistencygroups_list)
        if cg_links:
            consistencygroups_dict['consistencygroup_links'] = cg_links

        return consistencygroups_dict


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="DeveloperBus - Equipo 1 -HotStreet">
    <link rel="shortcut icon" href="img/favicon.ico">
    <title>Hot street!</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

        <form id="form-init" class="form-inline" action="#" role="form">

                <input type="text" class="form-control" id="tags" placeholder="Que estas buscando?">

            <button id="generar" type="submit" class="btn btn-default">Buscar</button>

                <button id="ubicacion" type="button" class="btn btn-info" onclick="find_location()">Ubicame</button>

        </form>


text:
package de.tu_berlin.cit.intercloud.occi.sla;

import de.tu_berlin.cit.intercloud.occi.core.annotations.Attribute;
import de.tu_berlin.cit.intercloud.occi.core.annotations.Category;
import de.tu_berlin.cit.intercloud.occi.core.annotations.Mixin;
import de.tu_berlin.cit.intercloud.occi.core.annotations.Attribute.AttributeType;

/**
 * This mixin defines a window with a fix time length.
 *
 * @author Alexander Stanik <alexander.stanik@tu-berlin.de>
 */
@Mixin(schema = SlaSchemas.ServiceEvaluatorMixinSchema, term = TimeWindowMetricMixin.TimeWindowMetricTerm,
		applies = SlaSchemas.SlaSchema + ServiceEvaluatorLink.ServiceEvaluatorTerm)
public class TimeWindowMetricMixin extends Category {

	public final static String TimeWindowMetricTitle = "Time Window Metric Mixin";

	public final static String TimeWindowMetricTerm = "timewindow";

	public TimeWindowMetricMixin() {
		super(TimeWindowMetricTitle);
	}

	public TimeWindowMetricMixin(String title) {
		super(title);
	}

	public enum WindowType {
		SlidingWindow,
		BatchWindow
	}

	/**
	 * The type of the window, i.e. either a periodically assessed window or a continuously assessed window.
	 */
	@Attribute(name = "intercloud.sla.metric.windowtype",
			type = AttributeType.ENUM,
			mutable = true,
			required = true,
			value = "SlidingWindow",
			description = "The type of the window, i.e. either a periodically assessed window (BatchWindow) or a continuously assessed window (SlidingWindow).")
	public WindowType windowType = WindowType.SlidingWindow;

	/**
	 * The time length of the window, i.e. the duration that this window is assess.
	 */
	@Attribute(name = "intercloud.sla.metric.windowduration",
			type = AttributeType.INTEGER,
			mutable = true,
			required = true,
			description = "The time length of the window, i.e. the duration that this window is assess.")
	public Integer windowDuration = null;

	public enum TimeUnit {
		years,
		months,
		weeks,
		days,
		hours,
		minutes,
		seconds,
		milliseconds
	}

	/**
	 * The unit in which time length of the window is specified.
	 */
	@Attribute(name = "intercloud.sla.metric.durationunit",
			type = AttributeType.ENUM,
			mutable = true,
			required = true,
			value = "seconds",
			description = "The unit in which time length of the window is specified (e.g. years, months, weeks, days, hours, minutes, seconds, or milliseconds).")
	public TimeUnit durationUnit = TimeUnit.seconds;

}


text:
from __future__ import absolute_import

from sentry.utils.db import get_db_engine
from sentry.testutils import TestCase

class GetDbEngineTest(TestCase):
    def test_with_dotted_path(self):
        with self.settings(DATABASES={"default": {"ENGINE": "blah.postgres"}}):
            self.assertEquals(get_db_engine(), "postgres")

    def test_no_path(self):
        with self.settings(DATABASES={"default": {"ENGINE": "postgres"}}):
            self.assertEquals(get_db_engine(), "postgres")


text:
// Copyright 2020 The XLS Authors
//
// Licensed 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.

#include "xls/dslx/parametric_expression.h"

namespace xls::dslx {

/* static */ ParametricExpression::Evaluated ParametricExpression::ToEvaluated(
    const EnvValue& value) {
  if (std::holds_alternative<InterpValue>(value)) {
    return std::get<InterpValue>(value);
  }
  return std::get<const ParametricExpression*>(value)->Clone();
}

/* static */ ParametricExpression::EnvValue ParametricExpression::ToEnvValue(
    const Evaluated& v) {
  if (std::holds_alternative<InterpValue>(v)) {
    return std::get<InterpValue>(v);
  }
  return std::get<std::unique_ptr<ParametricExpression>>(v).get();
}

std::unique_ptr<ParametricExpression> ParametricExpression::ToOwned(
    const std::variant<const ParametricExpression*, InterpValue>& operand) {
  if (std::holds_alternative<InterpValue>(operand)) {
    return std::make_unique<ParametricConstant>(std::get<InterpValue>(operand));
  }
  return std::get<const ParametricExpression*>(operand)->Clone();
}

std::unique_ptr<ParametricExpression> ParametricExpression::Add(
    const EnvValue& lhs, const EnvValue& rhs) {
  if (std::holds_alternative<InterpValue>(lhs) &&
      std::holds_alternative<InterpValue>(rhs)) {
    return std::make_unique<ParametricConstant>(
        std::get<InterpValue>(lhs).Add(std::get<InterpValue>(rhs)).value());
  }
  return std::make_unique<ParametricAdd>(ToOwned(lhs), ToOwned(rhs));
}
std::unique_ptr<ParametricExpression> ParametricExpression::Mul(
    const EnvValue& lhs, const EnvValue& rhs) {
  if (std::holds_alternative<InterpValue>(lhs) &&
      std::holds_alternative<InterpValue>(rhs)) {
    return std::make_unique<ParametricConstant>(
        std::get<InterpValue>(lhs).Mul(std::get<InterpValue>(rhs)).value());
  }
  return std::make_unique<ParametricMul>(ToOwned(lhs), ToOwned(rhs));
}
ParametricExpression::Evaluated ParametricExpression::TryUnwrapConstant(
    std::unique_ptr<ParametricExpression> e) {
  if (auto* c = dynamic_cast<ParametricConstant*>(e.get())) {
    return c->value();
  }
  return std::move(e);
}

}  // namespace xls::dslx


text:
function string:split( inSplitPattern, outResults )
	if not outResults then
		outResults = { }
	end
	local theStart = 1
	local theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
	while theSplitStart do
		table.insert( outResults, string.sub( self, theStart, theSplitStart-1 ) )
		theStart = theSplitEnd + 1
		theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
	end
	table.insert( outResults, string.sub( self, theStart ) )
	return outResults
end

function read_lines(filename)
	lines = {}

	for line in io.lines(file) do
		lines[#lines + 1] = line
	end

	return lines
end

function load_model(filename)
	model = {v = {}, vt = {}, vn = {}, f = {}}
	for _, line in read_lines(filename) do
		arr = line:split(" ")
		_, model[arr[1]]
	end
end


text:
require([ 'require.config' ], function() {
    require([ 'jQuery', 'Underscore', 'Backbone', './TopView' ],
    //
    function($, _, Backbone, TopView) {

        var ContentView = TopView.extend({
            template : _.template('' + '
'
                    + '
Content
'
                    + '
'),
            renderParagraphs : function(el) {
                var parent = el.parent();
                el.remove();
                _.each(this.model.get('content'), function(p) {
                    var e = el.clone();
                    e.html(p);
                    e.click(function() {
                        alert(e.html());
                    })
                    parent.append(e);
                }, this);
            }

        });

        var View = TopView.extend({
            template : _.template('' + '
'
                    + '
Title
'
                    + '
Content
'
                    + '
'),
            renderTop : function(el) {
                console.log('Render Top');
            },
            renderTitle : function(el) {
                el.html(this.model.get('title'))
                var that = this;
                el.click(function() {
                    that.contentEl.toggle();
                })
            },
            renderContent : function(el) {
                this.contentEl = el;
                new ContentView({
                    el : el,
                    model : this.model
                }).render();
                return false;
            }
        })

        new View({
            model : new Backbone.Model({
                title : 'Hello, world!',
                content : [ 'This is a content', 'Second paragraph' ]
            }),
            el : $('#main')
        }).render()

    });
})


text:
package com.intellij.psi.search;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;

/**
 * @author peter
 */
public class DelegatingGlobalSearchScope extends GlobalSearchScope {
  protected final GlobalSearchScope myBaseScope;
  private final Object myEquality;

  public DelegatingGlobalSearchScope(@NotNull GlobalSearchScope baseScope) {
    super(baseScope.getProject());
    myBaseScope = baseScope;
    myEquality = ArrayUtil.EMPTY_OBJECT_ARRAY;
  }

  public DelegatingGlobalSearchScope(GlobalSearchScope baseScope, Object... equality) {
    super(baseScope.getProject());
    myBaseScope = baseScope;
    myEquality = Arrays.asList(equality);
  }

  @Override
  public boolean contains(VirtualFile file) {
    return myBaseScope.contains(file);
  }

  @Override
  public int compare(VirtualFile file1, VirtualFile file2) {
    return myBaseScope.compare(file1, file2);
  }

  @Override
  public boolean isSearchInModuleContent(@NotNull Module aModule) {
    return myBaseScope.isSearchInModuleContent(aModule);
  }

  @Override
  public boolean isSearchInModuleContent(@NotNull Module aModule, boolean testSources) {
    return myBaseScope.isSearchInModuleContent(aModule, testSources);
  }

  @Override
  public boolean isSearchInLibraries() {
    return myBaseScope.isSearchInLibraries();
  }

  @Override
  public boolean isSearchOutsideRootModel() {
    return myBaseScope.isSearchOutsideRootModel();
  }

  @Override
  public String getDisplayName() {
    return myBaseScope.getDisplayName();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    DelegatingGlobalSearchScope that = (DelegatingGlobalSearchScope)o;

    if (!myBaseScope.equals(that.myBaseScope)) return false;
    if (!myEquality.equals(that.myEquality)) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = myBaseScope.hashCode();
    result = 31 * result + myEquality.hashCode();
    return result;
  }
}


text:
from numpy import array
from dazer_methods import Dazer
import matplotlib.pyplot as plt
from lib.Astro_Libraries.Abundances_InferenceModel_Helium_v20 import Run_MCMC

#Declare operation objects
dz  = Dazer()
bm  = Run_MCMC()

#MCMC configuration run
default_db_folder   = '/home/vital/Astrodata/Inference_output/'
db_name_ext         = 'pymc3_stellar'
iterat, burn, thin  = 7000, 1000, 1 #15000, 1500, 2
synth_model         = 'initial_tests'
params_list         = ['z_star','sigma_star','Av_star', 'chiSq_ssp']
synth_model         = 'ssp_synthesis_pymc3'
db_name_ext         = 'ssp_testsErrNew'

#Generate the synthetic data
bm.calculate_synthFluxes(synth_model)

print '-----Declaring the mod'

# #Select right model according to data
# bm.select_inference_model(synth_model)

#Variables to save
db_address  = '{}{}_it{}_burn{}_thin{}_{}'.format(default_db_folder, synth_model, iterat, burn, thin, db_name_ext)

print '-----This is the runner'
# # #Run sampler
bm.run_pymc3(db_address, iterat, burn, thin, variables_list=params_list)

# #Load database
# pymc2_db, stat_db_dict = bm.load_pymc_database(db_address)
#
# #Traces plot
# dz.traces_plot(params_list, pymc2_db, stat_db_dict)
# dz.save_manager(db_address + '_tracesPlot', save_pickle = False)
#
# #Posteriors plot
# dz.posteriors_plot(params_list, pymc2_db, stat_db_dict)
# dz.save_manager(db_address + '_posteriorPlot', save_pickle = False)
#
# #Posteriors plot
# dz.acorr_plot(params_list, pymc2_db, stat_db_dict, n_columns=1, n_rows=len(params_list))
# dz.save_manager(db_address + '_acorrPlot', save_pickle = False)
#
# #Corner plot
# dz.corner_plot(params_list, pymc2_db, stat_db_dict)
# dz.save_manager(db_address + '_cornerPlot', save_pickle = False)


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eas.client.dbstructure.gui.edits;

import com.eas.client.dbstructure.SqlActionsController;
import com.eas.client.dbstructure.SqlActionsController.DescribeFieldAction;
import com.eas.client.dbstructure.SqlActionsController.ModifyFieldAction;
import com.eas.client.dbstructure.SqlActionsController.RenameFieldAction;
import com.eas.client.dbstructure.exceptions.DbActionException;
import com.eas.client.metadata.Field;
import com.eas.client.metadata.Fields;

/**
 *
 * @author mg
 */
public class ModifyFieldEdit extends DbStructureEdit {

    protected Fields fields;
    protected Field oldFieldSpec;
    protected Field newFieldSpec;
    protected String tableName;
    protected boolean namesAreDifferent;
    protected boolean contentsAreDifferent;
    protected boolean commentsAreDifferent;

    public ModifyFieldEdit(SqlActionsController aSqlController, String aTableName, Fields aFields, Field aOldFieldSpec, Field aNewFieldSpec) {
        super(aSqlController);
        fields = aFields;
        oldFieldSpec = aOldFieldSpec;
        newFieldSpec = aNewFieldSpec;
        tableName = aTableName;
        namesAreDifferent = !oldFieldSpec.getName().toLowerCase().equals(newFieldSpec.getName().toLowerCase());
        String oldDescription = oldFieldSpec.getDescription() != null ? oldFieldSpec.getDescription().toLowerCase() : "";
        String newDescription = newFieldSpec.getDescription() != null ? newFieldSpec.getDescription().toLowerCase() : "";
        commentsAreDifferent = !oldDescription.equals(newDescription);
        Field lNewFieldSpec = new Field(newFieldSpec);
        lNewFieldSpec.setName(oldFieldSpec.getName());
        lNewFieldSpec.setDescription(oldFieldSpec.getDescription());
        contentsAreDifferent = !oldFieldSpec.isEqual(lNewFieldSpec);
        assert contentsAreDifferent || namesAreDifferent || commentsAreDifferent;
    }

    @Override
    protected void doUndoWork() throws Exception {
        if (namesAreDifferent) {
            fields.invalidateFieldsHash();
            RenameFieldAction sqlAction1 = sqlController.createRenameFieldAction(tableName, newFieldSpec.getName(), oldFieldSpec);
            if (!sqlAction1.execute()) {
                DbActionException ex = new DbActionException(sqlAction1.getErrorString());
                ex.setParam1(tableName);
                ex.setParam2(newFieldSpec.getName());
                throw ex;
            }
        }
        if (contentsAreDifferent) {
            ModifyFieldAction sqlAction = sqlController.createModifyFieldAction(tableName, newFieldSpec, oldFieldSpec);
            if (!sqlAction.execute()) {
                DbActionException ex = new DbActionException(sqlAction.getErrorString());
                ex.setParam1(tableName);
                ex.setParam2(newFieldSpec.getName());
                throw ex;
            }
        }
        if (commentsAreDifferent) {
            DescribeFieldAction sqlAction = sqlController.createDescribeFieldAction(tableName, oldFieldSpec.getName(), oldFieldSpec.getDescription());
            if (!sqlAction.execute()) {
                DbActionException ex = new DbActionException(sqlAction.getErrorString());
                ex.setParam1(tableName);
                ex.setParam2(oldFieldSpec.getName());
                throw ex;
            }
        }
    }

    @Override
    protected void doRedoWork() throws Exception {
        if (namesAreDifferent) {
            fields.invalidateFieldsHash();
            RenameFieldAction sqlAction1 = sqlController.createRenameFieldAction(tableName, oldFieldSpec.getName(), newFieldSpec);
            if (!sqlAction1.execute()) {
                DbActionException ex = new DbActionException(sqlAction1.getErrorString());
                ex.setParam1(tableName);
                ex.setParam2(oldFieldSpec.getName());
                throw ex;
            }
        }
        if (contentsAreDifferent) {
            ModifyFieldAction sqlAction = sqlController.createModifyFieldAction(tableName, oldFieldSpec, newFieldSpec);
            if (!sqlAction.execute()) {
                DbActionException ex = new DbActionException(sqlAction.getErrorString());
                ex.setParam1(tableName);
                ex.setParam2(oldFieldSpec.getName());
                throw ex;
            }
        }
        if (commentsAreDifferent) {
            DescribeFieldAction sqlAction = sqlController.createDescribeFieldAction(tableName, newFieldSpec.getName(), newFieldSpec.getDescription());
            if (!sqlAction.execute()) {
                DbActionException ex = new DbActionException(sqlAction.getErrorString());
                ex.setParam1(tableName);
                ex.setParam2(newFieldSpec.getName());
                throw ex;
            }
        }
    }

    @Override
    protected String getChangingTableName() {
        return tableName;
    }
}


text:
import logging
import os

from google.cloud import bigquery

from load_benchmark_tools import load_table_benchmark
from generic_benchmark_tools import bucket_util
from query_benchmark_tools import federated_query_benchmark

class BenchmarkRunner:
    """Contains methods for processing benchmark resources and running
    benchmarks.

    Attributes:
        bq_project(str): ID of the project that holds the BigQuery dataset
            and benchmark tables.
        gcs_project(str):  ID of the project that holds the GCS bucket
            where the files needed for benchmarks stored.
        staging_project(str_: ID of the project that contains the
            staging tables that the files to be loaded into the tables
            were generated from.
        staging_dataset_id(str): ID of the dataset that contains the
            staging tables that the files to be loaded into the tables
            were generated from.
        dataset_id(str): ID of the dataset that will hold the tables for
            loading.
        bucket_name(str): Name of the GCS bucket that holds the files that
            should be loaded into tables.
        bucket_util(generic_benchmark_tools.bucket_util.BucketUtil): Helper
            class for interacting with the bucket that the holds the files used
            for benchmarks.
        results_table_name(str): Name of the BigQuery table that benchmark
            results will be inserted into.
        results_table_dataset_id(str): Name of the BigQuery dataset that
            benchmark results will be inserted into.
        duplicate_benchmark_tables(bool): Boolean value to determine what to
            do if a file has already been loaded into a table for a give file
            combination. If True, BenchmarkRunner will run the benchmark again
            with the same combination to increase the number of results for
            accuracy. If not, BenchmarkRunner will only create a benchmark table
            for a given combination if one has not yet been created.
        file_params(dict): Dictionary containing each file parameter and
            its possible values.
        bq_logs_dataset(str): Name of dataset hold BQ logs table.
        run_federated_query_benchmark(Bool): Flag to indicate that the
            Federated Query Benchmark is the primary benchmark running.
        include_federated_query_benchmark(Bool): Flag to indicate that the
            Federated Query Benchmark should be run along with the File Loader
            Benchmark.
        files_to_skip(set): Set of file URIs to skip if necessary.

    """

    def __init__(self,
                 bq_project,
                 gcs_project,
                 staging_project,
                 staging_dataset_id,
                 dataset_id,
                 bucket_name,
                 results_table_name,
                 results_table_dataset_id,
                 duplicate_benchmark_tables,
                 file_params,
                 bq_logs_dataset,
                 run_federated_query_benchmark=False,
                 include_federated_query_benchmark=False):
        self.bq_project = bq_project
        self.gcs_project = gcs_project
        self.staging_project = staging_project
        self.staging_dataset_id = staging_dataset_id
        self.dataset_id = dataset_id
        self.bucket_name = bucket_name
        self.bucket_util = bucket_util.BucketUtil(
            bucket_name=self.bucket_name,
            project_id=self.gcs_project,
            file_params=file_params,
        )
        self.results_table_name = results_table_name
        self.results_table_dataset_id = results_table_dataset_id
        self.duplicate_benchmark_tables = duplicate_benchmark_tables
        self.bq_logs_dataset = bq_logs_dataset
        self.run_federated_query_benchmark = run_federated_query_benchmark
        self.include_federated_query_benchmark = \
            include_federated_query_benchmark
        self.files_to_skip = set()

    def execute_file_loader_benchmark(self):
        """Processes files to skip and runs File Load Benchmark"""
        files_with_benchmark_tables = self._gather_files_with_benchmark_data()
        if not self.duplicate_benchmark_tables:
            self.files_to_skip = files_with_benchmark_tables
        self._create_tables(files_with_benchmark_tables)

    def execute_federated_query_benchmark(self):
        """Processes files to skip and runs Federated Query Benchmark"""
        files_with_benchmark_tables = self._gather_files_with_benchmark_data()
        self._create_tables(files_with_benchmark_tables)

    def _gather_files_with_benchmark_data(self):
        """Generates file combinations that already have load benchmark data.

        Creates a set of files that already have been loaded to create
        benchmark tables. Generates list by querying the job.sourceURI field
        from the results table.
        Returns:
            Set of file names that already have been loaded to create
            benchmark tables.
        """
        query = (
            'SELECT loadProperties.sourceURI FROM `{0:s}.{1:s}.{2:s}` '.format(
                self.bq_project,
                self.results_table_dataset_id,
                self.results_table_name,
            ))
        query_job = bigquery.Client().query(
            query,
            location='US',
        )
        files_with_benchmark_tables = set()
        for row in query_job:
            if row['sourceURI'] and self.bucket_name in row['sourceURI']:
                uri = row['sourceURI'].split('gs://{0:s}/'.format(
                    self.bucket_name))[1]
                file_name = uri.split('/*')[0]
                files_with_benchmark_tables.add(file_name)
        return files_with_benchmark_tables

    def _create_tables(self, files_with_benchmark_data):
        """Creates a table for each file combination in GCS bucket.

        Args:
            files_with_benchmark_data(set): Set of file names that already
            have benchmark data.
        """
        # Gather file combinations that exist in the GCS Bucket.
        existing_paths = self.bucket_util.get_existing_paths(
            run_federated_query_benchmark=self.run_federated_query_benchmark)
        # Create a benchmark table for each existing file combination, and
        # load the data from the file into the benchmark table.
        for path in existing_paths:
            dirname = os.path.dirname(path)
            if dirname not in self.files_to_skip:
                if dirname in files_with_benchmark_data:
                    verb = 'Duplicating'
                else:
                    verb = 'Processing'
                logging.info('{0:s} benchmark table for {1:s}'.format(
                    verb,
                    dirname,
                ))
                table = load_table_benchmark.LoadTableBenchmark(
                    bq_project=self.bq_project,
                    gcs_project=self.gcs_project,
                    staging_project=self.staging_project,
                    staging_dataset_id=self.staging_dataset_id,
                    dataset_id=self.dataset_id,
                    bucket_name=self.bucket_name,
                    dirname=dirname,
                    results_table_name=self.results_table_name,
                    results_table_dataset_id=self.results_table_dataset_id,
                    bq_logs_dataset=self.bq_logs_dataset)
                table_name = table.create_table()
                table.load_from_gcs()
                if self.run_federated_query_benchmark or \
                        self.include_federated_query_benchmark:

                    self._run_federated_query(table_name, dirname)
                table.delete_table()

    def _run_federated_query(self, table_name, dirname):
        """Runs the Federated Query Benchmark.

        Args:
           table_name(str): ID of the BigQuery table to run the native query on.
           dirname(str): Directory of the file(s) to run the external query on.
        """
        uri = 'gs://{0:s}/{1:s}'.format(self.bucket_name, dirname)
        query_benchmark = federated_query_benchmark \
            .FederatedQueryBenchmark(
                bq_project=self.bq_project,
                gcs_project=self.gcs_project,
                dataset_id=self.dataset_id,
                bq_logs_dataset_id=self.bq_logs_dataset,
                native_table_id=table_name,
                bucket_name=self.bucket_name,
                file_uri=uri,
                results_table_name=self.results_table_name,
                results_table_dataset_id=self.results_table_dataset_id
            )
        logging.info('Running Federated Query Benchmark for BQ managed '
                     'table {0:s} and file {1:s}'.format(table_name, uri))
        query_benchmark.run_queries()


text:
package consul

import "time"

type Option func(p *Provider)

func WithTTL(ttl time.Duration) Option {
	return func(p *Provider) {
		p.ttl = ttl
	}
}

func WithRefreshTTL(refreshTTL time.Duration) Option {
	return func(p *Provider) {
		p.refreshTTL = refreshTTL
	}
}

func WithConsulServerAddress(address string) Option {
	return func(p *Provider) {
		p.consulServerAddress = address
	}
}


text:
package clarifai2.api.request.model;

import clarifai2.internal.grpc.api.ModelVersionOuterClass;
import clarifai2.api.BaseClarifaiClient;
import clarifai2.api.request.ClarifaiPaginatedRequest;
import clarifai2.dto.model.ModelVersion;
import com.google.common.util.concurrent.ListenableFuture;
import org.jetbrains.annotations.NotNull;

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

public final class GetModelVersionsRequest
    extends ClarifaiPaginatedRequest.Builder<List<ModelVersion>, GetModelVersionsRequest> {

  @NotNull private final String modelID;

  public GetModelVersionsRequest(@NotNull final BaseClarifaiClient client, @NotNull String modelID) {
    super(client);
    this.modelID = modelID;
  }

  @NotNull @Override protected String method() {
    return "GET";
  }

  @NotNull @Override protected String subUrl(int page) {
    return buildURL("v2/models/" + modelID + "/versions", page);
  }

  @NotNull @Override protected List<ModelVersion> unmarshalerGrpc(Object returnedObject) {
    ModelVersionOuterClass.MultiModelVersionResponse modelVersionsResponse =
        (ModelVersionOuterClass.MultiModelVersionResponse) returnedObject;

    List<ModelVersion> modelVersions = new ArrayList<>();
    for (ModelVersionOuterClass.ModelVersion modelVersion : modelVersionsResponse.getModelVersionsList()) {
      modelVersions.add(ModelVersion.deserialize(modelVersion));
    }

    return modelVersions;
  }

  @NotNull @Override protected ListenableFuture buildRequestGrpc(int page) {
    return stub(page).listModelVersions(ModelVersionOuterClass.ListModelVersionsRequest.newBuilder().build());
  }
}


text:
This warning indicates that Infer was not able to determine a static
upper bound on the execution cost of the procedure. By default, this
issue type is disabled.

### Example 1: T due to expressivity

For instance, Inferbo's interval analysis is limited to affine
expressions. Hence, we can't statically estimate an upper bound on the
below example and obtain T(unknown) cost:
```java
// Expected: square root(x), got T
void square_root_FP(int x) {
 int i = 0;
 while (i * i < x) {
   i++;
 }
}
```
### Example 2: T due to unmodeled calls
Another common case where we get T cost is when Infer cannot statically determine the range of values for loop bounds. For instance,

```java
void loop_over_charArray_FP(StringBuilder builder, String input) {
  for (Character c : input.toCharArray()) {}
}
```
Here, Infer does not have any InferBo models for the range of values returned by `String.toCharArray`, hence it cannot determine that we will be iterating over a char array in the size of `input` string.

To teach InferBo about such library calls, they should be semantically modeled in [InferBo](https://github.com/facebook/infer/blob/main/infer/src/bufferoverrun/bufferOverrunModels.ml).

### Example 3: T due to calling another T-costed function
Since the analysis is inter-procedural, another example we can have T cost is if at least one of the callees has T cost.

```java
// Expected: constant, got T
void call_top_cost_FP() {
 square_root_FP(1); // square_root_FP has Top cost
}
```


text:
package io.bootique.jersey.client;

import io.bootique.BQRuntime;
import io.bootique.Bootique;
import io.bootique.jersey.JerseyModule;
import io.bootique.jetty.JettyModule;
import io.bootique.jetty.junit5.JettyTester;
import io.bootique.junit5.BQApp;
import io.bootique.junit5.BQTest;
import io.bootique.junit5.BQTestFactory;
import io.bootique.junit5.BQTestTool;
import io.bootique.logback.LogbackModuleProvider;
import org.junit.jupiter.api.Test;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import static org.junit.jupiter.api.Assertions.assertEquals;

@BQTest
public class HttpClientFactoryIT {

    static final JettyTester jetty = JettyTester.create();

    @BQApp
    static final BQRuntime server = Bootique.app("--server")
            .modules(JettyModule.class, JerseyModule.class)
            .moduleProvider(new LogbackModuleProvider())
            .module(b -> JerseyModule.extend(b).addResource(Resource.class))
            .module(jetty.moduleReplacingConnectors())
            .createRuntime();

    @BQTestTool
    final BQTestFactory clientFactory = new BQTestFactory();

    @Test
    public void testNewClient() {
        HttpClientFactory factory =
                clientFactory.app()
                        .moduleProvider(new JerseyClientModuleProvider())
                        .moduleProvider(new LogbackModuleProvider())
                        .createRuntime()
                        .getInstance(HttpClientFactory.class);

        Client client = factory.newClient();

        Response r1 = client.target(JettyTester.getUrl(server)).path("get").request().get();
        assertEquals(Response.Status.OK.getStatusCode(), r1.getStatus());
        assertEquals("got", r1.readEntity(String.class));
    }

    @Test
    public void testNewClientAuth() {
        HttpClientFactory factory =
                clientFactory.app()
                        .moduleProvider(new JerseyClientModuleProvider())
                        .moduleProvider(new LogbackModuleProvider())
                        .property("bq.jerseyclient.auth.auth1.type", "basic")
                        .property("bq.jerseyclient.auth.auth1.username", "u")
                        .property("bq.jerseyclient.auth.auth1.password", "p")
                        .createRuntime()
                        .getInstance(HttpClientFactory.class);

        Client client = factory.newBuilder().auth("auth1").build();

        Response r1 = client.target(JettyTester.getUrl(server)).path("get_auth").request().get();
        assertEquals(Response.Status.OK.getStatusCode(), r1.getStatus());
        assertEquals("got_Basic dTpw", r1.readEntity(String.class));
    }

    @Path("/")
    @Produces(MediaType.TEXT_PLAIN)
    public static class Resource {

        @GET
        @Path("get")
        public String get() {
            return "got";
        }

        @GET
        @Path("get_auth")
        public String getAuth(@HeaderParam("Authorization") String auth) {
            return "got_" + auth;
        }
    }
}


text:
PROJECT = diffy
REBAR := $(shell which rebar 2>/dev/null || echo ./rebar)
REBAR_URL := https://github.com/downloads/basho/rebar/rebar
DIALYZER = dialyzer

all: compile

./rebar:
	erl -noshell -s inets start -s ssl start \
        -eval '{ok, saved_to_file} = httpc:request(get, {"$(REBAR_URL)", []}, [], [{stream, "./rebar"}])' \
        -s inets stop -s init stop
	chmod +x ./rebar

compile: rebar
	$(REBAR) compile

eunit: rebar
	$(REBAR) get-dep compile
	$(REBAR) eunit -v skip_deps=true

clean: rebar
	$(REBAR) clean

distclean:
	rm $(REBAR)

# dializer

build-plt:
	@$(DIALYZER) --build_plt --output_plt .$(PROJECT).plt \
		--apps erts kernel stdlib -r deps

dialyze:
	@$(DIALYZER) -pa deps/*/ebin --src src --plt .$(PROJECT).plt --no_native \
		-Werror_handling -Wrace_conditions -Wunmatched_returns


text:
/**
 * @flow
 */

import type A from "./A.js";
import type {Foo, Bar as Baz} from "./A.js";

type duck = {
  quack: () => string;
}

// These string types should confict with the imported types
var A: string = "Hello";
var Foo: string = "Goodbye";
var Baz: string = "Go away please";

// This string type should conflict with the typedef
var duck: string = "quack";


text:
package com.tlear.trise.interactions;

public class NoAction implements Action {

}


text:
            <?php _e('Revision Number', HKM_LANGUAGE_PACK); ?>
            <?php _e('Submission Time', HKM_LANGUAGE_PACK); ?>

            <?php _e('Revision Number', HKM_LANGUAGE_PACK); ?>
            <?php _e('Submission Time', HKM_LANGUAGE_PACK); ?>


text:
package org.apache.velocity.tools.view.jsp.jspimpl;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;

import java.io.IOException;
import java.io.Writer;

import org.junit.Before;
import org.junit.Test;

/**
 * Tests {@link JspWriterImpl}.
 *
 */
public class JspWriterImplTest
{

    private Writer writer;

    private JspWriterImpl jspWriter;

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception
    {
        writer = createMock(Writer.class);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#write(int)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testWriteInt() throws IOException
    {
        writer.write(10);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.write(10);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#write(char[])}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testWriteCharArray() throws IOException
    {
        writer.write(aryEq("hello".toCharArray()), eq(0), eq(5));

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.write("hello".toCharArray());
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#write(char[], int, int)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testWriteCharArrayIntInt() throws IOException
    {
        writer.write(aryEq("hello".toCharArray()), eq(2), eq(3));

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.write("hello".toCharArray(), 2, 3);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#flush()}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testFlush() throws IOException
    {
        writer.flush();

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.flush();
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#close()}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testClose() throws IOException
    {
        writer.close();

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.close();
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#newLine()}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testNewLine() throws IOException
    {
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.newLine();
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#print(boolean)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintBoolean() throws IOException
    {
        writer.write("true", 0, 4);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.print(true);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#print(char)}.
     * @throws IOException
     */
    @Test
    public void testPrintChar() throws IOException
    {
        writer.write("x", 0, 1);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.print('x');
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#print(int)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintInt() throws IOException
    {
        writer.write("152", 0, 3);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.print(152);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#print(long)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintLong() throws IOException
    {
        writer.write("152", 0, 3);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.print(152l);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#print(float)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintFloat() throws IOException
    {
        writer.write("0.5", 0, 3);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.print(0.5f);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#print(double)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintDouble() throws IOException
    {
        writer.write("0.5", 0, 3);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.print(0.5d);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#print(char[])}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintCharArray() throws IOException
    {
        writer.write(aryEq("hello".toCharArray()), eq(0), eq(5));

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.print("hello".toCharArray());
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println()}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintln() throws IOException
    {
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println();
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println(boolean)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintlnBoolean() throws IOException
    {
        writer.write("true", 0, 4);
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println(true);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println(char)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintlnChar() throws IOException
    {
        writer.write("x", 0, 1);
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println('x');
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println(int)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintlnInt() throws IOException
    {
        writer.write("152", 0, 3);
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println(152);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println(long)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintlnLong() throws IOException
    {
        writer.write("152", 0, 3);
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println(152l);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println(float)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintlnFloat() throws IOException
    {
        writer.write("0.5", 0, 3);
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println(0.5f);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println(double)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintlnDouble() throws IOException
    {
        writer.write("0.5", 0, 3);
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println(0.5d);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println(char[])}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintlnCharArray() throws IOException
    {
        writer.write(aryEq("hello".toCharArray()), eq(0), eq(5));
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println("hello".toCharArray());
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#clear()}.
     * @throws IOException If something goes wrong.
     */
    @Test(expected = IllegalStateException.class)
    public void testClear() throws IOException
    {
        jspWriter = new JspWriterImpl(writer);
        jspWriter.clear();
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#clearBuffer()}.
     * @throws IOException If something goes wrong.
     */
    @Test(expected = IllegalStateException.class)
    public void testClearBuffer() throws IOException
    {
        jspWriter = new JspWriterImpl(writer);
        jspWriter.clearBuffer();
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#getRemaining()}.
     */
    @Test
    public void testGetRemaining()
    {
        jspWriter = new JspWriterImpl(writer);
        assertEquals(0, jspWriter.getRemaining());
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#write(java.lang.String, int, int)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testWriteStringIntInt() throws IOException
    {
        writer.write("hello", 0, 3);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.write("hello", 0, 3);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#write(java.lang.String)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testWriteString() throws IOException
    {
        writer.write("hello", 0, 5);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.write("hello");
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#print(java.lang.String)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintString() throws IOException
    {
        writer.write("hello", 0, 5);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.print("hello");
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#print(java.lang.Object)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintObject() throws IOException
    {
        writer.write("null", 0, 4);

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.print((Object) null);
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println(java.lang.String)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintlnString() throws IOException
    {
        writer.write("hello", 0, 5);
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println("hello");
        verify(writer);
    }

    /**
     * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspWriterImpl#println(java.lang.Object)}.
     * @throws IOException If something goes wrong.
     */
    @Test
    public void testPrintlnObject() throws IOException
    {
        writer.write("null", 0, 4);
        writer.write(JspWriterImpl.lineSeparator, 0, JspWriterImpl.lineSeparator.length());

        replay(writer);
        jspWriter = new JspWriterImpl(writer);
        jspWriter.println((Object) null);
        verify(writer);
    }

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.xzy.android.fastvalueholdersample.MainActivity" >

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layoutAnimation="@anim/list_animation"
        >
    </ListView>

</RelativeLayout>


text:
require 'rspec'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'rcsv'


text:
package com.andrewkroh.cisco.xmlservices;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

/**
 * JAX-RS resource that hosts {@link XmlPushCallback}s as sub-resources.
 *
 * @author akroh
 */
@ApplicationScoped
@Path("/callback")
public class XmlPushCallbackRestResource
{
    /**
     * {@link XmlPushCallbackManager} that contains the {@link XmlPushCallback}
     * objects.
     */
    @Inject
    private XmlPushCallbackManager manager;

    /**
     * Gets the callback resource by its callbackId.
     *
     * @param callbackId
     *            callback ID assigned to the {@link XmlPushCallback} when it
     *            was registered
     * @return {@link XmlPushCallback} with the given callback ID, or
     *         {@code null} if one is not registered with that ID
     */
    @Path("/{id}")
    public XmlPushCallback getCallback(@PathParam("id") String callbackId)
    {
        return manager.getCallback(callbackId);
    }
}


text:
package jpower.core.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Indicates that this class is in Beta Testing
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Beta {
}


text:
namespace clang {
namespace tidy {
namespace android {

/// dup() is better to be replaced by fcntl(), which has close-on-exec flag.
/// Find the usage of dup() and redirect user to use fcntl().
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-dup.html
class CloexecDupCheck : public CloexecCheck {
public:
  CloexecDupCheck(StringRef Name, ClangTidyContext *Context)
      : CloexecCheck(Name, Context) {}
  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};

} // namespace android
} // namespace tidy
} // namespace clang

#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_DUP_H


text:
module Saml
  module Elements
    class AttributeStatement
      include Saml::Base
      include Saml::AttributeFetcher

      tag 'AttributeStatement'
      register_namespace 'saml', Saml::SAML_NAMESPACE
      namespace 'saml'

      has_many :attributes, Saml::Elements::Attribute
      has_many :encrypted_attributes, Saml::Elements::EncryptedAttribute

      def attribute
        warn '[DEPRECATED] please use #attributes'
        attributes
      end

      def attribute=(attributes)
        warn '[DEPRECATED] please use #attributes='
        self.attributes = attributes
      end
    end
  end
end


text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed 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.

import { Component, Injector } from '@angular/core';
import { ModalController } from 'ionic-angular';
import { CoreAppProvider } from '@providers/app';
import { CoreCourseProvider } from '@core/course/providers/course';
import { CoreCourseModuleMainResourceComponent } from '@core/course/classes/main-resource-component';
import { AddonModImscpProvider } from '../../providers/imscp';
import { AddonModImscpPrefetchHandler } from '../../providers/prefetch-handler';

/**
 * Component that displays a IMSCP.
 */
@Component({
    selector: 'addon-mod-imscp-index',
    templateUrl: 'addon-mod-imscp-index.html',
})
export class AddonModImscpIndexComponent extends CoreCourseModuleMainResourceComponent {
    component = AddonModImscpProvider.COMPONENT;

    items = [];
    currentItem: string;
    src = '';

    // Initialize empty previous/next to prevent showing arrows for an instant before they're hidden.
    previousItem = '';
    nextItem = '';

    constructor(injector: Injector, private imscpProvider: AddonModImscpProvider, private courseProvider: CoreCourseProvider,
            private appProvider: CoreAppProvider, private modalCtrl: ModalController,
            private imscpPrefetch: AddonModImscpPrefetchHandler) {
        super(injector);
    }

    /**
     * Component being initialized.
     */
    ngOnInit(): void {
        super.ngOnInit();

        this.loadContent().then(() => {
            this.imscpProvider.logView(this.module.instance, this.module.name).then(() => {
                this.courseProvider.checkModuleCompletion(this.courseId, this.module.completiondata);
            }).catch(() => {
                // Ignore errors.
            });
        });
    }

    /**
     * Perform the invalidate content function.
     *
     * @return {Promise<any>} Resolved when done.
     */
    protected invalidateContent(): Promise<any> {
        return this.imscpProvider.invalidateContent(this.module.id, this.courseId);
    }

    /**
     * Download imscp contents.
     *
     * @param  {boolean} [refresh] Whether we're refreshing data.
     * @return {Promise<any>} Promise resolved when done.
     */
    protected fetchContent(refresh?: boolean): Promise<any> {
        let downloadFailed = false;
        const promises = [];

        promises.push(this.imscpProvider.getImscp(this.courseId, this.module.id).then((imscp) => {
            this.description = imscp.intro || imscp.description;
            this.dataRetrieved.emit(imscp);
        }));

        promises.push(this.imscpPrefetch.download(this.module, this.courseId).catch(() => {
            // Mark download as failed but go on since the main files could have been downloaded.
            downloadFailed = true;

            return this.courseProvider.loadModuleContents(this.module, this.courseId).catch((error) => {
                // Error getting module contents, fail.
                this.domUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true);

                return Promise.reject(null);
            });
        }));

        return Promise.all(promises).then(() => {
            this.items = this.imscpProvider.createItemList(this.module.contents);
            if (this.items.length && typeof this.currentItem == 'undefined') {
                this.currentItem = this.items[0].href;
            }

            return this.loadItem(this.currentItem).catch((error) => {
                this.domUtils.showErrorModalDefault(error, 'addon.mod_imscp.deploymenterror', true);

                return Promise.reject(null);
            });
        }).then(() => {
            if (downloadFailed && this.appProvider.isOnline()) {
                // We could load the main file but the download failed. Show error message.
                this.domUtils.showErrorModal('core.errordownloadingsomefiles', true);
            }

            // All data obtained, now fill the context menu.
            this.fillContextMenu(refresh);
        });
    }

    /**
     * Loads an item.
     *
     * @param  {string} itemId Item ID.
     * @return {Promise<any>} Promise resolved when done.
     */
    loadItem(itemId: string): Promise<any> {
        return this.imscpProvider.getIframeSrc(this.module, itemId).then((src) => {
            this.currentItem = itemId;
            this.previousItem = this.imscpProvider.getPreviousItem(this.items, itemId);
            this.nextItem = this.imscpProvider.getNextItem(this.items, itemId);

            if (this.src && src == this.src) {
                // Re-loading same page. Set it to empty and then re-set the src in the next digest so it detects it has changed.
                this.src = '';
                setTimeout(() => {
                    this.src = src;
                });
            } else {
                this.src = src;
            }
        });
    }

    /**
     * Show the TOC.
     *
     * @param {MouseEvent} event Event.
     */
    showToc(event: MouseEvent): void {
        // Create the toc modal.
        const modal =  this.modalCtrl.create('AddonModImscpTocPage', {
            items: this.items,
            selected: this.currentItem
        }, { cssClass: 'core-modal-lateral',
            showBackdrop: true,
            enableBackdropDismiss: true,
            enterAnimation: 'core-modal-lateral-transition',
            leaveAnimation: 'core-modal-lateral-transition' });

        modal.onDidDismiss((itemId) => {
            if (itemId) {
                this.loadItem(itemId);
            }
        });

        modal.present({
            ev: event
        });
    }
}


text:
<?php

namespace GrumPHP\Configuration\Compiler;

use GrumPHP\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class TaskCompilerPass
 *
 * @package GrumPHP\Configuration\Compiler
 */
class TaskCompilerPass implements CompilerPassInterface
{

    const TAG_GRUMPHP_TASK = 'grumphp.task';

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $definition = $container->findDefinition('task_runner');
        $taggedServices = $container->findTaggedServiceIds(self::TAG_GRUMPHP_TASK);
        $configuration = $container->getParameter('tasks');

        $tasksRegistered = array();
        $tasksMetadata = array();
        $tasksConfiguration = array();
        foreach ($taggedServices as $id => $tags) {
            $taskTag = $this->getTaskTag($tags);
            $configKey = $taskTag['config'];
            if (in_array($configKey, $tasksRegistered)) {
                throw new RuntimeException(
                    sprintf('The name of a task should be unique. Duplicate found: %s', $configKey)
                );
            }

            $tasksRegistered[] = $configKey;
            if (!array_key_exists($configKey, $configuration)) {
                continue;
            }

            // Load configuration and metadata:
            $taskConfig = is_array($configuration[$configKey]) ? $configuration[$configKey] : array();
            $tasksMetadata[$configKey] = $this->parseTaskMetadata($taskConfig);

            // The metadata can't be part of the actual configuration.
            // This will throw exceptions during options resolving.
            unset($taskConfig['metadata']);
            $tasksConfiguration[$configKey] = $taskConfig;

            // Add the task to the task runner:
            $definition->addMethodCall('addTask', array(new Reference($id)));
        }

        sort($tasksRegistered);

        $container->setParameter('grumphp.tasks.registered', $tasksRegistered);
        $container->setParameter('grumphp.tasks.configuration', $tasksConfiguration);
        $container->setParameter('grumphp.tasks.metadata', $tasksMetadata);
    }

    /**
     * @param array $tags
     *
     * @return array
     */
    private function getTaskTag(array $tags)
    {
        $resolver = new OptionsResolver();
        $resolver->setRequired(array('config'));

        return $resolver->resolve(current($tags));
    }

    /**
     * @param $configuration
     *
     * @return array
     */
    private function parseTaskMetadata($configuration)
    {
        $resolver = new OptionsResolver();
        $resolver->setDefaults(array(
            'priority' => 0,
            'blocking' => true,
        ));

        $metadata = isset($configuration['metadata']) ? $configuration['metadata'] : array();

        return $resolver->resolve($metadata);
    }
}


text:
package com.bzu.yhd.pocketcampus.widget;

import com.bzu.yhd.pocketcampus.BuildConfig;
import com.bzu.yhd.pocketcampus.base.BaseApplication;
import com.bzu.yhd.pocketcampus.base.Config;
import com.bzu.yhd.pocketcampus.bottomnav.home.weather.domain.CityORM;
import com.bzu.yhd.pocketcampus.widget.utils.PLog;
import com.bzu.yhd.pocketcampus.widget.utils.RxUtils;
import com.bzu.yhd.pocketcampus.widget.utils.SimpleSubscriber;
import com.litesuits.orm.LiteOrm;

import rx.Observable;

/**
 * Created by HugoXie on 16/7/24.
 *
 * Email: Hugo3641@gamil.com
 * GitHub: https://github.com/xcc3641
 * Info:
 */
public class OrmLite {

    static LiteOrm sLiteOrm;

    public static LiteOrm getInstance() {
        getOrmHolder();
        return sLiteOrm;
    }

    private static OrmLite getOrmHolder() {
        return OrmHolder.sInstance;
    }

    private OrmLite() {
        if (sLiteOrm == null) {
            sLiteOrm = LiteOrm.newSingleInstance(BaseApplication.getAppContext(), Config.ORM_NAME);

        }
        sLiteOrm.setDebugged(BuildConfig.DEBUG);
    }

    private static class OrmHolder {
        private static final OrmLite sInstance = new OrmLite();
    }

    public static <T> void OrmTest(Class<T> t) {
        Observable.from(getInstance().query(t))
            .compose(RxUtils.rxSchedulerHelper())
            .subscribe(new SimpleSubscriber<T>() {
                @Override
                public void onNext(T t) {
                    if (t instanceof CityORM) {
                        PLog.w(((CityORM) t).getName());
                    }
                }
            });
    }
}


text:
package ee.ria.xroad.common.messagelog;

import lombok.Value;

import java.io.Serializable;
import java.util.Date;

/**
 * Message for finding a log record for a given message Query Id, start and end time.
 */
@Value
public class FindByQueryId implements Serializable {

    private final String queryId;
    private final Date startTime;
    private final Date endTime;
}


text:
#region License
//   Copyright 2015 Kastellanos Nikolaos
//
//   Licensed 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.
#endregion

namespace tainicom.ProtonType.Framework.ViewModels
{
    public class ToolViewModel : PaneViewModel
    {
        protected readonly object Model;
        public string Name { get; private set; }

        private bool _isVisible = true;
        public bool IsVisible
        {
            get { return _isVisible; }
            set
            {
                if (_isVisible != value)
                {
                    _isVisible = value;
                    RaisePropertyChanged(()=>IsVisible);
                }
            }
        }

        public ToolViewModel(object model, string name)
        {
            this.Model = model;
            this.Name = name;
            this.Title = name;
        }
    }
}


text:
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <link href="/feed.xml" type="application/rss+xml" rel="alternate" title="Sitewide RSS Feed">

  <title>{% if page.title %}{{ page.title | escape }}{% else %}{{ site.title | escape }}{% endif %}</title>

  <link href="/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/css/fontello.css">
  <link rel="stylesheet" href="/css/pygments.css">
  <link rel="stylesheet" href="/css/style.css">
</head>


text:
import unittest
try:
    import submission
except ImportError:
    pass

class Test1(unittest.TestCase):

    def test_passes(self):
        """This test should pass"""
        self.assertTrue(submission.return_true())

    def test_fails(self):
        """This test should fail"""
        self.assertTrue(submission.return_false())

class Test2(unittest.TestCase):

    def test_fails_and_outputs_json(self):
        """This test should fail and print json"""
        self.fail(submission.return_json())

if __name__ == '__main__':
    unittest.main()


text:
class WXDLLIMPEXP_BASE wxSingleInstanceChecker
{
public:
    // default ctor, use Create() after it
    wxSingleInstanceChecker() { Init(); }

    // like Create() but no error checking (dangerous!)
    wxSingleInstanceChecker(const wxString& name,
                            const wxString& path = wxEmptyString)
    {
        Init();
        Create(name, path);
    }

    // notice that calling Create() is optional now, if you don't do it before
    // calling IsAnotherRunning(), CreateDefault() is used automatically
    //
    // name it is used as the mutex name under Win32 and the lock file name
    // under Unix so it should be as unique as possible and must be non-empty
    //
    // path is optional and is ignored under Win32 and used as the directory to
    // create the lock file in under Unix (default is wxGetHomeDir())
    //
    // returns false if initialization failed, it doesn't mean that another
    // instance is running - use IsAnotherRunning() to check it
    bool Create(const wxString& name, const wxString& path = wxEmptyString);

    // use the default name, which is a combination of wxTheApp->GetAppName()
    // and wxGetUserId() for mutex/lock file
    //
    // this is called implicitly by IsAnotherRunning() if the checker hadn't
    // been created until then
    bool CreateDefault()
    {
        wxCHECK_MSG( wxTheApp, false, "must have application instance" );
        return Create(wxTheApp->GetAppName() + '-' + wxGetUserId());
    }

    // is another copy of this program already running?
    bool IsAnotherRunning() const
    {
        if ( !m_impl )
        {
            if ( !const_cast<wxSingleInstanceChecker *>(this)->CreateDefault() )
            {
                // if creation failed, return false as it's better to not
                // prevent this instance from starting up if there is an error
                return false;
            }
        }

        return DoIsAnotherRunning();
    }

    // dtor is not virtual, this class is not meant to be used polymorphically
    ~wxSingleInstanceChecker();

private:
    // common part of all ctors
    void Init() { m_impl = NULL; }

    // do check if another instance is running, called only if m_impl != NULL
    bool DoIsAnotherRunning() const;

    // the implementation details (platform specific)
    class WXDLLIMPEXP_FWD_BASE wxSingleInstanceCheckerImpl *m_impl;

    wxDECLARE_NO_COPY_CLASS(wxSingleInstanceChecker);
};

#endif // wxUSE_SNGLINST_CHECKER

#endif // _WX_SNGLINST_H_


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsUnicharBuffer_h__
#define nsUnicharBuffer_h__

#include "nsIUnicharBuffer.h"
#include "mozilla/Attributes.h"

class UnicharBufferImpl MOZ_FINAL : public nsIUnicharBuffer {
public:
  UnicharBufferImpl();

  static NS_METHOD
  Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);

  NS_DECL_ISUPPORTS
  NS_IMETHOD Init(uint32_t aBufferSize);
  NS_IMETHOD_(int32_t) GetLength() const;
  NS_IMETHOD_(int32_t) GetBufferSize() const;
  NS_IMETHOD_(PRUnichar*) GetBuffer() const;
  NS_IMETHOD_(bool) Grow(int32_t aNewSize);

  PRUnichar* mBuffer;
  uint32_t mSpace;
  uint32_t mLength;

private:
  ~UnicharBufferImpl();
};

#endif // nsUnicharBuffer_h__