text:
package org.optaplanner.benchmark.config.blueprint;

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

import javax.xml.bind.annotation.XmlEnum;

import org.optaplanner.benchmark.config.SolverBenchmarkConfig;
import org.optaplanner.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
import org.optaplanner.core.config.constructionheuristic.ConstructionHeuristicType;
import org.optaplanner.core.config.localsearch.LocalSearchPhaseConfig;
import org.optaplanner.core.config.localsearch.LocalSearchType;
import org.optaplanner.core.config.phase.PhaseConfig;
import org.optaplanner.core.config.solver.SolverConfig;

@XmlEnum
public enum SolverBenchmarkBluePrintType {
    /*
     * Run the default {@link ConstructionHeuristicType} with and without the default {@link LocalSearchType}.
     */
    CONSTRUCTION_HEURISTIC_WITH_AND_WITHOUT_LOCAL_SEARCH,
    /**
     * Run every {@link ConstructionHeuristicType}.
     */
    EVERY_CONSTRUCTION_HEURISTIC_TYPE,
    /**
     * Run the default {@link ConstructionHeuristicType} with every {@link LocalSearchType}.
     */
    EVERY_LOCAL_SEARCH_TYPE,
    /**
     * Run every {@link ConstructionHeuristicType} with every {@link LocalSearchType}.
     */
    EVERY_CONSTRUCTION_HEURISTIC_TYPE_WITH_EVERY_LOCAL_SEARCH_TYPE;

    protected List<SolverBenchmarkConfig> buildSolverBenchmarkConfigList() {
        switch (this) {
            case CONSTRUCTION_HEURISTIC_WITH_AND_WITHOUT_LOCAL_SEARCH:
                return buildConstructionHeuristicWithAndWithoutLocalSearch();
            case EVERY_CONSTRUCTION_HEURISTIC_TYPE:
                return buildEveryConstructionHeuristicType();
            case EVERY_LOCAL_SEARCH_TYPE:
                return buildEveryLocalSearchType();
            case EVERY_CONSTRUCTION_HEURISTIC_TYPE_WITH_EVERY_LOCAL_SEARCH_TYPE:
                return buildEveryConstructionHeuristicTypeWithEveryLocalSearchType();
            default:
                throw new IllegalStateException("The solverBenchmarkBluePrintType ("
                        + this + ") is not implemented.");
        }
    }

    private List<SolverBenchmarkConfig> buildConstructionHeuristicWithAndWithoutLocalSearch() {
        List<SolverBenchmarkConfig> solverBenchmarkConfigList = new ArrayList<>(2);
        solverBenchmarkConfigList.add(buildSolverBenchmarkConfig(null, false, null));
        solverBenchmarkConfigList.add(buildSolverBenchmarkConfig(null, true, null));
        return solverBenchmarkConfigList;
    }

    private List<SolverBenchmarkConfig> buildEveryConstructionHeuristicType() {
        ConstructionHeuristicType[] chTypes = ConstructionHeuristicType.getBluePrintTypes();
        List<SolverBenchmarkConfig> solverBenchmarkConfigList = new ArrayList<>(chTypes.length);
        for (ConstructionHeuristicType chType : chTypes) {
            solverBenchmarkConfigList.add(buildSolverBenchmarkConfig(chType, false, null));
        }
        return solverBenchmarkConfigList;
    }

    private List<SolverBenchmarkConfig> buildEveryLocalSearchType() {
        LocalSearchType[] lsTypes = LocalSearchType.getBluePrintTypes();
        List<SolverBenchmarkConfig> solverBenchmarkConfigList = new ArrayList<>(lsTypes.length);
        for (LocalSearchType lsType : lsTypes) {
            solverBenchmarkConfigList.add(buildSolverBenchmarkConfig(null, true, lsType));
        }
        return solverBenchmarkConfigList;
    }

    private List<SolverBenchmarkConfig> buildEveryConstructionHeuristicTypeWithEveryLocalSearchType() {
        ConstructionHeuristicType[] chTypes = ConstructionHeuristicType.getBluePrintTypes();
        LocalSearchType[] lsTypes = LocalSearchType.getBluePrintTypes();
        List<SolverBenchmarkConfig> solverBenchmarkConfigList = new ArrayList<>(
                chTypes.length * lsTypes.length);
        for (ConstructionHeuristicType chType : chTypes) {
            for (LocalSearchType lsType : lsTypes) {
                solverBenchmarkConfigList.add(buildSolverBenchmarkConfig(chType, true, lsType));
            }
        }
        return solverBenchmarkConfigList;
    }

    protected SolverBenchmarkConfig buildSolverBenchmarkConfig(ConstructionHeuristicType constructionHeuristicType,
            boolean localSearchEnabled, LocalSearchType localSearchType) {
        SolverBenchmarkConfig solverBenchmarkConfig = new SolverBenchmarkConfig();
        String constructionHeuristicName = constructionHeuristicType == null
                ? "Construction Heuristic"
                : constructionHeuristicType.name();
        String name;
        if (!localSearchEnabled) {
            name = constructionHeuristicName;
        } else {
            String localSearchName = localSearchType == null
                    ? "Local Search"
                    : localSearchType.name();
            name = constructionHeuristicType == null ? localSearchName
                    : constructionHeuristicName + " - " + localSearchName;
        }
        solverBenchmarkConfig.setName(name);
        SolverConfig solverConfig = new SolverConfig();
        List<PhaseConfig> phaseConfigList = new ArrayList<>(2);
        ConstructionHeuristicPhaseConfig constructionHeuristicPhaseConfig = new ConstructionHeuristicPhaseConfig();
        if (constructionHeuristicType != null) {
            constructionHeuristicPhaseConfig.setConstructionHeuristicType(constructionHeuristicType);
        }
        phaseConfigList.add(constructionHeuristicPhaseConfig);
        if (localSearchEnabled) {
            LocalSearchPhaseConfig localSearchPhaseConfig = new LocalSearchPhaseConfig();
            if (localSearchType != null) {
                localSearchPhaseConfig.setLocalSearchType(localSearchType);
            }
            phaseConfigList.add(localSearchPhaseConfig);
        }
        solverConfig.setPhaseConfigList(phaseConfigList);
        solverBenchmarkConfig.setSolverConfig(solverConfig);
        return solverBenchmarkConfig;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2015 Cognitive Medical Systems, Inc (http://www.cognitivemedciine.com).

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.
-->

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="FulfillmentServiceEngine" name="FulfillmentServiceEngine"
		class="org.socraticgrid.hl7.services.orders.engines.fulfillment.FulfillmentServiceEngine">
		<property name="endpoint" value="http://172.31.5.68:8080/OrderFulfillment/orderfulfillmentclient"/>
	</bean>
</beans>

redpajama_set_name: RedPajamaGithub


text:
<?php

defined('_JEXEC') or die;

/**
 * Model class to manage postinstall messages
 *
 * @since  3.2
 */
class PostinstallModelMessages extends FOFModel
{
	/**
	 * Builds the SELECT query
	 *
	 * @param   boolean  $overrideLimits  Are we requested to override the set limits?
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   3.2
	 */
	public function buildQuery($overrideLimits = false)
	{
		$query = parent::buildQuery($overrideLimits);

		$db = $this->getDbo();

		// Add a forced extension filtering to the list
		$eid = $this->getState('eid', 700);
		$query->where($db->qn('extension_id') . ' = ' . $db->q($eid));

		// Force filter only enabled messages
		$published = $this->getState('published', 1, 'int');
		$query->where($db->qn('enabled') . ' = ' . $db->q($published));

		return $query;
	}

	/**
	 * Returns the name of an extension, as registered in the #__extensions table
	 *
	 * @param   integer  $eid  The extension ID
	 *
	 * @return  string  The extension name
	 *
	 * @since   3.2
	 */
	public function getExtensionName($eid)
	{
		// Load the extension's information from the database
		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->select(array('name', 'element', 'client_id'))
			->from($db->qn('#__extensions'))
			->where($db->qn('extension_id') . ' = ' . $db->q((int) $eid));

		$db->setQuery($query, 0, 1);

		$extension = $db->loadObject();

		if (!is_object($extension))
		{
			return '';
		}

		// Load language files
		$basePath = JPATH_ADMINISTRATOR;

		if ($extension->client_id == 0)
		{
			$basePath = JPATH_SITE;
		}

		$lang = JFactory::getLanguage();
		$lang->load($extension->element, $basePath);

		// Return the localised name
		return JText::_($extension->name);
	}

	/**
	 * Resets all messages for an extension
	 *
	 * @param   integer  $eid  The extension ID whose messages we'll reset
	 *
	 * @return  mixed  False if we fail, a db cursor otherwise
	 *
	 * @since   3.2
	 */
	public function resetMessages($eid)
	{
		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->update($db->qn('#__postinstall_messages'))
			->set($db->qn('enabled') . ' = ' . $db->q(1))
			->where($db->qn('extension_id') . ' = ' . $db->q($eid));
		$db->setQuery($query);

		return $db->execute();
	}

	/**
	 * List post-processing. This is used to run the programmatic display
	 * conditions against each list item and decide if we have to show it or
	 * not.
	 *
	 * Do note that this a core method of the RAD Layer which operates directly
	 * on the list it's being fed. A little touch of modern magic.
	 *
	 * @param   array  &$resultArray  A list of items to process
	 *
	 * @return  void
	 *
	 * @since   3.2
	 */
	protected function onProcessList(&$resultArray)
	{
		$unset_keys          = array();
		$language_extensions = array();

		foreach ($resultArray as $key => $item)
		{
			// Filter out messages based on dynamically loaded programmatic conditions.
			if (!empty($item->condition_file) && !empty($item->condition_method))
			{
				jimport('joomla.filesystem.file');

				$file = FOFTemplateUtils::parsePath($item->condition_file, true);

				if (JFile::exists($file))
				{
					require_once $file;

					$result = call_user_func($item->condition_method);

					if ($result === false)
					{
						$unset_keys[] = $key;
					}
				}
			}

			// Load the necessary language files.
			if (!empty($item->language_extension))
			{
				$hash = $item->language_client_id . '-' . $item->language_extension;

				if (!in_array($hash, $language_extensions))
				{
					$language_extensions[] = $hash;
					JFactory::getLanguage()->load($item->language_extension, $item->language_client_id == 0 ? JPATH_SITE : JPATH_ADMINISTRATOR);
				}
			}
		}

		if (!empty($unset_keys))
		{
			foreach ($unset_keys as $key)
			{
				unset($resultArray[$key]);
			}
		}
	}

	/**
	 * Get the drop-down options for the list of component with post-installation messages
	 *
	 * @since 3.4
	 *
	 * @return  array  Compatible with JHtmlSelect::genericList
	 */
	public function getComponentOptions()
	{
		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->select('extension_id')
			->from($db->qn('#__postinstall_messages'))
			->group(array($db->qn('extension_id')));
		$db->setQuery($query);
		$extension_ids = $db->loadColumn();

		$options = array();

		foreach ($extension_ids as $eid)
		{
			$extension_name = $this->getExtensionName($eid);

			if ($extension_name == 'files_joomla')
			{
				$extension_name = JText::_('COM_POSTINSTALL_TITLE_JOOMLA');
			}

			$options[] = JHtml::_('select.option', $eid, $extension_name);
		}

		return $options;
	}

	/**
	 * Adds or updates a post-installation message (PIM) definition. You can use this in your post-installation script using this code:
	 *
	 * require_once JPATH_LIBRARIES . '/fof/include.php';
	 * FOFModel::getTmpInstance('Messages', 'PostinstallModel')->addPostInstallationMessage($options);
	 *
	 * The $options array contains the following mandatory keys:
	 *
	 * extension_id        The numeric ID of the extension this message is for (see the #__extensions table)
	 *
	 * type                One of message, link or action. Their meaning is:
	 *                         message  Informative message. The user can dismiss it.
	 *                         link     The action button links to a URL. The URL is defined in the action parameter.
	 *                         action   A PHP action takes place when the action button is clicked. You need to specify the action_file
	 *                                  (RAD path to the PHP file) and action (PHP function name) keys. See below for more information.
	 *
	 * title_key           The JText language key for the title of this PIM.
	 *                     Example: COM_FOOBAR_POSTINSTALL_MESSAGEONE_TITLE
	 *
	 * description_key     The JText language key for the main body (description) of this PIM
	 *                     Example: COM_FOOBAR_POSTINSTALL_MESSAGEONE_DESCRIPTION
	 *
	 * action_key		   The JText language key for the action button. Ignored and not required when type=message
	 * 					   Example: COM_FOOBAR_POSTINSTALL_MESSAGEONE_ACTION
	 *
	 * language_extension  The extension name which holds the language keys used above.
	 *                     For example, com_foobar, mod_something, plg_system_whatever, tpl_mytemplate
	 *
	 * language_client_id  Should we load the front-end (0) or back-end (1) language keys?
	 *
	 * version_introduced  Which was the version of your extension where this message appeared for the first time?
	 *                     Example: 3.2.1
	 *
	 * enabled             Must be 1 for this message to be enabled. If you omit it, it defaults to 1.
	 *
	 * condition_file      The RAD path to a PHP file containing a PHP function which determines whether this message should be shown to
	 *                     the user. @see FOFTemplateUtils::parsePath() for RAD path format. Joomla! will include this file before calling
	 *                     the condition_method.
	 *                     Example:   admin://components/com_foobar/helpers/postinstall.php
	 *
	 * condition_method    The name of a PHP function which will be used to determine whether to show this message to the user. This must be
	 *                     a simple PHP user function (not a class method, static method etc) which returns true to show the message and false
	 *                     to hide it. This function is defined in the condition_file.
	 *                     Example: com_foobar_postinstall_messageone_condition
	 *
	 * When type=message no additional keys are required.
	 *
	 * When type=link the following additional keys are required:
	 *
	 * action  The URL which will open when the user clicks on the PIM's action button
	 *         Example:    index.php?option=com_foobar&view=tools&task=installSampleData
	 *
	 * When type=action the following additional keys are required:
	 *
	 * action_file  The RAD path to a PHP file containing a PHP function which performs the action of this PIM. @see FOFTemplateUtils::parsePath()
	 *              for RAD path format. Joomla! will include this file before calling the function defined in the action key below.
	 *              Example:   admin://components/com_foobar/helpers/postinstall.php
	 *
	 * action       The name of a PHP function which will be used to run the action of this PIM. This must be a simple PHP user function
	 *              (not a class method, static method etc) which returns no result.
	 *              Example: com_foobar_postinstall_messageone_action
	 *
	 * @param   array  $options  See description
	 *
	 * @return  $this
	 *
	 * @throws  Exception
	 */
	public function addPostInstallationMessage(array $options)
	{
		// Make sure there are options set
		if (!is_array($options))
		{
			throw new Exception('Post-installation message definitions must be of type array', 500);
		}

		// Initialise array keys
		$defaultOptions = array(
			'extension_id'       => '',
			'type'               => '',
			'title_key'          => '',
			'description_key'    => '',
			'action_key'         => '',
			'language_extension' => '',
			'language_client_id' => '',
			'action_file'        => '',
			'action'             => '',
			'condition_file'     => '',
			'condition_method'   => '',
			'version_introduced' => '',
			'enabled'            => '1',
		);

		$options = array_merge($defaultOptions, $options);

		// Array normalisation. Removes array keys not belonging to a definition.
		$defaultKeys = array_keys($defaultOptions);
		$allKeys     = array_keys($options);
		$extraKeys   = array_diff($allKeys, $defaultKeys);

		if (!empty($extraKeys))
		{
			foreach ($extraKeys as $key)
			{
				unset($options[$key]);
			}
		}

		// Normalisation of integer values
		$options['extension_id']       = (int) $options['extension_id'];
		$options['language_client_id'] = (int) $options['language_client_id'];
		$options['enabled']            = (int) $options['enabled'];

		// Normalisation of 0/1 values
		foreach (array('language_client_id', 'enabled') as $key)
		{
			$options[$key] = $options[$key] ? 1 : 0;
		}

		// Make sure there's an extension_id
		if (!(int) $options['extension_id'])
		{
			throw new Exception('Post-installation message definitions need an extension_id', 500);
		}

		// Make sure there's a valid type
		if (!in_array($options['type'], array('message', 'link', 'action')))
		{
			throw new Exception('Post-installation message definitions need to declare a type of message, link or action', 500);
		}

		// Make sure there's a title key
		if (empty($options['title_key']))
		{
			throw new Exception('Post-installation message definitions need a title key', 500);
		}

		// Make sure there's a description key
		if (empty($options['description_key']))
		{
			throw new Exception('Post-installation message definitions need a description key', 500);
		}

		// If the type is anything other than message you need an action key
		if (($options['type'] != 'message') && empty($options['action_key']))
		{
			throw new Exception('Post-installation message definitions need an action key when they are of type "' . $options['type'] . '"', 500);
		}

		// You must specify the language extension
		if (empty($options['language_extension']))
		{
			throw new Exception('Post-installation message definitions need to specify which extension contains their language keys', 500);
		}

		// The action file and method are only required for the "action" type
		if ($options['type'] == 'action')
		{
			if (empty($options['action_file']))
			{
				throw new Exception('Post-installation message definitions need an action file when they are of type "action"', 500);
			}

			$file_path = FOFTemplateUtils::parsePath($options['action_file'], true);

			if (!@is_file($file_path))
			{
				throw new Exception('The action file ' . $options['action_file'] . ' of your post-installation message definition does not exist', 500);
			}

			if (empty($options['action']))
			{
				throw new Exception('Post-installation message definitions need an action (function name) when they are of type "action"', 500);
			}
		}

		if ($options['type'] == 'link')
		{
			if (empty($options['link']))
			{
				throw new Exception('Post-installation message definitions need an action (URL) when they are of type "link"', 500);
			}
		}

		// The condition file and method are only required when the type is not "message"
		if ($options['type'] != 'message')
		{
			if (empty($options['condition_file']))
			{
				throw new Exception('Post-installation message definitions need a condition file when they are of type "' . $options['type'] . '"', 500);
			}

			$file_path = FOFTemplateUtils::parsePath($options['condition_file'], true);

			if (!@is_file($file_path))
			{
				throw new Exception('The condition file ' . $options['condition_file'] . ' of your post-installation message definition does not exist', 500);
			}

			if (empty($options['condition_method']))
			{
				throw new Exception(
					'Post-installation message definitions need a condition method (function name) when they are of type "'
					. $options['type'] . '"',
					500
				);
			}
		}

		// Check if the definition exists
		$table     = $this->getTable();
		$tableName = $table->getTableName();

		$db    = $this->getDbo();
		$query = $db->getQuery(true)
			->select('*')
			->from($db->qn($tableName))
			->where($db->qn('extension_id') . ' = ' . $db->q($options['extension_id']))
			->where($db->qn('type') . ' = ' . $db->q($options['type']))
			->where($db->qn('title_key') . ' = ' . $db->q($options['title_key']));

		$existingRow = $db->setQuery($query)->loadAssoc();

		// Is the existing definition the same as the one we're trying to save?
		if (!empty($existingRow))
		{
			$same = true;

			foreach ($options as $k => $v)
			{
				if ($existingRow[$k] != $v)
				{
					$same = false;
					break;
				}
			}

			// Trying to add the same row as the existing one; quit
			if ($same)
			{
				return $this;
			}

			// Otherwise it's not the same row. Remove the old row before insert a new one.
			$query = $db->getQuery(true)
				->delete($db->qn($tableName))
				->where($db->q('extension_id') . ' = ' . $db->q($options['extension_id']))
				->where($db->q('type') . ' = ' . $db->q($options['type']))
				->where($db->q('title_key') . ' = ' . $db->q($options['title_key']));

			$db->setQuery($query)->execute();
		}

		// Insert the new row
		$options = (object) $options;
		$db->insertObject($tableName, $options);

		return $this;
	}
}


text:
+++
description = ""
title = "Get in Touch"
type = "contact"
+++


text:
"""Kubernetes classes for wrapping NetworkPolicy APIs."""
import abc
import random
import string
from typing import Dict, Optional

from kubernetes import client

from libcloudforensics.providers.kubernetes import base

class K8sNetworkPolicy(base.K8sNamespacedResource):
  """Class representing a Kubernetes NetworkPolicy, enabling API calls."""

  def Delete(self, cascade: bool = True) -> None:
    """Override of abstract method. The cascade parameter is ignored."""
    api = self._Api(client.NetworkingV1Api)
    api.delete_namespaced_network_policy(self.name, self.namespace)

  def Read(self) -> client.V1NetworkPolicy:
    """Override of abstract method."""
    api = self._Api(client.NetworkingV1Api)
    return api.read_namespaced_network_policy(self.name, self.namespace)

  def Patch(
      self,
      match_labels: Optional[Dict[str, str]] = None,
      not_match_labels: Optional[Dict[str, str]] = None) -> None:
    """Patches a Kubernetes NetworkPolicy to (not) match specified labels.

    The patched NetworkPolicy will have new fields in the podSelector's
    matchLabels and matchExpressions, so that it now has to match the labels
    given in match_labels, and not match the labels in not_match_labels.

    e.g. calling this method on a policy with an empty podSelector with args:

    ```
    match_labels={'app': 'nginx'}
    not_match_labels={'quarantine': 'true'}
    ```

    will result in a NetworkPolicy with the following spec YAML:

    ```
      spec:
        podSelector:
          matchExpressions:
          - key: quarantine
            operator: NotIn
            values:
            - "true"
          matchLabels:
            app: nginx
    ```

    Args:
      match_labels: The matchLabels to be added to the NetworkPolicy spec.
      not_match_labels: The labels to excluded from the NetworkPolicy. Each
          of these key-value pairs will result in a line in matchExpressions
          with the format {key: KEY, operator: NotIn, values: [VALUE]}.
    """
    api = self._Api(client.NetworkingV1Api)

    match_expressions = self.Read().spec.pod_selector.match_expressions or []
    if not_match_labels:
      match_expressions.extend(
          client.V1LabelSelectorRequirement(
              key=key, operator='NotIn', values=[value]) for key,
          value in not_match_labels.items())

    api.patch_namespaced_network_policy(
        self.name,
        self.namespace,
        {
            'spec':
                client.V1NetworkPolicySpec(
                    pod_selector=client.V1LabelSelector(
                        match_labels=match_labels,
                        match_expressions=match_expressions,
                    ))
        })

class K8sNetworkPolicyWithSpec(K8sNetworkPolicy, metaclass=abc.ABCMeta):
  """Class representing a Kubernetes NetworkPolicy with an underlying spec.

  This class additionally exposes creation API calls, as specification
  arguments can now be provided.
  """

  @property
  @abc.abstractmethod
  def _spec(self) -> client.V1NetworkPolicySpec:
    """The specification of this network policy to be used on creation."""

  @property
  def _metadata(self) -> client.V1ObjectMeta:
    """The metadata of this network policy to be used on creation."""
    return client.V1ObjectMeta(namespace=self.namespace, name=self.name)

  @property
  def _policy(self) -> client.V1NetworkPolicy:
    """The policy object of this network policy to be used on creation."""
    return client.V1NetworkPolicy(spec=self._spec, metadata=self._metadata)

  def Create(self) -> None:
    """Creates this network policy via the Kubernetes API."""
    api = self._Api(client.NetworkingV1Api)
    api.create_namespaced_network_policy(self.namespace, self._policy)

class K8sTargetedDenyAllNetworkPolicy(K8sNetworkPolicyWithSpec):
  """Class representing a deny-all NetworkPolicy.

  https://kubernetes.io/docs/concepts/services-networking/network-policies/#default-deny-all-ingress-and-all-egress-traffic  # pylint: disable=line-too-long

  Attributes:
    labels (Dict[str, str]): The matchLabels used by this NetworkPolicy.
  """

  def __init__(self, api_client: client.ApiClient, namespace: str) -> None:
    """Returns a deny-all Kubernetes NetworkPolicy.

    Args:
      api_client (ApiClient): The Kubernetes API client to the cluster.
      namespace (str): The namespace for this NetworkPolicy.
    """
    self._GenerateTag()
    name = 'cfu-netpol-{0:s}'.format(self._tag)
    super().__init__(api_client, name, namespace)

  def _GenerateTag(self) -> None:
    """Generates a random tag for this deny-all NetworkPolicy."""
    chars = random.choices(string.ascii_lowercase + string.digits, k=16)
    self._tag = ''.join(chars)

  @property
  def labels(self) -> Dict[str, str]:
    """The pod selector labels (matchLabels) of this policy."""
    return {'quarantineId': self._tag}

  @property
  def _spec(self) -> client.V1NetworkPolicySpec:
    """Override of abstract property."""
    return client.V1NetworkPolicySpec(
        pod_selector=client.V1LabelSelector(match_labels=self.labels),
        policy_types=[
            'Ingress',
            'Egress',
        ])


text:
ENV["TEST"] = "true"
require 'rubygems'
require 'bundler/setup'
require 'minitest/reporters'
require_relative '../lib/environment'

Dir["./app/**/*.rb"].each { |f| require f }
Dir["./lib/*.rb"].each { |f| require f }

reporter_options = { color: true }
Minitest::Reporters.use! [Minitest::Reporters::DefaultReporter.new(reporter_options)]

require 'minitest/autorun'
class Minitest::Test
  def setup
    Database.load_structure
    Database.execute("DELETE FROM readings;")
  end
end

def record_test_readings

    Database.transaction do
      sql = Database.prepare("INSERT INTO [readings] (id, sensor_id, pressure_value, time_stamp) VALUES (?, ?, ?, strftime('%Y-%m-%d %H:%M:%f'));")

      File.foreach('./lib/serial_files/test_serial_raw_80_seconds.txt').first(10).each do |line|
        temp_arr = line.split(':')
        sql.execute(1, temp_arr[0].hex + 1, temp_arr[1].hex + 1)
      end

      File.foreach('./lib/serial_files/test_serial_raw_15_seconds.txt').first(10).each do |line|
        temp_arr = line.split(':')
        sql.execute(2, temp_arr[0].hex + 1, temp_arr[1].hex + 1)
      end

    end

end

def main_menu
  "1. Start a session\n" +
  "2. Query a session\n" +
  "3. Exit\n"
end

def error
  "Please try again without any arguments...\n" +
  "Try \"./serial_parser_storage\"\n"
end


text:
package com.google.cloud.bqhiveloader

import org.apache.log4j.{LogManager, Logger}

trait Logging {
  @transient
  protected lazy val logger: Logger = LogManager.getLogger(this.getClass)
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>ORKShoulderRangeOfMotionStepViewController Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				ResearchKit

				ResearchKit

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Instance Methods">

		<option value="//api/name/result">- result</option>

	</optgroup>

</select>

ORKShoulderRangeOfMotionStepViewController Class Reference

	Inherits from
	ORKRangeOfMotionStepViewController : ORKActiveStepViewController : ORKStepViewController : UIViewController

	Declared in
	ORKShoulderRangeOfMotionStepViewController.h
ORKShoulderRangeOfMotionStepViewController.m

Overview

This class override its parent’s result because here
a flex result of 0 degrees would mean the device is at a 90 degree angle.

– result

The current state of the result. (read-only)

- (ORKResult *)result

Discussion

The task view controller uses this property to get the results for the
step, and to collate them into the task result.

The current step result and any subsidiary results representing data collected
so far are available in this property. You can detect significant changes to the result,
such as when the user enters a new answer, using the
stepViewControllerResultDidChange: delegate callback.

Subclasses must use this property to return the current results.
Subclasses may call super to obtain
a clean, empty result object appropriate for the step, to which they can
attach appropriate child results.

The implementations of this method in the ResearchKit framework currently create a new
result object on every call, so do not call this method unless it is
actually necessary.

Declared In

ORKStepViewController.h

Copyright © 2018 ResearchKit. All rights reserved. Updated: 2018-07-23

Generated by appledoc 2.2.1 (build 1334).


text:
  <meta charset="utf-8">
  <title>Panzer Test Suite</title>
  <link rel="stylesheet" href="../node_modules/mocha/mocha.css" />

Panzer Test Suite

Testing version 0.4.0, by Bemi Faison. Source files on github.com


text:
require "kanji/generate"
require "kanji/generators/abstract_generator"
require "dry/core/inflector"

module Kanji
  module Generators
    class Project < AbstractGenerator
      def initialize(app_name, options = {})
        @app_name = app_name
        super(underscored_project_name)
      end

      def populate_templates
        add_bin
        add_config
        add_db
        add_log
        add_spec
        add_app
        add_lib
        add_system
        add_config_files
      end

      private
      attr_reader :app_name

      def post_process_callback
        message = <<-TEXT
\n
You're now ready to start writing your Kanji app! Congratulations!
Because this is a data driven API application, you can't do much
with it until you create some types! Get started by using a generator:
`kanji g type User email:string`

This will generate a type and some mutations for you! Then you can:
`rake db:create && rake db:migrate`

After that open up `app/query_type.rb` and add a field to your root query
type:

field :users do
  type -> { types[Types::User[:graphql_type]] }
  description "All of the users for this app"

  resolve -> (obj, args, ctx) { Types::User[:repo].all }
end

Now open up `app/schema.rb` and uncomment the lines that add the
query and mutation types.

Start your server: `kanji s` and visit `localhost:3300/graphiql` and
start exploring!
        TEXT

        generator.processor.say(message, :cyan)
      end

      def destination
        underscored_project_name
      end

      def template_scope
        {
          underscored_project_name: underscored_project_name,
          camel_cased_app_name: camel_cased_app_name
        }
      end

      def underscored_project_name
        Dry::Core::Inflector.underscore(app_name)
      end

      def camel_cased_app_name
        Dry::Core::Inflector.camelize(underscored_project_name)
      end

      def add_bin
        add_template("bin/console.tt", "bin/console")
        add_template("bin/setup", "bin/setup")
      end

      def add_config
        add_template(".env.tt", ".env")
        add_template(".env.test.tt", ".env.test")
      end

      def add_db
        add_template("db/sample_data.rb", "db/sample_data.rb")
        add_template("db/seed.rb", "db/seed.rb")
        add_template(".keep", "db/migrate/.keep")
      end

      def add_app
        add_template("app/types.rb.tt", "app/types.rb")
        add_template("app/schema.rb.tt", "app/schema.rb")
        add_template("app/query_type.rb.tt", "app/query_type.rb")
        add_template("app/mutation_type.rb.tt", "app/mutation_type.rb")
        add_template("app/views/graphiql.html.erb", "app/views/graphiql.html.erb")
        add_template(".keep", "app/repositories/.keep")
        add_template(".keep", "app/types/.keep")
        add_template(".keep", "client/.keep")
      end

      def add_lib
        add_template(".keep", "lib/.keep")
      end

      def add_log
        add_template(".keep", "log/.keep")
      end

      def add_spec
        add_template(".rspec", ".rspec")

        # Base spec helpers
        add_template("spec/db_spec_helper.rb.tt", "spec/db_spec_helper.rb")
        add_template("spec/spec_helper.rb", "spec/spec_helper.rb")

        # DB support
        add_template("spec/support/db/factory.rb", "spec/support/db/factory.rb")
        add_template("spec/support/db/helpers.rb.tt", "spec/support/db/helpers.rb")
        add_template("spec/factories/example.rb", "spec/factories/example.rb")
      end

      def add_system
        add_system_lib
        add_system_boot
      end

      def add_system_lib
        add_template("system/project/container.rb.tt", "system/#{underscored_project_name}/container.rb")
        add_template("system/project/import.rb.tt", "system/#{underscored_project_name}/import.rb")
        add_template("system/project/settings.rb.tt", "system/#{underscored_project_name}/settings.rb")
        add_template("system/project/application.rb.tt", "system/#{underscored_project_name}/application.rb")
      end

      def add_system_boot
        add_template("system/boot.rb.tt", "system/boot.rb")
        add_template("system/boot/monitor.rb.tt", "system/boot/monitor.rb")
        add_template("system/boot/rom.rb.tt", "system/boot/rom.rb")
        add_template("system/boot/settings.rb.tt", "system/boot/settings.rb")
        add_template("system/boot/graph.rb.tt", "system/boot/graph.rb")
        add_template("system/boot/repos.rb.tt", "system/boot/repos.rb")
      end

      def add_config_files
        add_template(".gitignore.tt", ".gitignore")
        add_template("Gemfile", "Gemfile")
        add_template("Rakefile.tt", "Rakefile")
        add_template("config.ru.tt", "config.ru")
        add_template("README.md.tt", "README.md")
      end
    end
  end
end


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Plugins\Contents\Columns\Metrics;

use Piwik\DataTable\Row;
use Piwik\Metrics\Formatter;
use Piwik\Piwik;
use Piwik\Plugin\ProcessedMetric;

/**
 * The content interaction rate. Calculated as:
 *
 *     nb_interactions / nb_impressions
 *
 * nb_interactions & nb_impressions are calculated by the Contents archiver.
 */
class InteractionRate extends ProcessedMetric
{
    public function getName()
    {
        return 'interaction_rate';
    }

    public function getTranslatedName()
    {
        return Piwik::translate('Contents_InteractionRate');
    }

    public function compute(Row $row)
    {
        $interactions = $this->getMetric($row, 'nb_interactions');
        $impressions = $this->getMetric($row, 'nb_impressions');

        return Piwik::getQuotientSafe($interactions, $impressions, $precision = 4);
    }

    public function format($value, Formatter $formatter)
    {
        return $formatter->getPrettyPercentFromQuotient($value);
    }

    public function getDependentMetrics()
    {
        return array('nb_interactions', 'nb_impressions');
    }
}


text:
package io.circe.pointer.literal

import io.circe.pointer.Pointer
import scala.quoted._
import scala.language.`3.0`

private object PointerLiteralMacros {

  final def pointerImpl(sc: Expr[StringContext], argsExpr: Expr[Seq[Any]])(using q: Quotes): Expr[Pointer] = {
    import q.reflect.*
    val stringParts: Seq[String] = sc match {
      case '{ StringContext($parts: _*) } => parts.valueOrAbort
    }

    if (Pointer.parse(stringParts.mkString("X")).isRight) {
      val args = argsExpr match {
        case Varargs(argExprs) => argExprs
        case other             => report.error("Invalid arguments for pointer literal."); Nil
      }
      val input = args.zip(stringParts.tail).foldLeft(Expr(stringParts.head)) {
        case (acc, (a, p)) =>
          val pExpr = Expr(p)
          '{ $acc + $a.toString.replaceAll("~", "~0").replaceAll("/", "~1") + $pExpr }
      }

      '{
        _root_.io.circe.pointer.Pointer
          .parse($input)
          .asInstanceOf[_root_.scala.Right[_root_.scala.Nothing, _root_.io.circe.pointer.Pointer]]
          .value
      }
    } else {
      q.reflect.report.error(s"Invalid JSON Pointer in interpolated string")
      '{ null }
    }
  }
}


text:
set -u

DIVERGED=$(git merge-base --fork-point origin/master > /dev/null; echo $?)

if [[ "${DIVERGED}" == 0 ]]; then
  if [[ "${BUILDKITE_TAG}" == "" ]]; then
    if [[ "${BUILDKITE_BRANCH}" == "master" ]]; then
      CI_BYPASS=$(git diff --name-only HEAD~1 | sed -rn '/^(CODE_OF_CONDUCT\.md|CONTRIBUTING\.md|README\.md|SECURITY\.md|crowdin\.yml|\.all-contributorsrc|\.editorconfig|\.github\/.*|docs\/.*|examples\/.*)/!{q1}' && echo true || echo false)
    else
      CI_BYPASS=$(git diff --name-only `git merge-base --fork-point origin/master` | sed -rn '/^(CODE_OF_CONDUCT\.md|CONTRIBUTING\.md|README\.md|SECURITY\.md|crowdin\.yml|\.all-contributorsrc|\.editorconfig|\.github\/.*|docs\/.*|examples\/.*)/!{q1}' && echo true || echo false)
    fi
  else
    CI_BYPASS="false"
  fi
else
  CI_BYPASS="false"
fi

cat << EOF
env:
  CI_BYPASS: ${CI_BYPASS}

steps:
  - label: ":docker: Deploy Manifest"
    command: "authelia-scripts docker push-manifest"
    depends_on:
      - "unit-test"
    retry:
      manual:
        permit_on_passed: true
    agents:
      upload: "fast"
    if: build.env("CI_BYPASS") != "true"

  - label: ":github: Deploy Artifacts"
    command: "ghartifacts.sh"
    depends_on:
      - "unit-test"
      - "build-deb-package-amd64"
      - "build-deb-package-armhf"
      - "build-deb-package-arm64"
    retry:
      automatic: true
    agents:
      upload: "fast"
    key: "artifacts"
    if: build.tag != null

  - label: ":linux: Deploy AUR"
    command: ".buildkite/steps/aurpackages.sh | buildkite-agent pipeline upload"
    depends_on: ~
    if: build.tag != null && build.env("CI_BYPASS") != "true"

  - label: ":debian: :fedora: :ubuntu: Deploy APT"
    command: "aptdeploy.sh"
    depends_on:
      - "build-deb-package-amd64"
      - "build-deb-package-arm64"
      - "build-deb-package-armhf"
    agents:
      upload: "fast"
    if: build.tag != null

  - label: ":book: Deploy Documentation"
    command: "syncdoc.sh"
    depends_on: ~
    agents:
      upload: "fast"
    if: build.branch == "master"
EOF


text:
Canvas* MainWindow::canvas;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), _ui(new Ui::MainWindow)
{
    _ui->setupUi(this);

    canvas = new Canvas(this, _ui->frmCanvas->x(), _ui->frmCanvas->y(),
                        _ui->frmCanvas->width(), _ui->frmCanvas->height());

    _ui->lstLayers->setIconSize(QSize(75, 75));
    _ui->lstLayers->setResizeMode(QListWidget::Adjust);

    _ui->cbMode->addItem("None");
    _ui->cbMode->addItem("Alpha Blending");
    _ui->cbMode->addItem("Average Mode");
    _ui->cbMode->addItem("Multiply Mode");
    _ui->cbMode->addItem("Screen Mode");
    _ui->cbMode->addItem("Difference Mode");
    _ui->cbMode->addItem("Negation Mode");

    setAcceptDrops(true);

    _blendMode = BLEND_MODE_NONE;
}

MainWindow::~MainWindow()
{
    for (int i = 0; i < _ui->lstLayers->count(); ++i)
    {
        QListWidgetItem* item = _ui->lstLayers->item(i);
        Layer* layer = static_cast<Layer*>(_ui->lstLayers->itemWidget(item));
        if (layer != 0)
            delete layer->getImage();
    }
    delete _ui;
}

void MainWindow::loadAndAddImage(const QString& fileName)
{
    QImage* image = new QImage(fileName);
    if (image->isNull()) {
        delete image;
        return;
    }

    QListWidgetItem* widgetItem = new QListWidgetItem();
    widgetItem->setIcon(QIcon(fileName));
    _ui->lstLayers->addItem(widgetItem);

    Layer* layer = new Layer(image);
    widgetItem->setSizeHint(layer->sizeHint());
    _ui->lstLayers->setItemWidget(widgetItem, layer);

    canvas->update();
}

void MainWindow::dragEnterEvent(QDragEnterEvent* event)
{
    if (event->mimeData()->hasUrls())
        event->acceptProposedAction();
}

void MainWindow::dropEvent(QDropEvent* event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    for (int i = 0; i < urls.size(); i++)
        loadAndAddImage(urls.at(i).toLocalFile());
}

void MainWindow::paintEvent(QPaintEvent*)
{
    canvas->clear();

    for (int i = 0; i < _ui->lstLayers->count(); ++i)
    {
        QListWidgetItem* item = _ui->lstLayers->item(i);
        Layer* layer = static_cast<Layer*>(_ui->lstLayers->itemWidget(item));

        if (layer != 0 && layer->isVisible())
            canvas->drawImage(layer, _blendMode, (i == 0));
    }

   if (_blendMode != BLEND_MODE_NONE)
        canvas->draw();
}

void MainWindow::on_cbMode_currentIndexChanged(const QString& itemID)
{
    if      (itemID == "None")              _blendMode = BLEND_MODE_NONE;
    else if (itemID == "Alpha Blending")    _blendMode = BLEND_MODE_ALPHA_BLENDING;
    else if (itemID == "Average Mode")      _blendMode = BLEND_MODE_AVERAGE;
    else if (itemID == "Multiply Mode")     _blendMode = BLEND_MODE_MULTIPLY;
    else if (itemID == "Screen Mode")       _blendMode = BLEND_MODE_SCREEN;
    else if (itemID == "Difference Mode")   _blendMode = BLEND_MODE_DIFFERENCE;
    else if (itemID == "Negation Mode")     _blendMode = BLEND_MODE_NEGATION;

    canvas->update();
}

void MainWindow::on_btnUpArrow_clicked()
{
    QListWidget* list = _ui->lstLayers;

    int currentIndex =  list->currentRow();
    if (currentIndex < 1)
        return;

    QListWidgetItem* currentItem =  list->item(currentIndex);
    Layer* oldLayer = static_cast<Layer*>(list->itemWidget(currentItem));
    Layer* newLayer = new Layer(oldLayer->getImage(), oldLayer->isVisible(), oldLayer->getAlpha());

    list->removeItemWidget(currentItem);
    list->takeItem(currentIndex);
    list->insertItem(currentIndex - 1, currentItem);
    list->setCurrentRow(currentIndex - 1);
    list->setItemWidget(currentItem, newLayer);

    canvas->update();
}

void MainWindow::on_btnDownArrow_clicked()
{
    QListWidget* list = _ui->lstLayers;

    int currentIndex =  list->currentRow();
    if (currentIndex >= list->count() - 1)
        return;

    QListWidgetItem* currentItem =  list->item(currentIndex);
    Layer* oldLayer = static_cast<Layer*>(list->itemWidget(currentItem));
    Layer* newLayer = new Layer(oldLayer->getImage(), oldLayer->isVisible(), oldLayer->getAlpha());

    list->removeItemWidget(currentItem);
    list->takeItem(currentIndex);
    list->insertItem(currentIndex + 1, currentItem);
    list->setCurrentRow(currentIndex + 1);
    list->setItemWidget(currentItem, newLayer);

    canvas->update();
}

void MainWindow::on_btnRemove_clicked()
{
    QListWidget* list = _ui->lstLayers;
    int currentIndex =  list->currentRow();
    if (currentIndex < 0 || currentIndex >= list->count())
        return;

    list->takeItem(currentIndex);

    canvas->update();
}


text:
/*	$OpenBSD: vfs_vnops.c,v 1.20 1999/02/26 04:51:17 art Exp $	*/
/*	$NetBSD: vfs_vnops.c,v 1.20 1996/02/04 02:18:41 christos Exp $	*/

/*
 * Copyright (c) 1982, 1986, 1989, 1993
 *	The Regents of the University of California.  All rights reserved.
 * (c) UNIX System Laboratories, Inc.
 * All or some portions of this file are derived from material licensed
 * to the University of California by American Telephone and Telegraph
 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
 * the permission of UNIX System Laboratories, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)vfs_vnops.c	8.5 (Berkeley) 12/8/94
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/buf.h>
#include <sys/proc.h>
#include <sys/mount.h>
#include <sys/namei.h>
#include <sys/vnode.h>
#include <sys/ioctl.h>
#include <sys/tty.h>

#include <vm/vm.h>

#if defined(UVM)
#include <uvm/uvm_extern.h>
#endif

struct 	fileops vnops =
	{ vn_read, vn_write, vn_ioctl, vn_select, vn_closefile };

/*
 * Common code for vnode open operations.
 * Check permissions, and call the VOP_OPEN or VOP_CREATE routine.
 */
int
vn_open(ndp, fmode, cmode)
	register struct nameidata *ndp;
	int fmode, cmode;
{
	register struct vnode *vp;
	register struct proc *p = ndp->ni_cnd.cn_proc;
	register struct ucred *cred = p->p_ucred;
	struct vattr va;
	int error;

	if ((fmode & (FREAD|FWRITE)) == 0)
		return (EINVAL);
	if ((fmode & (O_TRUNC | FWRITE)) == O_TRUNC)
		return (EINVAL);
	if (fmode & O_CREAT) {
		ndp->ni_cnd.cn_nameiop = CREATE;
		ndp->ni_cnd.cn_flags = LOCKPARENT | LOCKLEAF;
		if (((fmode & O_EXCL) == 0) &&
		    ((fmode & FNOSYMLINK) == 0))
			ndp->ni_cnd.cn_flags |= FOLLOW;
		if ((error = namei(ndp)) != 0)
			return (error);

		if (ndp->ni_vp == NULL) {
			VATTR_NULL(&va);
			va.va_type = VREG;
			va.va_mode = cmode;
			VOP_LEASE(ndp->ni_dvp, p, cred, LEASE_WRITE);
			error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
					   &ndp->ni_cnd, &va);
			if (error)
				return (error);
			fmode &= ~O_TRUNC;
			vp = ndp->ni_vp;
		} else {
			VOP_ABORTOP(ndp->ni_dvp, &ndp->ni_cnd);
			if (ndp->ni_dvp == ndp->ni_vp)
				vrele(ndp->ni_dvp);
			else
				vput(ndp->ni_dvp);
			ndp->ni_dvp = NULL;
			vp = ndp->ni_vp;
			if (fmode & O_EXCL) {
				error = EEXIST;
				goto bad;
			}
			if ((ndp->ni_vp->v_type == VLNK) &
			    ((fmode & FNOSYMLINK) != 0)) {
				error = EFTYPE;
				goto bad;
			}

			fmode &= ~O_CREAT;
		}
	} else {
		ndp->ni_cnd.cn_nameiop = LOOKUP;
		ndp->ni_cnd.cn_flags = FOLLOW | LOCKLEAF;
		if ((error = namei(ndp)) != 0)
			return (error);
		vp = ndp->ni_vp;
	}
	if (vp->v_type == VSOCK) {
		error = EOPNOTSUPP;
		goto bad;
	}
	if ((fmode & O_CREAT) == 0) {
		if (fmode & FREAD) {
			if ((error = VOP_ACCESS(vp, VREAD, cred, p)) != 0)
				goto bad;
		}
		if (fmode & FWRITE) {
			if (vp->v_type == VDIR) {
				error = EISDIR;
				goto bad;
			}
			if ((error = vn_writechk(vp)) != 0 ||
			    (error = VOP_ACCESS(vp, VWRITE, cred, p)) != 0)
				goto bad;
		}
	}
	if (fmode & O_TRUNC) {
		VOP_UNLOCK(vp, 0, p);				/* XXX */
		VOP_LEASE(vp, p, cred, LEASE_WRITE);
		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, p);	/* XXX */
		VATTR_NULL(&va);
		va.va_size = 0;
		if ((error = VOP_SETATTR(vp, &va, cred, p)) != 0)
			goto bad;
	}
	if ((error = VOP_OPEN(vp, fmode, cred, p)) != 0)
		goto bad;
	if (fmode & FWRITE)
		vp->v_writecount++;
	return (0);
bad:
	vput(vp);
	return (error);
}

/*
 * Check for write permissions on the specified vnode.
 * Prototype text segments cannot be written.
 */
int
vn_writechk(vp)
	register struct vnode *vp;
{

	/*
	 * Disallow write attempts on read-only file systems;
	 * unless the file is a socket or a block or character
	 * device resident on the file system.
	 */
	if (vp->v_mount->mnt_flag & MNT_RDONLY) {
		switch (vp->v_type) {
		case VREG: case VDIR: case VLNK:
			return (EROFS);
		case VNON: case VCHR: case VSOCK:
		case VFIFO: case VBAD: case VBLK:
			break;
		}
	}
	/*
	 * If there's shared text associated with
	 * the vnode, try to free it up once.  If
	 * we fail, we can't allow writing.
	 */
#if defined(UVM)
	if ((vp->v_flag & VTEXT) && !uvm_vnp_uncache(vp))
		return (ETXTBSY);
#else
	if ((vp->v_flag & VTEXT) && !vnode_pager_uncache(vp))
		return (ETXTBSY);
#endif
	return (0);
}

/*
 * Vnode close call
 */
int
vn_close(vp, flags, cred, p)
	register struct vnode *vp;
	int flags;
	struct ucred *cred;
	struct proc *p;
{
	int error;

	if (flags & FWRITE)
		vp->v_writecount--;
	error = VOP_CLOSE(vp, flags, cred, p);
	vrele(vp);
	return (error);
}

/*
 * Package up an I/O request on a vnode into a uio and do it.
 */
int
vn_rdwr(rw, vp, base, len, offset, segflg, ioflg, cred, aresid, p)
	enum uio_rw rw;
	struct vnode *vp;
	caddr_t base;
	int len;
	off_t offset;
	enum uio_seg segflg;
	int ioflg;
	struct ucred *cred;
	size_t *aresid;
	struct proc *p;
{
	struct uio auio;
	struct iovec aiov;
	int error;

	if ((ioflg & IO_NODELOCKED) == 0)
		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, p);
	auio.uio_iov = &aiov;
	auio.uio_iovcnt = 1;
	aiov.iov_base = base;
	aiov.iov_len = len;
	auio.uio_resid = len;
	auio.uio_offset = offset;
	auio.uio_segflg = segflg;
	auio.uio_rw = rw;
	auio.uio_procp = p;
	if (rw == UIO_READ) {
		error = VOP_READ(vp, &auio, ioflg, cred);
	} else {
		error = VOP_WRITE(vp, &auio, ioflg, cred);
	}
	if (aresid)
		*aresid = auio.uio_resid;
	else
		if (auio.uio_resid && error == 0)
			error = EIO;
	if ((ioflg & IO_NODELOCKED) == 0)
		VOP_UNLOCK(vp, 0, p);
	return (error);
}

/*
 * File table vnode read routine.
 */
int
vn_read(fp, uio, cred)
	struct file *fp;
	struct uio *uio;
	struct ucred *cred;
{
	register struct vnode *vp = (struct vnode *)fp->f_data;
	int error = 0;
	size_t count;
	struct proc *p = uio->uio_procp;

	VOP_LEASE(vp, uio->uio_procp, cred, LEASE_READ);
	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, p);
	uio->uio_offset = fp->f_offset;
	count = uio->uio_resid;
	if (vp->v_type != VDIR)
		error = VOP_READ(vp, uio,
		    (fp->f_flag & FNONBLOCK) ? IO_NDELAY : 0, cred);
	fp->f_offset += count - uio->uio_resid;
	VOP_UNLOCK(vp, 0, p);
	return (error);
}

/*
 * File table vnode write routine.
 */
int
vn_write(fp, uio, cred)
	struct file *fp;
	struct uio *uio;
	struct ucred *cred;
{
	register struct vnode *vp = (struct vnode *)fp->f_data;
	struct proc *p = uio->uio_procp;
	int error, ioflag = IO_UNIT;
	size_t count;

	if (vp->v_type == VREG && (fp->f_flag & O_APPEND))
		ioflag |= IO_APPEND;
	if (fp->f_flag & FNONBLOCK)
		ioflag |= IO_NDELAY;
	if ((fp->f_flag & O_FSYNC) ||
	    (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS)))
		ioflag |= IO_SYNC;
	VOP_LEASE(vp, uio->uio_procp, cred, LEASE_WRITE);
	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, p);
	uio->uio_offset = fp->f_offset;
	count = uio->uio_resid;
	error = VOP_WRITE(vp, uio, ioflag, cred);
	if (ioflag & IO_APPEND)
		fp->f_offset = uio->uio_offset;
	else
		fp->f_offset += count - uio->uio_resid;
	VOP_UNLOCK(vp, 0, p);
	return (error);
}

/*
 * File table vnode stat routine.
 */
int
vn_stat(vp, sb, p)
	struct vnode *vp;
	register struct stat *sb;
	struct proc *p;
{
	struct vattr va;
	int error;
	u_short mode;

	error = VOP_GETATTR(vp, &va, p->p_ucred, p);
	if (error)
		return (error);
	/*
	 * Copy from vattr table
	 */
	sb->st_dev = va.va_fsid;
	sb->st_ino = va.va_fileid;
	mode = va.va_mode;
	switch (vp->v_type) {
	case VREG:
		mode |= S_IFREG;
		break;
	case VDIR:
		mode |= S_IFDIR;
		break;
	case VBLK:
		mode |= S_IFBLK;
		break;
	case VCHR:
		mode |= S_IFCHR;
		break;
	case VLNK:
		mode |= S_IFLNK;
		break;
	case VSOCK:
		mode |= S_IFSOCK;
		break;
	case VFIFO:
		mode |= S_IFIFO;
		break;
	default:
		return (EBADF);
	};
	sb->st_mode = mode;
	sb->st_nlink = va.va_nlink;
	sb->st_uid = va.va_uid;
	sb->st_gid = va.va_gid;
	sb->st_rdev = va.va_rdev;
	sb->st_size = va.va_size;
	sb->st_atimespec = va.va_atime;
	sb->st_mtimespec = va.va_mtime;
	sb->st_ctimespec = va.va_ctime;
	sb->st_blksize = va.va_blocksize;
	sb->st_flags = va.va_flags;
	sb->st_gen = va.va_gen;
	sb->st_blocks = va.va_bytes / S_BLKSIZE;
	return (0);
}

/*
 * File table vnode ioctl routine.
 */
int
vn_ioctl(fp, com, data, p)
	struct file *fp;
	u_long com;
	caddr_t data;
	struct proc *p;
{
	register struct vnode *vp = ((struct vnode *)fp->f_data);
	struct vattr vattr;
	int error;

	switch (vp->v_type) {

	case VREG:
	case VDIR:
		if (com == FIONREAD) {
			error = VOP_GETATTR(vp, &vattr, p->p_ucred, p);
			if (error)
				return (error);
			*(int *)data = vattr.va_size - fp->f_offset;
			return (0);
		}
		if (com == FIONBIO || com == FIOASYNC)	/* XXX */
			return (0);			/* XXX */
		/* fall into ... */

	default:
		return (ENOTTY);

	case VFIFO:
	case VCHR:
	case VBLK:
		error = VOP_IOCTL(vp, com, data, fp->f_flag, p->p_ucred, p);
		if (error == 0 && com == TIOCSCTTY) {
			if (p->p_session->s_ttyvp)
				vrele(p->p_session->s_ttyvp);
			p->p_session->s_ttyvp = vp;
			VREF(vp);
		}
		return (error);
	}
}

/*
 * File table vnode select routine.
 */
int
vn_select(fp, which, p)
	struct file *fp;
	int which;
	struct proc *p;
{

	return (VOP_SELECT(((struct vnode *)fp->f_data), which, fp->f_flag,
			   fp->f_cred, p));
}

/*
 * Check that the vnode is still valid, and if so
 * acquire requested lock.
 */
int
vn_lock(vp, flags, p)
	struct vnode *vp;
	int flags;
	struct proc *p;
{
	int error;

	do {
		if ((flags & LK_INTERLOCK) == 0)
			simple_lock(&vp->v_interlock);
		if (vp->v_flag & VXLOCK) {
			vp->v_flag |= VXWANT;
			simple_unlock(&vp->v_interlock);
			tsleep((caddr_t)vp, PINOD, "vn_lock", 0);
			error = ENOENT;
		} else {
			error = VOP_LOCK(vp, flags | LK_INTERLOCK | LK_CANRECURSE, p);
			if (error == 0)
				return (error);
		}
		flags &= ~LK_INTERLOCK;
	} while (flags & LK_RETRY);
	return (error);
}

/*
 * File table vnode close routine.
 */
int
vn_closefile(fp, p)
	struct file *fp;
	struct proc *p;
{

	return (vn_close(((struct vnode *)fp->f_data), fp->f_flag,
		fp->f_cred, p));
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Elaphomyces vulgaris var. granulatus Corda

### Remarks
null


text:
/*
 * 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.
 */
package com.facebook.presto.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import static com.google.common.collect.Maps.fromProperties;

public final class PropertiesUtil
{
    private PropertiesUtil() {}

    public static Map<String, String> loadProperties(File file)
            throws IOException
    {
        Properties properties = new Properties();
        try (InputStream in = new FileInputStream(file)) {
            properties.load(in);
        }
        return fromProperties(properties);
    }
}


text:
using System.Linq;
using DatenMeister.Core.EMOF.Implementation;
using DatenMeister.Core.EMOF.Interface.Common;
using DatenMeister.Core.EMOF.Interface.Reflection;
using DatenMeister.Core.Helper;
using DatenMeister.Core.Models;
using DatenMeister.Core.Models.EMOF;
using DatenMeister.Core.Uml.Helper;
using DatenMeister.Forms;
using DatenMeister.Forms.FormModifications;

namespace DatenMeister.Extent.Forms
{
    /// <summary>
    ///     Defines the default type modification plugin.
    /// It finds the 'packagedElement' of a package and adds all preferred type as being mentioned
    /// in the package instance itself
    /// </summary>
    public class PackageFormModificationPlugin : IFormModificationPlugin
    {
        public bool ModifyForm(FormCreationContext context, IElement form)
        {
            if (context.MetaClass?.Equals(_DatenMeister.TheOne.CommonTypes.Default.__Package) == true
                && context.FormType == _DatenMeister._Forms.___FormType.Object
                && context.ParentPropertyName == string.Empty
                && context.DetailElement != null)
            {
                var tabPackagedElement =
                    FormMethods.GetTableFormForPropertyName(form,
                        _DatenMeister._CommonTypes._Default._Package.packagedElement);

                if (tabPackagedElement != null)
                {
                    var factory = new MofFactory(form);

                    var defaultTypes =
                        tabPackagedElement.get<IReflectiveCollection>(_DatenMeister._Forms._TableForm
                            .defaultTypesForNewElements);

                    // Checks the preferred types
                    var preferredTypes =
                        context.DetailElement.getOrDefault<IReflectiveCollection>(
                            _DatenMeister._CommonTypes._Default._Package.preferredType);

                    AddPreferredTypes(form, factory, preferredTypes, defaultTypes);

                    // Checks the preferred package.
                    // If a preferred package is set, then all containing classes will be added
                    var preferredPackages =
                        context.DetailElement.getOrDefault<IReflectiveCollection>(
                            _DatenMeister._CommonTypes._Default._Package.preferredPackage);

                    if (preferredPackages != null)
                        foreach (var preferredPackage in preferredPackages.OfType<IElement>())
                        {
                            var preferredTypes2 = PackageMethods.GetPackagedObjects(preferredPackage);
                            AddPreferredTypes(form, factory, preferredTypes2, defaultTypes);
                        }
                }

                return true;
            }

            return false;
        }

        private static void AddPreferredTypes(
            IObject form,
            MofFactory factory,
            IReflectiveCollection? preferredTypes,
            IReflectiveCollection defaultTypes)
        {
            if (preferredTypes != null)
                foreach (var preferredType in preferredTypes.OfType<IElement>())
                    AddPreferredType(form, factory, preferredType, defaultTypes);
        }

        private static void AddPreferredType(
            IObject form,
            IFactory factory,
            IElement preferredType,
            IReflectiveCollection defaultTypes)
        {
            if (preferredType.getMetaClass()?.Equals(_UML.TheOne.StructuredClassifiers.__Class) == true)
            {
                var defaultType = factory.create(_DatenMeister.TheOne.Forms.__DefaultTypeForNewElement);
                defaultType.set(_DatenMeister._Forms._DefaultTypeForNewElement.name,
                    NamedElementMethods.GetName(preferredType));
                defaultType.set(_DatenMeister._Forms._DefaultTypeForNewElement.metaClass, preferredType);
                defaultTypes.add(defaultType);

                FormMethods.AddToFormCreationProtocol(
                    form,
                    "[PackageFormModificationPlugin]: Add DefaultType by preferred Types" +
                    NamedElementMethods.GetName(defaultType));
            }
        }
    }
}


text:
/*
 * dict.util.share.js
 * Share with bookmarklet. No jQuery
 */
void((function(w,d){
'use strict';
function get1stTag() {
    var result;
    for (var i = 0; i < arguments.length; i++) {
        var tag=arguments[i],
            tags=d.getElementsByTagName(tag);
        if (tags.length>0) {
            result = tags[0];
            break;
        }
    }
    return result || d.documentElement.childNodes[0];
}

// for test & hook
w.__DICT__ = w.__DICT__ || {};
w.__DICT__.appendTag = function (node) {
    var tag = get1stTag('head','body');
    if (tag){
        tag.appendChild(node);
    } else {
        var url = 'http://dict-admin.appspot.com';
        alert('Sorry, Not support for your browser. More details, visit: '+url);
        window.open(url);
    }
};

})(window,document));


text:
"""
A module for sharing intermediates between contractions.

Copyright (c) 2018 Uber Technologies
"""

import contextlib
import functools
import numbers
import threading
from collections import Counter, defaultdict
from typing import Any
from typing import Counter as CounterType
from typing import Dict, Generator, List, Optional, Tuple, Union

from .parser import alpha_canonicalize, parse_einsum_input
from .typing import ArrayType

CacheKeyType = Union[Tuple[str, str, int, Tuple[int, ...]], Tuple[str, int]]
CacheType = Dict[CacheKeyType, ArrayType]

__all__ = [
    "currently_sharing",
    "get_sharing_cache",
    "shared_intermediates",
    "count_cached_ops",
    "transpose_cache_wrap",
    "einsum_cache_wrap",
    "to_backend_cache_wrap",
]

_SHARING_STACK: Dict[int, List[CacheType]] = defaultdict(list)

def currently_sharing() -> bool:
    """Check if we are currently sharing a cache -- thread specific."""
    return threading.get_ident() in _SHARING_STACK

def get_sharing_cache() -> CacheType:
    """Return the most recent sharing cache -- thread specific."""
    return _SHARING_STACK[threading.get_ident()][-1]

def _add_sharing_cache(cache: CacheType) -> Any:
    _SHARING_STACK[threading.get_ident()].append(cache)

def _remove_sharing_cache() -> None:
    tid = threading.get_ident()
    _SHARING_STACK[tid].pop()
    if not _SHARING_STACK[tid]:
        del _SHARING_STACK[tid]

@contextlib.contextmanager
def shared_intermediates(
    cache: Optional[CacheType] = None,
) -> Generator[CacheType, None, None]:
    """Context in which contract intermediate results are shared.

    Note that intermediate computations will not be garbage collected until
    1. this context exits, and
    2. the yielded cache is garbage collected (if it was captured).

    **Parameters:**

    - **cache** - *(dict)* If specified, a user-stored dict in which intermediate results will be stored. This can be used to interleave sharing contexts.

    **Returns:**

    - **cache** - *(dict)* A dictionary in which sharing results are stored. If ignored,
        sharing results will be garbage collected when this context is
        exited. This dict can be passed to another context to resume
        sharing.
    """
    if cache is None:
        cache = {}
    _add_sharing_cache(cache)
    try:
        yield cache
    finally:
        _remove_sharing_cache()

def count_cached_ops(cache: CacheType) -> CounterType[str]:
    """Returns a counter of the types of each op in the cache.
    This is useful for profiling to increase sharing.
    """
    return Counter(key[0] for key in cache.keys())

def _save_tensors(*tensors: ArrayType) -> None:
    """Save tensors in the cache to prevent their ids from being recycled.
    This is needed to prevent false cache lookups.
    """
    cache = get_sharing_cache()
    for tensor in tensors:
        cache["tensor", id(tensor)] = tensor

def _memoize(key: CacheKeyType, fn: Any, *args: Any, **kwargs: Any) -> ArrayType:
    """Memoize ``fn(*args, **kwargs)`` using the given ``key``.
    Results will be stored in the innermost ``cache`` yielded by
    :func:`shared_intermediates`.
    """
    cache = get_sharing_cache()
    if key in cache:
        return cache[key]
    result = fn(*args, **kwargs)
    cache[key] = result
    return result

def transpose_cache_wrap(transpose: Any) -> Any:
    """Decorates a ``transpose()`` implementation to be memoized inside a
    :func:`shared_intermediates` context.
    """

    @functools.wraps(transpose)
    def cached_transpose(a, axes, backend="numpy"):
        if not currently_sharing():
            return transpose(a, axes, backend=backend)

        # hash by axes
        _save_tensors(a)
        axes = tuple(axes)
        key = "transpose", backend, id(a), axes
        return _memoize(key, transpose, a, axes, backend=backend)

    return cached_transpose

def tensordot_cache_wrap(tensordot: Any) -> Any:
    """Decorates a ``tensordot()`` implementation to be memoized inside a
    :func:`shared_intermediates` context.
    """

    @functools.wraps(tensordot)
    def cached_tensordot(x, y, axes=2, backend="numpy"):
        if not currently_sharing():
            return tensordot(x, y, axes, backend=backend)

        # hash based on the (axes_x,axes_y) form of axes
        _save_tensors(x, y)
        if isinstance(axes, numbers.Number):
            axes = (
                list(range(len(x.shape)))[len(x.shape) - axes :],
                list(range(len(y.shape)))[:axes],
            )
        axes = tuple(axes[0]), tuple(axes[1])
        key = "tensordot", backend, id(x), id(y), axes
        return _memoize(key, tensordot, x, y, axes, backend=backend)

    return cached_tensordot

def einsum_cache_wrap(einsum: Any) -> Any:
    """Decorates an ``einsum()`` implementation to be memoized inside a
    :func:`shared_intermediates` context.
    """

    @functools.wraps(einsum)
    def cached_einsum(*args, **kwargs):
        if not currently_sharing():
            return einsum(*args, **kwargs)

        # hash modulo commutativity by computing a canonical ordering and names
        backend = kwargs.pop("backend", "numpy")
        equation = args[0]
        inputs, output, operands = parse_einsum_input(args)
        inputs = inputs.split(",")

        _save_tensors(*operands)

        # Build canonical key
        canonical = sorted(zip(inputs, map(id, operands)), key=lambda x: x[1])
        canonical_ids = tuple(id_ for _, id_ in canonical)
        canonical_inputs = ",".join(input_ for input_, _ in canonical)
        canonical_equation = alpha_canonicalize(canonical_inputs + "->" + output)

        key = "einsum", backend, canonical_equation, canonical_ids
        return _memoize(key, einsum, equation, *operands, backend=backend)

    return cached_einsum

def to_backend_cache_wrap(to_backend: Any = None, constants: Any = False) -> Any:
    """Decorates an ``to_backend()`` implementation to be memoized inside a
    :func:`shared_intermediates` context (e.g. ``to_cupy``, ``to_torch``).
    """
    # manage the case that decorator is called with args
    if to_backend is None:
        return functools.partial(to_backend_cache_wrap, constants=constants)

    if constants:

        @functools.wraps(to_backend)
        def cached_to_backend(array, constant=False):
            if not currently_sharing():
                return to_backend(array, constant=constant)

            # hash by id
            key = to_backend.__name__, id(array), constant
            return _memoize(key, to_backend, array, constant=constant)

    else:

        @functools.wraps(to_backend)
        def cached_to_backend(array):
            if not currently_sharing():
                return to_backend(array)

            # hash by id
            key = to_backend.__name__, id(array)
            return _memoize(key, to_backend, array)

    return cached_to_backend


text:
try:
    import smbus
except ImportError:
    raise ImportError("python-smbus not found'")
import re

"""
================================================
ABElectronics Python Helper Functions
Version 1.0 Created 29/02/2015
Python 3 only
Requires python 3 smbus to be installed.  For more information
about enabling i2c and installing smbus visit
https://www.abelectronics.co.uk/i2c-raspbian-wheezy/info.aspx
================================================
"""

class ABEHelpers:

    def get_smbus(self):
        # detect i2C port number and assign to i2c_bus
        i2c_bus = 0
        for line in open('/proc/cpuinfo').readlines():
            m = re.match('(.*?)\s*:\s*(.*)', line)
            if m:
                (name, value) = (m.group(1), m.group(2))
                if name == "Revision":
                    if value[-4:] in ('0002', '0003'):
                        i2c_bus = 0
                    else:
                        i2c_bus = 1
                    break
        try:
            return smbus.SMBus(i2c_bus)
        except IOError:
                print ("Could not open the i2c bus.")
                print ("Please check that i2c is enabled and python-smbus and i2c-tools are installed.")
                print ("Visit https://www.abelectronics.co.uk/i2c-raspbian-wheezy/info.aspx for more information.")


text:
package org.jboss.arquillian.graphene.drone;

import org.jboss.arquillian.core.spi.LoadableExtension;
import org.jboss.arquillian.drone.spi.Configurator;
import org.jboss.arquillian.drone.spi.Destructor;
import org.jboss.arquillian.drone.spi.Instantiator;
import org.jboss.arquillian.graphene.drone.factory.GrapheneAndroidDriverFactory;
import org.jboss.arquillian.graphene.drone.factory.GrapheneChromeDriverFactory;
import org.jboss.arquillian.graphene.drone.factory.GrapheneFirefoxDriverFactory;
import org.jboss.arquillian.graphene.drone.factory.GrapheneHtmlUnitDriverFactory;
import org.jboss.arquillian.graphene.drone.factory.GrapheneIPhoneDriverFactory;
import org.jboss.arquillian.graphene.drone.factory.GrapheneInternetExplorerDriverFactory;
import org.jboss.arquillian.graphene.drone.factory.GrapheneWebDriverFactory;

/**
 * Arquillian Drone support Graphene and WebDriver and its implementations
 *
 * Lukas Fryc
 */
public class DroneGrapheneExtension implements LoadableExtension {

    public void register(ExtensionBuilder builder) {

        builder.service(Configurator.class, GrapheneAndroidDriverFactory.class);
        builder.service(Instantiator.class, GrapheneAndroidDriverFactory.class);
        builder.service(Destructor.class, GrapheneAndroidDriverFactory.class);

        builder.service(Configurator.class, GrapheneChromeDriverFactory.class);
        builder.service(Instantiator.class, GrapheneChromeDriverFactory.class);
        builder.service(Destructor.class, GrapheneChromeDriverFactory.class);

        builder.service(Configurator.class, GrapheneFirefoxDriverFactory.class);
        builder.service(Instantiator.class, GrapheneFirefoxDriverFactory.class);
        builder.service(Destructor.class, GrapheneFirefoxDriverFactory.class);

        builder.service(Configurator.class, GrapheneHtmlUnitDriverFactory.class);
        builder.service(Instantiator.class, GrapheneHtmlUnitDriverFactory.class);
        builder.service(Destructor.class, GrapheneHtmlUnitDriverFactory.class);

        builder.service(Configurator.class, GrapheneInternetExplorerDriverFactory.class);
        builder.service(Instantiator.class, GrapheneInternetExplorerDriverFactory.class);
        builder.service(Destructor.class, GrapheneInternetExplorerDriverFactory.class);

        builder.service(Configurator.class, GrapheneIPhoneDriverFactory.class);
        builder.service(Instantiator.class, GrapheneIPhoneDriverFactory.class);
        builder.service(Destructor.class, GrapheneIPhoneDriverFactory.class);

        builder.service(Configurator.class, GrapheneWebDriverFactory.class);
        builder.service(Instantiator.class, GrapheneWebDriverFactory.class);
        builder.service(Destructor.class, GrapheneWebDriverFactory.class);
    }
}


text:
package com.cloudbees.gasp.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.cloudbees.gasp.R;
import com.cloudbees.gasp.activity.TwitterStreamActivity;
import com.cloudbees.gasp.service.RESTIntentService;
import com.cloudbees.gasp.twitter.TwitterAPI;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

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

/**
 * Closely modeled on Neil Goodman's Android REST tutorials
 * https://github.com/posco2k8/rest_service_tutorial
 * https://github.com/posco2k8/rest_loader_tutorial.git
 *
 * @author Mark Prichard
 */
public class TwitterResponderFragment extends RESTResponderFragment {
    private static final String TAG = TwitterResponderFragment.class.getName();

    private List<String> mTweets;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setTweets();
    }

    private void setTweets() {
        TwitterStreamActivity activity = (TwitterStreamActivity) getActivity();

        try {
            // Get Twitter search keyword from Shared Preferences
            SharedPreferences gaspSharedPreferences =
                    PreferenceManager.getDefaultSharedPreferences(getActivity());
            String keyword = gaspSharedPreferences.getString(getString(R.string.gasp_twitter_preferences), "");

            if (mTweets == null && activity != null) {
                Intent intent = new Intent(activity, RESTIntentService.class);
                intent.setData(Uri.parse(TwitterAPI.getTwitterApiSearch()));

                Bundle params = new Bundle();
                params.putString("q", keyword);
                params.putString("count", "10");

                Bundle headers = new Bundle();
                headers.putString("Authorization", "Bearer " + TwitterStreamActivity.getTwitterOAuthToken());

                intent.putExtra(RESTIntentService.EXTRA_PARAMS, params);
                intent.putExtra(RESTIntentService.EXTRA_HEADERS, headers);
                intent.putExtra(RESTIntentService.EXTRA_RESULT_RECEIVER, getResultReceiver());

                activity.startService(intent);
            } else if (activity != null) {
                ArrayAdapter<String> adapter = activity.getArrayAdapter();

                adapter.clear();
                for (String tweet : mTweets) {
                    adapter.add(tweet);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRESTResult(int code, String result) {
        if (code == 200 && result != null) {
            mTweets = getTweetsFromJson(result);
            setTweets();
        }
        else {
            Activity activity = getActivity();
            if (activity != null) {
                Toast.makeText(activity,
                                getResources().getString(R.string.gasp_twitter_error),
                                Toast.LENGTH_SHORT)
                                .show();
            }
        }
    }

    private static List<String> getTweetsFromJson(String json) {
        ArrayList<String> tweetList = new ArrayList<String>();

        try {
            JSONObject tweetsWrapper = (JSONObject) new JSONTokener(json).nextValue();
            JSONArray  tweets        = tweetsWrapper.getJSONArray("statuses");

            for (int i = 0; i < tweets.length(); i++) {
                JSONObject tweet = tweets.getJSONObject(i);
                Log.d(TAG, "Tweet: " + tweet.getString("text"));
                tweetList.add(tweet.getString("text"));
            }
        }
        catch (JSONException e) {
            Log.e(TAG, "Failed to parse JSON.", e);
        }

        return tweetList;
    }

}


text:
import flatbuffers

class Register(object):
    __slots__ = ['_tab']

    @classmethod
    def GetRootAsRegister(cls, buf, offset):
        n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
        x = Register()
        x.Init(buf, n + offset)
        return x

    # Register
    def Init(self, buf, pos):
        self._tab = flatbuffers.table.Table(buf, pos)

    # Register
    def Request(self):
        o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
        if o != 0:
            return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
        return 0

    # Register
    def Procedure(self):
        o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
        if o != 0:
            return self._tab.String(o + self._tab.Pos)
        return None

    # Register
    def Match(self):
        o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
        if o != 0:
            return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos)
        return 0

    # Register
    def Invoke(self):
        o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
        if o != 0:
            return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos)
        return 0

    # Register
    def Concurrency(self):
        o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
        if o != 0:
            return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos)
        return 0

    # Register
    def ForceReregister(self):
        o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14))
        if o != 0:
            return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
        return False

def RegisterStart(builder): builder.StartObject(6)
def RegisterAddRequest(builder, request): builder.PrependUint64Slot(0, request, 0)
def RegisterAddProcedure(builder, procedure): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(procedure), 0)
def RegisterAddMatch(builder, match): builder.PrependUint8Slot(2, match, 0)
def RegisterAddInvoke(builder, invoke): builder.PrependUint8Slot(3, invoke, 0)
def RegisterAddConcurrency(builder, concurrency): builder.PrependUint16Slot(4, concurrency, 0)
def RegisterAddForceReregister(builder, forceReregister): builder.PrependBoolSlot(5, forceReregister, 0)
def RegisterEnd(builder): return builder.EndObject()


text:
var akop = {
  debug: {
      isOn: true,
      log: function() {
          if (this.isOn && window.console)
              console.log.apply(window.console, arguments);
      },
      warn: function() {
          if (this.isOn && window.console)
              console.warn.apply(window.console, arguments);
      },
      dir: function() {
          if (this.isOn && window.console)
              console.dir.apply(window.console, arguments);
      },
      stop: function() {
          if (this.isOn)
              debugger;
      }
  },

	getTargetObject: function (e) {
		return (e.target.tagName == "A") ? e.target	: e.target.parentNode;
	},

	getOffsetRectById: function (elemId) {
		return akop.getOffsetRect(document.getElementById(elemId));
	},

	/** Находим координаты нужного блока */
	getOffsetRect: function (elem) {
		if (elem == null) {
			result = {top: 0, left: 0};
		} else {
			var box = elem.getBoundingClientRect();

			var body = document.body;
			var docElem = document.documentElement;

			var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
			var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;

			var clientTop = docElem.clientTop || body.clientTop || 0;
			var clientLeft = docElem.clientLeft || body.clientLeft || 0;

			var top  = box.top +  scrollTop - clientTop;
			var left = box.left + scrollLeft - clientLeft;

			result = {top: Math.round(top), left: Math.round(left)};
		}
		return result;
	},

	/**
	 *  Загружает страницу указанную в атрибуте href, показывает ее в модальном окне
	 *  работа в 6 этапов:
	 *  1. Загружает страницу страницу указанную в атрибуте href
	 *  2. Запускаем функцию указанную в аттрибуте data-callback-function-before-load
	 *     (в этой функции должен быть код выполняющий допобработки перед загрузкой, например, формирование url)
	 *  3. Помещает в модальное окно
	 *  4. На кнопку сохранения вешаем функцию указанную в аттрибуте data-callback-function
	 *  5. Открываем модальное окно
	 *  6. Запускаем функцию указанную в аттрибуте data-callback-function-after-load (в этой функции должен быть код выполняющий допобработки перед редактированием)
	 *
	 */
	showAjaxPage: function (e) {
		e = e || window.event;
		akop.debug.log("showAjaxPage e", e);
		e.preventDefault();
		akop.closeDismissable();

		/** Получаем данные в тэге "A" */

		var obj = akop.getTargetObject(e);
		var d = obj.dataset;

		var url = obj.href;
		var callbackFunctionAfterLoad = eval('(' + d.callbackFunctionAfterLoad + ')');
		var callbackFunctionBeforeLoad = eval('(' + d.callbackFunctionBeforeLoad + ')');

		if (callbackFunctionBeforeLoad != undefined) callbackFunctionBeforeLoad.call(this, obj, e);
		$.ajax({
			type: "POST",
			"url": url,
			data: d,
			error: function() {
				akop.showMessage("Ошибка загрузки данных. Попробуйте позже.", 5000, "danger");
			},
			success: function(response) {
				akop.showModal(e, response, d.callbackFunction);

				if (callbackFunctionAfterLoad != undefined) callbackFunctionAfterLoad.call(this, obj, e);
			},
			complete: function() {
			}
		});

	},

	showModal: function (e, message, callbackFunction) {
		e = e || window.event;
		e.preventDefault();
		akop.closeDismissable();

		/** Получаем данные в тэге "A" */

		var obj = akop.getTargetObject(e);
		var d = obj.dataset;

		/** Размер модального окна */
		$modalDialog = $('.modal-dialog')
			.removeClass("modal-sm")
			.removeClass("modal-lg");

		if (d.modalSize) {
			$modalDialog.addClass(d.modalSize);
		}

		$(".modal-header").css("display", "block");
		$("#myModalLabel").text(d.heading);
		$("#modal-body").html(message);
		$('#myModal').modal({ keyboard: true }).modal('show');
		$('#myModal').find("input").first().focus();
		var callbackFunction = eval('(' + callbackFunction + ')');

		$("#modal-submit").off("click").on("click", function(e){
			$('#myModal').modal('hide');
			callbackFunction.call(this, obj);
			return false;
		});

	},

	/**
	*	Скрываем всплывающее сообщение
	*/
	closeMessage: function () {
		$("#akop-alerter").remove();
	},

	/**
	*	Показываем всплывающее сообщение
	*/

	showMessage: function (message, messageTimeout, messageType) {
		akop.closeDismissable();
		if (typeof messageType == 'undefined') messageType = "info";
		var alerterId = "akop-alerter";
		$("#" + alerterId).remove();
		var divAlert = "
" + message + "
";

		$("body")
			.append(divAlert)
			.fadeIn(300);

		/* Скрываем всплывающее сообщение после таймаута*/
		if (messageTimeout != undefined) {
			setTimeout(
				function () {$("#" + alerterId).fadeOut(300).remove();},
				messageTimeout
			);
		}
	},

	/**
	*	Показываем всплывающее сообщение
	*/
	showDismissable: function (message, messageType) {
		akop.closeDismissable();
		if (typeof messageType == 'undefined') messageType = "info";

		$container = $("#dismissable")
			.append("
"
				+ "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>"
				+ message
				+ "
")
			.fadeIn(300)
			.find("a")
			.on("click", function(e) {
				e = e || window.event;
				e.preventDefault();

				var obj = akop.getTargetObject(e);
				var callbackFunction = eval('(' + obj.dataset.callbackFunction + ')');
				if (callbackFunction != undefined) callbackFunction.call(this, obj, e);
			});

	},

	closeDismissable: function () {
		$("#dismissable").empty();
	},

	/** Показать запрос на подтверждение действия */
	showConfirm: function (textMessage, callback_yes) {
		akop.closeDismissable();

		$("#modal-body").text(textMessage);
		$(".modal-header").css("display", "none");
		$('#myModal').modal('show');

		$("#modal-submit").on("click", function(e){
			$('#myModal').modal('hide');
			akop.debug.log("modal-submit", e);
			callback_yes.call();
		});

	},

	nl2br: function(varTest){
		return varTest.replace(/(\r\n|\n\r|\r|\n)/g, "
");
	},

	br2nl: function(varTest){
		return varTest.replace(/
/g, "\r");
	}
};

$(document).ready(function() {
	/** Обработка ссылок, которые должны открываться во всплывающем окне  */
	$(".ajax-page")
		.on("click", akop.showAjaxPage);
});


text:
  This feature is mobile only

Enables browser header coloring with Material Design Colors and the theming system.

For more information, please visit:

https://developers.google.com/web/fundamentals/design-and-ui/browser-customization/theme-color.

Below are usage examples for both the Angular configuration phase, and during runtime.

Config Phase

<hljs lang="js">
  myAppModule
    .config(function($mdThemingProvider) {
      // Enable browser color
      $mdThemingProvider.enableBrowserColor({
        theme: 'myTheme', // Default is 'default'
        palette: 'accent', // Default is 'primary', any basic material palette and extended palettes are available
        hue: '200' // Default is '800'
      });
    });
</hljs>

Runtime

<hljs lang="js">
  myAppModule
    .controller('myCtrl', function($scope, $mdTheming) {
      var removeFunction = $mdTheming.setBrowserColor({
        theme: 'myTheme', // Default is 'default'
        palette: 'accent', // Default is 'primary', any basic material palette and extended palettes are available
        hue: '200' // Default is '800'
      });

      $scope.$on('$destroy', function () {
        removeFunction(); // COMPLETELY removes the browser color
      })
    })
</hljs>

For api reference please visit $mdThemingProvider documentation.


text:
local addonName, ns = ...

--Some Tags
oUF.Tags.Events["shorthp"] = "UNIT_HEALTH"
oUF.Tags.Methods["shorthp"] = function(unit)
	if not UnitIsDeadOrGhost(unit) then
		local hp = UnitHealth(unit)
		return AbbreviateLargeNumbers(hp)
	end
end

oUF.Tags.Events["shortpp"] = "UNIT_POWER"
oUF.Tags.Methods["shortpp"] = function(unit)
	if not UnitIsDeadOrGhost(unit) then
		local pp = UnitPower(unit)
		return AbbreviateLargeNumbers(pp)
	end
end

oUF.Tags.Events["shortname"] = "UNIT_NAME"
oUF.Tags.Methods["shortname"] = function(unit)
	local name = UnitName(unit)
	return string.sub(UnitName(unit), 1, 20)
end

oUF.Tags.Events["readycheckicon"] = "DoReadyCheck"
oUF.Tags.SharedEvents["IsInGroup"] = true
oUF.Tags.Methods["readycheckicon"] = function(unit)
	if unit == "player" and IsInGroup() then
		return [[|TInterface\RAIDFRAME\ReadyCheck-Ready|t]]
	end
end

oUF.Tags.Events["rsicon"] = "PLAYER_UPDATE_RESTING"
oUF.Tags.SharedEvents["PLAYER_UPDATE_RESTING"] = true
oUF.Tags.Methods["rsicon"] = function(unit)
	if unit == "player" and IsResting() then
		return [[|TInterface\CharacterFrame\UI-StateIcon:0:0:0:-6:64:64:28:6:6:28|t]]
	end
end
oUF.Tags.Events["combaticon"] = "PLAYER_REGEN_DISABLED PLAYER_REGEN_ENABLED"
oUF.Tags.SharedEvents["PLAYER_REGEN_DISABLED"] = true
oUF.Tags.SharedEvents["PLAYER_REGEN_ENABLED"] = true
oUF.Tags.Methods["combaticon"] = function(unit)
	if unit == "player" and UnitAffectingCombat("player") then
		return [[|TInterface\CharacterFrame\UI-StateIcon:0:0:0:0:64:64:37:58:5:26|t]]
	end
end

oUF.Tags.Events["leadericon"] = "GROUP_ROSTER_UPDATE"
oUF.Tags.SharedEvents["GROUP_ROSTER_UPDATE"] = true
oUF.Tags.Methods["leadericon"] = function(unit)
	if UnitIsGroupLeader(unit) then
		return [[|TInterface\GroupFrame\UI-Group-LeaderIcon:0|t]]
	elseif UnitInRaid(unit) and UnitIsGroupAssistant(unit) then
		return [[|TInterface\GroupFrame\UI-Group-AssistantIcon:0|t]]
	end
end

oUF.Tags.Events["mastericon"] = "PARTY_LOOT_METHOD_CHANGED GROUP_ROSTER_UPDATE"
oUF.Tags.SharedEvents["PARTY_LOOT_METHOD_CHANGED"] = true
oUF.Tags.SharedEvents["GROUP_ROSTER_UPDATE"] = true
oUF.Tags.Methods["mastericon"] = function(unit)
	local method, pid, rid = GetLootMethod()
	if method ~= "master" then return end
	local munit
	if pid then
		if pid == 0 then
			munit = "player"
		else
			munit = "party" .. pid
		end
	elseif rid then
		munit = "raid" .. rid
	end
	if munit and UnitIsUnit(munit, unit) then
		return [[|TInterface\GroupFrame\UI-Group-MasterLooter:0:0:0:2|t]]
	end
end

ns.tags = tags


text:
package com.yahoo.dtf.actions.file;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

import com.yahoo.dtf.actions.util.CDATA;
import com.yahoo.dtf.exception.DTFException;
import com.yahoo.dtf.exception.ParseException;
import com.yahoo.dtf.streaming.DTFInputStream;

/**
 * @dtf.tag cat
 *
 * @dtf.since 1.0
 * @dtf.author Rodney Gomes
 *
 * @dtf.tag.desc Cat tag is used to output information to files that would
 *               usually be logged to the test case output.
 *
 *
 * @dtf.tag.example
 * <cat uri="storage://OUTPUT/testoutput">
 *      This output will be visible at storage://OUTPUT/testoutput
 *      Os: ${os.name}
 *      Arch: ${os.arch}
 *      dtf.test.property1 = ${dtf.test.property1}
 *      dtf.test.property2 = ${dtf.test.property2}
 * </cat>
 *
 * @dtf.tag.example
 * <cat uri="storage://OUTPUT/testoutput" append="false">BLAH BLAH BLAH</cat>
 */
public class Cat extends CDATA {

    /**
     * @dtf.attr uri
     * @dtf.attr.desc The URI defining where to output the enclosed message.
     */
    private String uri = null;

    /**
     * @dtf.attr append
     * @dtf.attr.desc Attribute will specify if we want to append to the
     *                destination or just replace it with the new contents.
     */
    private String append = null;

    /**
     * @dtf.attr encoding
     * @dtf.attr.desc

     *                Encoding to use when loading the specified property file.
     *                DTF defaults to the Java default file encoding which comes
     *                from the property file.encoding. If you want to
     *                change the default encoding set the file.encoding on the
     *                command line when you start any of the components.
     *

     *

     *                Every implementation of the Java platform is required to
     *                support the following character encodings. Consult the
     *                release documentation for your implementation to see if
     *                any other encodings are supported.
     *

     *
     *

     *
US-ASCII    Seven-bit ASCII, a.k.a.

     *
ISO646-US, a.k.a. the Basic Latin block of the Unicode
     *                               character set

     *
ISO-8859-1  ISO Latin Alphabet No. 1, a.k.a.
     *                               ISO-LATIN-1

     *
Eight-bit Unicode Transformation Format

     *
UTF-16BE Sixteen-bit Unicode Transformation Format,
     *                               big-endian byte order

     *
UTF-16LE Sixteen-bit Unicode Transformation Format,
     *                               little-endian byte order

     *
UTF-16  Sixteen-bit Unicode Transformation Format,
     *                               byte order specified by a mandatory initial
     *                               byte-order mark (either order accepted on
     *                               input, big-endian used on output)

     *

     */
    private String encoding = null;

    public void execute() throws DTFException {
        OutputStream os = getStorageFactory().
                                          getOutputStream(getUri(),getAppend());

        try {
            DTFInputStream dis = getCDATAStream(getEncoding());

            if ( dis != null ) {
                byte[] bytes = new byte[4*1024];
                int read = 0;
                while ( (read = dis.read(bytes)) != -1 ) {
                    os.write(bytes,0,read);
                }
            }
        } catch (IOException e) {
            throw new DTFException("Unable to write to [" + getUri() + "]",e);
        } finally {
            try {
                os.close();
            } catch (IOException ignore) { }
        }
    }

    public void setUri(String uri) { this.uri = uri; }
    public URI getUri() throws ParseException { return parseURI(uri); }

    public void setAppend(String append) { this.append = append; }
    public boolean getAppend() throws ParseException { return toBoolean("append", append); }

    public void setEncoding(String encoding) { this.encoding = encoding; }
    public String getEncoding() throws ParseException { return replaceProperties(encoding); }
}