text:
<?php
namespace Scalr\Service\Aws\DataType;

use Scalr\Service\Aws\AbstractDataType;

/**
 * List data type
 *
 * @author    Vitaliy Demidov   <vitaliy@scalr.com>
 * @since     23.09.2012
 */
class ListDataType extends AbstractDataType implements \Iterator, \Countable, \ArrayAccess
{

    /**
     * @var array
     */
    private $aListData;

    /**
     * @var string
     */
    private $dataClassName;

    /**
     * @var string
     */
    private $propertyName;

    /**
     * Result list
     *
     * @var array
     */
    private $list;

    /**
     * Position is used for Iterator implementation
     *
     * @var int
     */
    private $listPosition = 0;

    /**
     * Next token
     *
     * @var string
     */
    private $nextToken = null;

    /**
     * {@inheritdoc}
     * @see ArrayAccess::offsetExists()
     */
    public function offsetExists($offset)
    {
        return isset($this->aListData[$offset]);
    }

    /**
     * {@inheritdoc}
     * @see ArrayAccess::offsetGet()
     */
    public function offsetGet($offset)
    {
        return isset($this->aListData[$offset]) ? $this->aListData[$offset] : null;
    }

    /**
     * {@inheritdoc}
     * @see ArrayAccess::offsetSet()
     */
    public function offsetSet($offset, $value)
    {
        if (!$this->isValidObject($value)) {
            throw new \InvalidArgumentException('If object is passed it must be instance of ' . $this->dataClassName);
        }
        $this->setExternalIdentifiersRecursively($value);
        if (is_null($offset)) {
            $this->aListData[] = $value;
        } else if (is_numeric($offset)) {
            $this->aListData[$offset] = $value;
        } else {
            throw new \InvalidArgumentException('It is not allowed to use string offset keys.');
        }
    }

    /**
     * {@inheritdoc}
     * @see ArrayAccess::offsetUnset()
     */
    public function offsetUnset($offset)
    {
        unset($this->aListData[$offset]);
    }

    /**
     * {@inheritdoc}
     * @see \Iterator::current()
     */
    public function current()
    {
        return $this->aListData[$this->listPosition];
    }

    /**
     * {@inheritdoc}
     * @see \Iterator::key()
     */
    public function key()
    {
        $key = $this->listPosition;
        return $key;
    }

    /**
     * {@inheritdoc}
     * @see \Iterator::next()
     */
    public function next()
    {
        ++$this->listPosition;
    }

    /**
     * {@inheritdoc}
     * @see \Iterator::rewind()
     */
    public function rewind()
    {
        $this->listPosition = 0;
        //It is necessary if we unset object at special position.
        $this->aListData = array_values($this->aListData);
    }

    /**
     * {@inheritdoc}
     * @see \Iterator::valid()
     */
    public function valid()
    {
        return isset($this->aListData[$this->listPosition]);
    }

    /**
     * {@inheritdoc}
     * @see \Countable::count()
     */
    public function count()
    {
        return count($this->aListData);
    }

    /**
     * Checks if required object is valid.
     *
     * @param    mixed    $object
     * @return   boolean  Returns TRUE if object is an instancse of correct data class
     */
    public function isValidObject($object)
    {
        if ($this->dataClassName !== null && is_object($object)) {
            if (!($object instanceof $this->dataClassName)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Gets an original object at position N
     *
     * @param    int    $position optional A position at the list. If null it will use current position.
     * @return   mixed  Returns an original object at position N in the list.
     */
    public function get($position = null)
    {
        if ($position === null) {
            $position = $this->listPosition;
        }
        return isset($this->aListData[$position]) ? $this->aListData[$position] : null;
    }

    /**
     * Constructor
     *
     * @param     string|array|object $aListData     An array or single element of the list. It can be array of
     *                                               the objects of dataClassName class or a single object of
     *                                               the mentioned class.
     * @param     string|array        $propertyName  optional A public property name of the object that is used as
     *                                               out for query string.
     * @param     string              $dataClassName optional A data class name of the objects which form a list.
     */
    public function __construct($aListData = null, $propertyName = null, $dataClassName = null)
    {
        parent::__construct();
        $this->aListData = ($aListData === null ? array() : (!is_array($aListData) ? ($aListData instanceof self ? $aListData->getComputed() : array(
            $aListData
        )) : $aListData));
        $this->dataClassName = $dataClassName;
        $this->propertyName = $propertyName;
        //It turns strings or arrays into dataClass objects and set appropriate properties.
        if ($this->dataClassName != null) {
            if (is_array($this->propertyName) && count($this->propertyName) == 0) {
                throw new \InvalidArgumentException('Invalid propertyName argument. It must not be empty.');
            }
            foreach ($this->aListData as $k => $v) {
                $t = $this->typeCastData($v);
                if ($t !== null) {
                    $this->aListData[$k] = $t;
                    unset($t);
                }
            }
        }
    }

    /**
     * Type casts an list data object.
     *
     * @param   mixed     $v   The list member.
     * @return  mixed     Returns type cast object
     * @throws  \InvalidArgumentException
     */
    private function typeCastData($v)
    {
        $dataClass = $this->dataClassName;
        if (is_string($v) || is_numeric($v)) {
            $t = new $dataClass;
            $prop = 'set' . ucfirst(is_array($this->propertyName) ? $this->propertyName[0] : (string)$this->propertyName);
            $t->$prop($v);
        } else if (is_array($v)) {
            $t = new $dataClass;
            foreach ((array)$this->propertyName as $prop) {
                if (!array_key_exists($prop, $v)) {
                    //If property value isn't found in the specified array
                    //it will be omitted instead of the error generation.
                    //This is necessary, for an instance, when we specify the list constructor
                    //with the full bunch of the options from the data object which is going to be listed,
                    //and when these properies can be optional at the same time.
                    continue;
                }
                $setfn = 'set' . ucfirst($prop);
                $t->$setfn($v[$prop]);
            }
        }
        return isset($t) ? $t : null;
    }

    /**
     * Refreshes the list
     *
     * @throws \InvalidArgumentException
     */
    protected function refresh()
    {
        $this->list = array();
        foreach ($this->aListData as $v) {
            if (is_string($v) || is_numeric($v)) {
                $this->list[] = $v;
            } else if (is_array($v)) {
                if ($this->propertyName === null) {
                    $this->list[] = $v;
                } else if (is_array($this->propertyName)) {
                    $arr = array();
                    foreach ($this->propertyName as $sName) {
                        if (!array_key_exists($sName, $v)) {
                            throw new \InvalidArgumentException(sprintf('Could not find %s index in array', $sName));
                        }
                        $arr[$sName] = $v[$sName];
                    }
                    $this->list[] = $arr;
                    unset($arr);
                } else if (array_key_exists($this->propertyName, $v)) {
                    $this->list[] = $v[$this->propertyName];
                } else {
                    throw new \InvalidArgumentException(sprintf('Could not find %s index in array', $this->propertyName));
                }
            } else if (is_object($v)) {
                if ($this->dataClassName !== null && !($v instanceof $this->dataClassName)) {
                    throw new \InvalidArgumentException('Invalid List Data argument. It must be instance of ' . $this->dataClassName);
                }
                if ($this->propertyName === null) {
                    $this->list[] = $v;
                } else if (is_array($this->propertyName)) {
                    $arr = array();
                    foreach ($this->propertyName as $sName) {
                        if (property_exists($v, $sName)) {
                            $arr[$sName] = $v->{$sName};
                        } else {
                            $method = 'get' . ucfirst($sName);
                            $arr[$sName] = $v->{$method}();
                        }
                    }
                    $this->list[] = $arr;
                    unset($arr);
                } else {
                    if (property_exists($v, $this->propertyName)) {
                        $this->list[] = $v->{$this->propertyName};
                    } else {
                        $method = 'get' . ucfirst($this->propertyName);
                        $this->list[] = $v->$method();
                    }
                }
            }
        }
    }

    /**
     * Appends item to the list
     *
     * @param   mixed   $item
     */
    public function append($item)
    {
        if (isset($this->dataClassName) && !($item instanceof $this->dataClassName)) {
            if (is_array($item)) {
                //It tries to transform array to data object
                $item = $this->typeCastData($item);
            }
            if (!($item instanceof $this->dataClassName)) {
                throw new \InvalidArgumentException(
                    'Invalid value. Item must be instance of ' . $this->dataClassName . ' class.'
                );
            }
        }
        $this->setExternalIdentifiersRecursively($item);
        $this->aListData[] = $item;
    }

    /**
     * Gets property name of object or a key of assocciative array
     *
     * @return string|array|null Returns property name of object or a key of assocciative array
     */
    public function getPropertyName()
    {
        return $this->propertyName;
    }

    /**
     * Gets data class name restriction
     *
     * @return string|null Returns data class name
     */
    public function getDataClassName()
    {
        return $this->dataClassName;
    }

    /**
     * Gets computed list
     *
     * @return array  Returns computed array of values that represent list.
     */
    public function getComputed()
    {
        $this->refresh();
        return $this->list === null ? array() : $this->list;
    }

    /**
     * Gets original list.
     *
     * Gets original data array that has been passed as argument in constructor.
     *
     * @return array Returns original data array that has been passed as first argument in constructor.
     */
    public function getOriginal()
    {
        return $this->aListData;
    }

    /**
     * Gets query parameters array.
     *
     * This method overrides parent method.
     *
     * @param    string    $uriParameterName  optional Parameter name. If null it will use class property name
     *                                                 that is provided in constructor.
     * @param    bool      $member            optional Should it add member prefix
     * @return   string    Returns query parameters array looks like array ( 'parameterName.member.n[.propName[.member.m]]' => value )
     *                     Values are not url encoded.
     */
    public function getQueryArray($uriParameterName = null, $member = true)
    {
        $mprefix = $member ? '.member.' : '.';
        $this->refresh();
        if ($uriParameterName === null) {
            if ($this->propertyName === null || is_array($this->propertyName)) {
                $uriParameterName = 'Undefined';
            } else {
                $uriParameterName = $this->uppercaseProperty($this->propertyName);
            }
        }
        $fnCast = function($value) {
            if ($value instanceof StringType || is_int($value) || is_float($value)) {
                $value = (string) $value;
            } else if ($value instanceof \DateTime) {
                $value = $value->format('c');
            } else if (is_bool($value)) {
                $value = $value ? 'true' : 'false';
            }
            return $value;
        };
        $n = 1;
        $arr = array();
        foreach ($this->list as $v) {
            if (is_array($this->propertyName)) {
                foreach ((array) $this->propertyName as $prop) {
                    $ucProp = $this->uppercaseProperty($prop);
                    if (isset($v[$prop]) && $v[$prop] instanceof AbstractDataType) {
                        $sub = $v[$prop]->getQueryArray($uriParameterName . $mprefix . $n . '.' . $ucProp, $member);
                        if (!empty($sub)) {
                            $arr = array_merge($arr, $sub);
                            unset($sub);
                        }
                    } else if (isset($v[$prop]) && (is_array($v[$prop]) || $v[$prop] instanceof \Traversable)) {
                        $m = 1;
                        foreach ($v[$prop] as $mval) {
                            $arr[$uriParameterName . $mprefix . $n . '.' . $ucProp . $mprefix . $m] = $fnCast($mval);
                            $m++;
                        }
                    } else {
                        $arr[$uriParameterName . $mprefix . $n . '.' . $ucProp] = $fnCast($v[$prop]);
                    }
                }
                $n++;
            } else {
                $arr[$uriParameterName . $mprefix . $n++] = $fnCast($v);
            }
        }
        return $arr;
    }

    /**
     * Gets an external identifier keys that are associated with this object.
     *
     * @return   array  Returns the list of the external identifiers.
     */
    public function getExternalIdentifiers()
    {
        return $this->_externalKeys;
    }

    /**
     * Sets nextToken.
     *
     * @param   string  $nextToken Next Token
     */
    public function setNextToken($nextToken)
    {
        $this->nextToken = $nextToken;
    }

    /**
     * Gets nextToken.
     *
     * @return  string Returns nextToken.
     */
    public function getNextToken()
    {
        return $this->nextToken;
    }
}


text:
namespace extensions {

class ErrorUtils {
 public:
  // Creates an error messages from a pattern.
  static std::string FormatErrorMessage(base::StringPiece format,
                                        base::StringPiece s1);

  static std::string FormatErrorMessage(base::StringPiece format,
                                        base::StringPiece s1,
                                        base::StringPiece s2);

  static std::string FormatErrorMessage(base::StringPiece format,
                                        base::StringPiece s1,
                                        base::StringPiece s2,
                                        base::StringPiece s3);

  static std::u16string FormatErrorMessageUTF16(base::StringPiece format,
                                                base::StringPiece s1);

  static std::u16string FormatErrorMessageUTF16(base::StringPiece format,
                                                base::StringPiece s1,
                                                base::StringPiece s2);

  static std::u16string FormatErrorMessageUTF16(base::StringPiece format,
                                                base::StringPiece s1,
                                                base::StringPiece s2,
                                                base::StringPiece s3);
};

}  // namespace extensions

#endif  // EXTENSIONS_COMMON_ERROR_UTILS_H_

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

    <title>brunt_vaisala_frequency — MetPy 1.1</title>

  <link href="../../_static/css/theme.css" rel="stylesheet" />
  <link href="../../_static/css/index.f6b7ca918bee2f46fd9abac01cfb07d5.css" rel="stylesheet" />

  <link rel="stylesheet"
    href="../../_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/basic.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/plot_directive.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-binder.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-dataframe.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-rendered-html.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/theme-unidata.css" />

  <link rel="preload" as="script" href="../../_static/js/index.1e043a052b0af929e4d8.js">

    <link rel="shortcut icon" href="../../_static/metpy_32x32.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="brunt_vaisala_frequency_squared" href="metpy.calc.brunt_vaisala_frequency_squared.html" />
    <link rel="prev" title="wind_speed" href="metpy.calc.wind_speed.html" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="docsearch:language" content="en" />
    <link rel="canonical" href="https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.brunt_vaisala_frequency.html" />

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-menu" aria-controls="navbar-menu" aria-expanded="false" aria-label="Toggle navigation">

    </button>

            Version 1.1

            User Guide

            Reference Guide

            Developer's Guide

            Example Gallery

            Support

            Release Notes

      <form class="bd-search d-flex align-items-center" action="../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" >
</form>

   constants

   units

   metpy.io

   calc

     add_height_to_pressure

     add_pressure_to_height

     density

     dry_lapse

     dry_static_energy

     geopotential_to_height

     height_to_geopotential

     mean_pressure_weighted

     potential_temperature

     sigma_to_pressure

     static_stability

     temperature_from_potential_temperature

     thickness_hydrostatic

     dewpoint

     dewpoint_from_relative_humidity

     dewpoint_from_specific_humidity

     equivalent_potential_temperature

     mixing_ratio

     mixing_ratio_from_relative_humidity

     mixing_ratio_from_specific_humidity

     moist_lapse

     moist_static_energy

     precipitable_water

     psychrometric_vapor_pressure_wet

     relative_humidity_from_dewpoint

     relative_humidity_from_mixing_ratio

     relative_humidity_from_specific_humidity

     relative_humidity_wet_psychrometric

     saturation_equivalent_potential_temperature

     saturation_mixing_ratio

     saturation_vapor_pressure

     scale_height

     specific_humidity_from_dewpoint

     specific_humidity_from_mixing_ratio

     thickness_hydrostatic_from_relative_humidity

     vapor_pressure

     vertical_velocity

     vertical_velocity_pressure

     virtual_potential_temperature

     virtual_temperature

     wet_bulb_temperature

     bulk_shear

     bunkers_storm_motion

     cape_cin

     critical_angle

     el

     lcl

     lfc

     lifted_index

     mixed_layer

     mixed_layer_cape_cin

     mixed_parcel

     most_unstable_cape_cin

     most_unstable_parcel

     parcel_profile

     parcel_profile_with_lcl

     parcel_profile_with_lcl_as_dataset

     showalter_index

     significant_tornado

     storm_relative_helicity

     supercell_composite

     surface_based_cape_cin

     absolute_momentum

     absolute_vorticity

     advection

     ageostrophic_wind

     coriolis_parameter

     divergence

     exner_function

     frontogenesis

     geostrophic_wind

     inertial_advective_wind

     kinematic_flux

     montgomery_streamfunction

     potential_vorticity_baroclinic

     potential_vorticity_barotropic

     q_vector

     shearing_deformation

     stretching_deformation

     total_deformation

     vorticity

     wind_components

     wind_direction

     wind_speed

     brunt_vaisala_frequency

     brunt_vaisala_frequency_squared

     brunt_vaisala_period

     friction_velocity

     gradient_richardson_number

     tke

     cross_section_components

     first_derivative

     gradient

     laplacian

     lat_lon_grid_deltas

     normal_component

     second_derivative

     tangential_component

     unit_vectors_from_cross_section

     apparent_temperature

     heat_index

     windchill

     altimeter_to_sea_level_pressure

     altimeter_to_station_pressure

     height_to_pressure_std

     pressure_to_height_std

     smooth_gaussian

     smooth_window

     smooth_rectangular

     smooth_circular

     smooth_n_point

     angle_to_direction

     azimuth_range_to_lat_lon

     find_bounding_indices

     find_intersections

     get_layer

     get_layer_heights

     get_perturbation

     isentropic_interpolation

     isentropic_interpolation_as_dataset

     nearest_intersection_idx

     parse_angle

     reduce_point_density

     resample_nn_1d

   metpy.plots

   ctables

   interpolate

   xarray

   References

brunt_vaisala_frequency¶

metpy.calc.brunt_vaisala_frequency(height, potential_temperature, vertical_dim=0)¶

Calculate the Brunt-Vaisala frequency.

This function will calculate the Brunt-Vaisala frequency as follows:

\[N = \left( \frac{g}{\theta} \frac{d\theta}{dz} \right)^\frac{1}{2}\]

This formula based off of Equations 3.75 and 3.77 in [Hobbs2006].

This function is a wrapper for brunt_vaisala_frequency_squared that filters out negative
(unstable) quantities and takes the square root.

Parameters

height (xarray.DataArray or pint.Quantity) – Atmospheric (geopotential) height

potential_temperature (xarray.DataArray or pint.Quantity) – Atmospheric potential temperature

vertical_dim (int, optional) – The axis corresponding to vertical in the potential temperature array, defaults to 0,
unless height and potential_temperature given as xarray.DataArray, in which case
it is automatically determined from the coordinate metadata.

Returns

pint.Quantity or xarray.DataArray – Brunt-Vaisala frequency. Given as pint.Quantity, unless both
height and potential_temperature arguments are given as xarray.DataArray, in
which case will be xarray.DataArray.

Changed in version 1.0: Renamed heights, axis parameters to height, vertical_dim

See also

brunt_vaisala_frequency_squared, brunt_vaisala_period, potential_temperature

    wind_speed
    brunt_vaisala_frequency_squared

          © Copyright 2008–2021, MetPy Developers.Development is supported by Unidata and the National Science Foundation..

        Last updated on Aug 09, 2021 at 17:24:01.

        Created using Sphinx 4.1.2.


text:
import Ember from 'ember';

var ApplicationController = Ember.ObjectController.extend({
    jsonString: function(){
        var jsonObject = this.get('model.menus');
        return JSON.stringify(jsonObject);
    }.property('jsonString'),
    refreshJson: function(){
        var jsonObject = JSON.parse(this.jsonString);
        this.set('model.menus', jsonObject);

        console.log('teste');
    }.observes('jsonString')
});

export default ApplicationController;


text:
"""Defines the Transformer model in TF 2.0.

Model paper: https://arxiv.org/pdf/1706.03762.pdf
Transformer model code source: https://github.com/tensorflow/tensor2tensor
"""

from typing import Any, Dict, Union, Iterable

import ml_collections
import tensorflow as tf

from deepconsensus.models import attention_layer
from deepconsensus.models import ffn_layer

class PrePostProcessingWrapper(tf.keras.layers.Layer):
  """Wrapper class that applies layer pre-processing and post-processing."""

  def __init__(self, layer: tf.keras.layers.Layer,
               params: ml_collections.ConfigDict):
    super(PrePostProcessingWrapper, self).__init__()
    self.layer = layer
    self.params = params
    self.postprocess_dropout = params["layer_postprocess_dropout"]

  def build(self, input_shape: Union[tf.TensorShape, Iterable[tf.TensorShape]]):
    # Create normalization layer
    self.layer_norm = tf.keras.layers.LayerNormalization(
        epsilon=1e-6, dtype="float32")
    super(PrePostProcessingWrapper, self).build(input_shape)

  def get_config(self) -> Dict[str, Any]:
    return {
        "params": self.params,
    }

  def call(self, x: tf.Tensor, *args, **kwargs) -> Dict[str, tf.Tensor]:
    """Calls wrapped layer with same parameters."""
    # Preprocessing: apply layer normalization
    training = kwargs["training"]

    y = self.layer_norm(x)

    # Get layer output.
    layer_output = self.layer(y, *args, **kwargs)
    y = layer_output["main_output"]

    # Postprocessing: apply dropout and residual connection
    if training:
      y = tf.nn.dropout(y, rate=self.postprocess_dropout)
    layer_output["main_output"] = x + y
    return layer_output

class EncoderStack(tf.keras.layers.Layer):
  """Transformer encoder stack.

  The encoder stack is made up of N identical layers. Each layer is composed
  of the sublayers:
    1. Self-attention layer
    2. Feedforward network (which is 2 fully-connected layers)
  """

  def __init__(self, params: ml_collections.ConfigDict):
    super(EncoderStack, self).__init__()
    self.params = params
    self.layers = []

  def build(self, input_shape: Union[tf.TensorShape, Iterable[tf.TensorShape]]):
    """Builds the encoder stack."""
    params = self.params
    for _ in range(params["num_hidden_layers"]):
      # Create sublayers for each layer.
      self_attention_layer = attention_layer.SelfAttention(
          params["hidden_size"], params["num_heads"],
          params["attention_dropout"])
      feed_forward_network = ffn_layer.FeedForwardNetwork(
          params["hidden_size"], params["filter_size"], params["relu_dropout"])

      self.layers.append([
          PrePostProcessingWrapper(self_attention_layer, params),
          PrePostProcessingWrapper(feed_forward_network, params)
      ])

    # Create final layer normalization layer.
    self.output_normalization = tf.keras.layers.LayerNormalization(
        epsilon=1e-6, dtype="float32")
    super(EncoderStack, self).build(input_shape)

  def get_config(self) -> Dict[str, Any]:
    return {
        "params": self.params,
    }

  def call(self, encoder_inputs: tf.Tensor, attention_bias: tf.Tensor,
           inputs_padding: tf.Tensor, training: bool) -> Dict[str, tf.Tensor]:
    """Return the output of the encoder layer stacks.

    Args:
      encoder_inputs: tensor with shape [batch_size, input_length, hidden_size]
      attention_bias: bias for the encoder self-attention layer. [batch_size, 1,
        1, input_length]
      inputs_padding: tensor with shape [batch_size, input_length], inputs with
        zero paddings.
      training: boolean, whether in training mode or not.

    Returns:
      Dictionary with the following (key:value) pairs:
        "self_attention_layer_{n}": Attention layer output for every layer in
        the encoder stack with shape [batch_size, input_length, hidden_size].
        "attention_scores_{n}" : Attention map for every layer in the
        encoder stack with shape [batch_size, num_heads, input_length,
        input_length].
        "ffn_layer_{n}": Feedforward network output for every layer in the
        encoder stack with shape [batch_size, input_length, hidden_size].
        "final_output": Final output of the entire encoder stack after
        normalization with shape [batch_size, input_length, hidden_size]. Used
        as input to the fully-connected layer which outputs logits.
    """
    outputs_dict = dict()
    for n, layer in enumerate(self.layers):
      # Run inputs through the sublayers.
      self_attention_layer = layer[0]
      feed_forward_network = layer[1]

      with tf.name_scope("layer_%d" % n):
        with tf.name_scope("self_attention"):
          layer_outputs = self_attention_layer(
              encoder_inputs, attention_bias, training=training)
          encoder_inputs = layer_outputs["main_output"]
          # Add attention layer outputs and attention map scores to outputs.
          outputs_dict[f"self_attention_layer_{n}"] = encoder_inputs
          outputs_dict[f"attention_scores_{n}"] = layer_outputs[
              "attention_scores"]
        with tf.name_scope("ffn"):
          layer_outputs = feed_forward_network(
              encoder_inputs, training=training)
          encoder_inputs = layer_outputs["main_output"]
          # Add output of the feedforward network to outputs.
          outputs_dict[f"ffn_layer_{n}"] = encoder_inputs

    # Add normalized final output of the entire encoder stack to outputs.
    outputs_dict["final_output"] = self.output_normalization(encoder_inputs)
    return outputs_dict


text:
<?php
include_once('/kunden/homepages/0/d643120834/htdocs/config/index.php');
require(ROOT.'inc/conn.php');
$config = new Blog();
$current_page = 0;
$site = $config->getSiteData($config->site);
$site['media']['photos'] = $config->getPhotoAds($site['creator'], 'current-promo',1);
$todays_date = date('Y-m-d');
$result = $conn->query('select * from twitter_data WHERE timestamp LIKE "%'.$todays_date.'%" ORDER BY `id` DESC');
$numb_soms_sent = count($result->fetchAll());

$leads_conversion = new Config();

/* DETECT HOW MANY POSTS CREATED TODAY */
$posted_today = null;
$tp = $config->getPostsByUser(0,1,'admin');
foreach ($tp as $post) {
    $post_date = date('m-d',strtotime($post['submission_date']));
    $todays_date2 = date('m-d');
    if ($post_date===$todays_date2) {
        $posted_today = true;
    }
}
if ($posted_today===true) {
    $status[] = 'BLOGS POSTED TODAY!';
} else {
    $status[] = 'NOT POSTED TODAY!';
}

/* DETECT HOW MANY PROMOS POSTED TO DAY */
$posted_today = null;
$tpr = $config->getPromosByUser('admin',0);
// $config->debug($tpr,1);
foreach ($tpr as $promo) {
    $post_date = date('m-d',strtotime($promo['date_created']));
    $todays_date2 = date('m-d');
    if ($post_date===$todays_date2) {
        $posted_today = true;
    }
}
if ($posted_today===true) {
    $status[] = 'PROMOS CREATED TODAY!';
} else {
    $status[] = 'NO PROMOS CREATED TODAY';

    $status[] = 'ADD NEW PROMO';
}

/* DETECT HOW MANY CLIENTS SIGNED UP TODAY */

/*
 * BUILD SOM ALERTS
 */
$status[] = 'Messages Sent: '.$numb_soms_sent.' / 600';
if ($numb_soms_sent < 600) {
	$status[] = 'Not Enough SOMS Sent.';
	$status[] = 'SOM';
    $status[] = '<button onclick="openScript()" class="btn btn-warning-outline btn-block">
            Open Script
        </button>';
} else {
	$status[] = 'SOM quota met!';
}
/*
 * GET SOM ALERT DATA
 */
$data='

Alerts
';
foreach ($status as $key => $value) {
    $data .= '

         '.$value.'

';
}
$data.='

';

$adminPosts = $config->getPostsByUser(0,20,'admin');

include(ROOT.'inc/connection.php');

// START COUTNING LEADS
$result = mysqli_query($con,"SELECT * FROM leads
		WHERE follow_up_date LIKE '%$todays_date%'
			/*OR follow_up_date='$yesterdays_date'
			OR follow_up_date='$daybefore_date'
			OR follow_up_date='$threedaysback'
			OR follow_up_date='$fourdaysback'
			OR follow_up_date='$fivedaysback'
			/*OR `user_name` = '".$user_name_session."' */
			ORDER BY `id` DESC LIMIT 100");

while($row = mysqli_fetch_assoc($result)) {
	$i = $i;
	$leads[$row['lead_twitter']][] = array('name'=>$row['lead_name'],'count'=>$row['count']);
	$i = $i + 1;
}
if ($leads==NULL) {
	$leads['noneFound'] =  'no leads found';
}
// var_dump($leads);

/*

 * Lead Build Data
 */
$lead_build='

Leads
';

foreach ($leads as $key => $value) {
if ($value!=='no leads found') {
        $status = '';
        if ($value[0]['count']>=3) {
            $count = $value[0]['count'];
            $status = 'status-completed';
        } elseif ($value[0]['count']>=1) {
            $count = $value[0]['count'];
            $status = 'status-backlog';
        } else {
            $count = 0;
            $status = 'status-noticket';
        }

        $lead_build .= '

            [@'.$key.'] ['.count($value).':'.$count.']
            '.$value[0]['name'].'

';
    } else {
        // echo 'No leads found!!';
    }
}
$lead_build.='

';

$number_of_leads = count($leads);
	$min_sales = 100;
	$price = 56;
	// GET PERCENTAGACES
	$sales_progress = round(($number_of_leads / $min_sales) * 100);
	$total_sales 	= number_format($number_of_leads * $price);
	$sales_estimate = $total_sales * 0.1;
	$total_sales_quota	=	number_format($min_sales * $price);

/*
 * GET SOM ALERT DATA
 */
$data.='

Progress
';
// foreach ($status as $key => $value) {
    $data .= '

        0
         '.$sales_progress.'% Completed

';
    $data .= '

        0
         $'.$total_sales.' / $'.$total_sales_quota.' Estimated Revenue

';
    $data .= '

        0
         '.$number_of_leads.' / '.$min_sales.'

';
    $data .= '

        0 ';
    if ($number_of_leads > $min_sales) {
    	$sales_status = 'Sales met!';
    } else {
    	$sales_status = 'Sales not met!';

    }

    $data.=  $sales_status.'

';

$data .= '

        View Clients

';

// }
$data.='

';

// var_dump($leads);
?>

<?php //include(ROOT.'submit/views/db/current_clients.php'); ?>

		<?php echo $data; ?>

    <select class="form-control lead-filter">
        <option value="today">Today</option>
        <option value="yesterday">Yesterday</option>
        <option value="this_month">This Month</option>
    </select>
		<?php echo $lead_build; ?>

Modal title

        <textarea class="form-control lead-response-input" rows="5"></textarea>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary lead-response-trigger">Send Message</button>


text:
//Listing 15.15 Domain entity with secured fields
package ajia.domain;

import javax.persistence.Entity;
import javax.persistence.Table;

import ajia.security.Access;
import ajia.util.DomainEntity;

//import ...

@Entity
@Table(name="products")
public class Product extends DomainEntity {
    private String name;
    private String description;
    @Access("ROLE_SUPERVISOR") private double price;

    //... unchanged from listing A.2

    public Product() {
    }

    public Product(String name, String description, double price) {
        this.name = name;
        this.description = description;
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product: " + name;
    }

    @Override
    public int hashCode() {
        return 31 + ((name == null) ? 0 : name.hashCode());
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Product other = (Product) obj;
        if (name == other.name
           || (name != null && name.equals(other.name))) {
            return true;
        }
        return false;
    }

}


text:
<?php

namespace Fresh\LeboncoinBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AnnonceurType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('pseudo')
            ->add('email')
            ->add('telephone')
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Fresh\LeboncoinBundle\Entity\Annonceur'
        ));
    }
}


text:
using System;
using rename_pcre_encoderNamespace;

public class runme {
  static void Main() {
    SomeWidget w = new SomeWidget();
    w.put_borderWidth(17);
    if ( w.get_borderWidth() != 17 )
      throw new Exception(String.Format("Border with should be 17, not {0}",
                                        w.get_borderWidth()));

    if ( rename_pcre_encoder.StartINSAneAndUNSAvoryTraNSAtlanticRaNSAck() != 42 )
      throw new Exception("Unexpected result of renamed function call");
  }
}


text:
function confirmCB(e) {
    $.label.setText($.inputText.value);
    $.inputText.setValue("");
}

$.index.open();


text:
import io
import os
import sys
import copy
import subprocess
import importlib
from dotenv import load_dotenv
from timeout import timeout

dotenv_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '.env'))
load_dotenv(dotenv_path)
PYTHON_EXE = os.environ.get('PYTHON_EXE')

# might bring this back next year, dont know yet...

# def check_console(test_file, q_name, args, answers):

#     proc = subprocess.Popen([PYTHON_EXE, '-u', os.path.abspath(os.path.join(os.path.dirname(__file__), '..', test_file))], stdout=subprocess.PIPE)
#     results = []
#     messages = []
#     status  = 'Successful!'
#     anss = []
#     for i, line in enumerate(proc.stdout):
#         ans = line.strip('\n')
#         anss.append(ans)
#         if ans == '':
#             break
#         else:
#             if int(ans) == answers[i]:
#                 results.append(True)
#                 messages.append('
Nice one! Was expecting {0} and got {1}
'.format(answers[i], ans))
#             else:
#                 results.append(False)
#                 messages.append('
Hmm not quite. Was expecting {0} but got {1}
'.format(answers[i], ans))
#     if False in results:
#         status = 'Unsuccessful'

#     return {'q_id': q_id, 'question_name': q_name,'answers': anss, 'status': status,'results':results, 'messages':messages}

def check_functions(file_path, function_name, args, answers, time_out, no_unpack=False, nested=False, unbracket=False):

    result = False
    try:

        # get the function out of the file submitted
        filename = os.path.basename(file_path).split('.')[0]
        function = getattr(importlib.import_module('uploads.{0}'.format(filename)), function_name)
        func = timeout(timeout=time_out)(function)

        # make a copy to submit to function incase argument is mutatable
        args_in = copy.copy(args)

        # check the number of args and call function accrodingly
        if len(args_in) == 0:
            ans = func()
        else:
            if no_unpack:
                ans = func(args_in)
            else:
                ans = func(*args_in)

        # if answer is within an array
        if nested:
            if ans == answers:
                result = True
        else:
            if [ans] == answers:
                result = True

        # remove bracktes for display in markerbot
        if unbracket:
            answers = answers[0]

        return {'input': args, 'result': result, 'output': ans, 'expected': answers}

    except Exception as e:
        return {'input': args, 'result': result, 'output': e.message, 'expected': answers}


text: supervisor index.js


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

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.

=cut

package Bio::EnsEMBL::Analysis::Hive::Config::ShortncRNA;

use strict;
use warnings;
use File::Spec::Functions;

use Bio::EnsEMBL::Analysis::Tools::Utilities qw(get_analysis_settings);
use Bio::EnsEMBL::Hive::PipeConfig::HiveGeneric_conf;
use base ('Bio::EnsEMBL::Analysis::Hive::Config::HiveBaseConfig_conf');

sub default_options {
  my ($self) = @_;

  return {
    # inherit other stuff from the base class
    %{ $self->SUPER::default_options() },

######################################################
#
# Variable settings- You change these!!!
#
######################################################
########################
# Misc setup info
########################
    dbowner                   => '' || $ENV{EHIVE_USER} || $ENV{USER},
    pipeline_name             => '' || $self->o('production_name').'_'.$self->o('ensembl_release'),
    user_r                    => '', # read only db user
    user                      => '', # write db user
    password                  => '', # password for write db user
    server_set                => '', # What server set to user, e.g. set1
    pipe_db_host              => '', # host for pipe db
    databases_host            => '', # host for general output dbs
    dna_db_host               => '', # host for dna db
    pipe_db_port              => '', # port for pipeline host
    databases_port            => '', # port for general output db host
    dna_db_port               => '', # port for dna db host
    repbase_logic_name        => '', # repbase logic name i.e. repeatmask_repbase_XXXX, ONLY FILL THE XXXX BIT HERE!!! e.g primates
    release_number            => '' || $self->o('ensembl_release'),
    species_name              => '', # e.g. mus_musculus
    production_name           => '', # usually the same as species name but currently needs to be a unique entry for the production db, used in all core-like db names
    dbname_accession          => '', # This is the assembly accession without [._] and all lower case, i.e gca001857705v1
    taxon_id                  => '', # should be in the assembly report file
    uniprot_set               => '', # e.g. mammals_basic, check UniProtCladeDownloadStatic.pm module in hive config dir for suitable set,
    sanity_set                => '', # sanity checks
    output_path               => '', # Lustre output dir. This will be the primary dir to house the assembly info and various things from analyses

########################
## Small ncRNAs params
#########################
    mirBase_fasta             => 'all_mirnas.fa', # What mirBase file to use. It is currently best to use on with the most appropriate set for your species
    rfc_scaler                => 'filter_dafs_rfc_scaler_human.pkl',
    rfc_model                 => 'filter_dafs_rfc_model_human.pkl',

    # Clade-based filtering on rfam accessions
    # Rfam db details should stay constant but check periodically
    rfam_user => 'rfamro',
    rfam_dbname => 'Rfam',
    rfam_host => 'mysql-rfam-public.ebi.ac.uk',
    rfam_port => 4497,

    rfam_path => catfile($self->o('base_blast_db_path'), 'ncrna', 'Rfam_14.0'),
    rfam_seeds => catfile($self->o('rfam_path'), 'Rfam.seed'),
    rfam_cm => catfile($self->o('rfam_path'), 'Rfam.cm'),
    filtered_rfam_cm => catfile($self->o('ncrna_dir'), 'Rfam.cm'),
    clade => $self->o('repbase_logic_name'),

########################
# Pipe and ref db info
########################
    pipe_db_name                  => $self->o('dbowner').'_'.$self->o('dbname_accession').'_pipe_'.$self->o('release_number'),
    dna_db_name                   => $self->o('dbowner').'_'.$self->o('dbname_accession').'_core_'.$self->o('release_number'),

    ncrna_db_host                => $self->o('databases_host'),
    ncrna_db_port                => $self->o('databases_port'),
    ncrna_db_name                  => $self->o('dbowner').'_'.$self->o('dbname_accession').'_ncrna_'.$self->o('release_number'),

    # This is used for the ensembl_production and the ncbi_taxonomy databases
    ensembl_release              => $ENV{ENSEMBL_RELEASE}, # this is the current release version on staging to be able to get the correct database

    databases_to_delete => ['ncrna_db'],

########################
# BLAST db paths
########################
    base_blast_db_path        => $ENV{BLASTDB_DIR},
    ncrna_blast_path          => catdir($self->o('base_blast_db_path'), 'ncrna', 'ncrna_2016_05'),
    mirna_blast_path          => catdir($self->o('base_blast_db_path'), 'ncrna', 'mirbase_22'),

######################################################
#
# Mostly constant settings
#
######################################################

    genome_dumps                  => catdir($self->o('output_path'), 'genome_dumps'),
    # This one is used in replacement of the dna table in the core db, so where analyses override slice->seq. Has simple headers with just the seq_region name. Also used by bwa in the RNA-seq analyses. Not masked
    faidx_genome_file             => catfile($self->o('genome_dumps'), $self->o('species_name').'_toplevel.fa'),
    use_genome_flatfile           => '1',# This will read sequence where possible from a dumped flatfile instead of the core db

    ncrna_dir => catdir($self->o('output_path'), 'ncrna'),

    ensembl_analysis_script           => catdir($self->o('enscode_root_dir'), 'ensembl-analysis', 'scripts'),
    sncrna_analysis_script             => catdir($self->o('ensembl_analysis_script'), 'genebuild', 'sncrna'),

########################
# Executable paths
########################
    blast_type => 'ncbi', # It can be 'ncbi', 'wu', or 'legacy_ncbi'
    blastn_exe_path => catfile($self->o('binary_base'), 'blastn'),
    cmsearch_exe_path    => catfile($self->o('binary_base'), 'cmsearch'), # #'opt', 'infernal10', 'bin', 'cmsearch'),

########################
# Misc setup info
########################
    repeatmasker_engine       => 'crossmatch',
    masking_timer_long        => '5h',
    masking_timer_short       => '2h',

# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# No option below this mark should be modified
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

########################
# db info
########################
    ncrna_db => {
      -dbname => $self->o('ncrna_db_name'),
      -host   => $self->o('ncrna_db_host'),
      -port   => $self->o('ncrna_db_port'),
      -user   => $self->o('user'),
      -pass   => $self->o('password'),
      -driver => $self->o('hive_driver'),
    },
  };
}

sub pipeline_wide_parameters {
  my ($self) = @_;

  return {
    %{$self->SUPER::pipeline_wide_parameters},
    use_genome_flatfile => $self->o('use_genome_flatfile'),
    genome_file          => $self->o('faidx_genome_file'),
  }
}

sub pipeline_create_commands {
  my ($self) = @_;

  return [

    # inheriting database and hive tables' creation
    @{ $self->SUPER::pipeline_create_commands },

    'mkdir -p ' . $self->o('ncrna_dir'),
  ];
}

sub pipeline_analyses {
  my ($self) = @_;

  return [
    {
      -logic_name => 'create_ncrna_db',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveCreateDatabase',
      -parameters => {
        source_db => $self->o('dna_db'),
        target_db => $self->o('ncrna_db'),
        create_type => 'clone',
      },
      -rc_name    => 'default',
      -input_ids  => [{}],
      -flow_into => {
        '1->A' => ['dump_repeats', 'fetch_rfam_accessions'],
        'A->1' => ['create_small_rna_slice_ids'],
      },
    },

    {
      -logic_name => 'dump_repeats',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => 'perl '.catfile($self->o('sncrna_analysis_script'), 'repeats_dump.pl').' '.
          $self->o('dna_db_name'). ' ' .
          $self->o('dna_db_host') . ' ' .
          $self->o('dna_db_port') . ' ' .
          $self->o('user_r') . ' ' .
          $self->o('ncrna_dir').' blastmirna',
      },
      -rc_name => '6GB',
    },

    {
      -logic_name => 'fetch_rfam_accessions',
      -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => 'perl ' . catfile($self->o('sncrna_analysis_script'), 'fetch_rfam_accessions.pl') .
          ' -h ' . $self->o('rfam_host') .
          ' -u ' . $self->o('rfam_user') .
          ' -p ' . $self->o('rfam_port') .
          ' -d ' . $self->o('rfam_dbname') .
          ' -c ' . $self->o('clade') .
          ' -o ' . $self->o('ncrna_dir'),
      },
      -rc_name => 'default',
      -flow_into => { '1' => 'extract_rfam_cm'},
    },

    {
      -logic_name => 'extract_rfam_cm',
      -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => 'perl '.catfile($self->o('sncrna_analysis_script'), 'filter_cm.pl').
          ' '.$self->o('rfam_cm').
          ' '.catfile($self->o('ncrna_dir'), 'accessions.txt').
          ' '.$self->o('filtered_rfam_cm'),
      },
      -rc_name => 'filter',
    },

    {
      -logic_name => 'create_small_rna_slice_ids',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveSubmitAnalysis',
      -parameters => {
        coord_system_name => 'toplevel',
        iid_type => 'slice',
        slice_size => 1000000,
        top_level => 1,
        target_db => $self->o('dna_db'),
        batch_slice_ids => 1,
        batch_target_size => 2000000,
      },
      -flow_into => {
        '2->A' => ['mirna_blast','run_cmsearch'],
        'A->1' => ['filter_ncrnas'],
      },
      -rc_name    => 'default',
    },

    {
      -logic_name => 'run_cmsearch',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveCMSearch',
      -parameters => {
        output_db => $self->o('ncrna_db'),
        dna_db => $self->o('dna_db'),
        logic_name => 'ncrna',
        module     => 'HiveCMSearch',
        cmsearch_exe_path => $self->o('cmsearch_exe_path'),
        rfam_seeds => $self->o('rfam_seeds'),
        rfam_cm => $self->o('filtered_rfam_cm'),
        blast_db_dir_path => $self->o('ncrna_blast_path').'/',
        output_dir => $self->o('ncrna_dir'),
      },
      -hive_capacity => 900,
      -rc_name    => '5GB',
      -flow_into => {
        '-1' => 'run_cmsearch_highmem',
        '-2' => 'run_cmsearch_highmem'},
    },

    {
      -logic_name => 'run_cmsearch_highmem',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveCMSearch',
      -parameters => {
        output_db => $self->o('ncrna_db'),
        dna_db => $self->o('dna_db'),
        logic_name => 'ncrna',
        module     => 'HiveCMSearch',
        cmsearch_exe_path => $self->o('cmsearch_exe_path'),
        rfam_seeds => $self->o('rfam_seeds'),
        rfam_cm => $self->o('filtered_rfam_cm'),
        blast_db_dir_path => $self->o('ncrna_blast_path').'/',
        output_dir => $self->o('ncrna_dir'),
      },
      -hive_capacity => 900,
      -rc_name    => '10GB',
    },

    {
      -logic_name => 'mirna_blast',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveBlastmiRNA',
      -parameters => {
        output_db => $self->o('ncrna_db'),
        dna_db => $self->o('dna_db'),
        logic_name => 'blastmirna',
        module     => 'HiveBlastmiRNA',
        blast_db_path => catfile($self->o('mirna_blast_path'), $self->o('mirBase_fasta')),
        blast_exe_path => $self->o('blastn_exe_path'),
        commandline_params => ' -num_threads 3 ',
        %{get_analysis_settings('Bio::EnsEMBL::Analysis::Hive::Config::BlastStatic','BlastmiRBase', {BLAST_PARAMS => {type => $self->o('blast_type')}})},
        timer => '2h',
      },
      -flow_into => {
        '-1' => ['rebatch_mirna'],
        '-2' => ['rebatch_mirna'],
      },
      -hive_capacity => $self->hive_capacity_classes->{'hc_high'},
      -rc_name    => 'blast',
    },

    {
      -logic_name => 'rebatch_mirna',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveSubmitAnalysis',
      -parameters => {
        target_db => $self->o('dna_db'),
        iid_type => 'rebatch_and_resize_slices',
        slice_size => 100000,
        batch_target_size => 100000,
      },
      -flow_into => {
        '2' => ['mirna_blast_retry'],
      },
      -rc_name    => 'default',
      -can_be_empty  => 1,
    },

    {
      -logic_name => 'mirna_blast_retry',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveBlastmiRNA',
      -parameters => {
        output_db => $self->o('ncrna_db'),
        dna_db => $self->o('dna_db'),
        logic_name => 'blastmirna',
        module     => 'HiveBlastmiRNA',
        blast_db_path => catfile($self->o('mirna_blast_path'), $self->o('mirBase_fasta')),
        blast_exe_path => $self->o('blastn_exe_path'),
        commandline_params => ' -num_threads 3 ',
        %{get_analysis_settings('Bio::EnsEMBL::Analysis::Hive::Config::BlastStatic','BlastmiRBase', {BLAST_PARAMS => {type => $self->o('blast_type')}})},
        timer => '1h',
      },
      -flow_into => {
        '-1' => ['failed_mirna_blast_job'],
        '-2' => ['failed_mirna_blast_job'],
      },
      -hive_capacity => $self->hive_capacity_classes->{'hc_high'},
      -rc_name    => 'blast_retry',
    },

    {
      -logic_name => 'failed_mirna_blast_job',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::Dummy',
      -parameters => {},
      -rc_name          => 'default',
      -can_be_empty  => 1,
    },

    {
      -logic_name => 'filter_ncrnas',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveFilterncRNAs',
      -parameters => {
        output_db => $self->o('ncrna_db'),
        dna_db => $self->o('dna_db'),
        logic_name => 'filter_ncrnas',
        module     => 'HiveFilterncRNAs',
      },
      -rc_name    => 'filter',
      -flow_into => {
        '2->A' => ['run_mirna'],
        'A->1' => ['concat_rnafold_result'],
      },
    },

    {
      -logic_name => 'run_mirna',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HivemiRNA',
      -parameters => {
        output_db => $self->o('ncrna_db'),
        dna_db => $self->o('dna_db'),
        logic_name => 'ncrna',
        module     => 'HivemiRNA',
        blast_db_dir_path => catfile($self->o('mirna_blast_path'), 'all_mirnas.embl'),
        output_dir => $self->o('ncrna_dir'),
      },
      -batch_size => 20,
      -hive_capacity => $self->hive_capacity_classes->{'hc_high'},
      -rc_name    => 'filter',
    },

    {
      -logic_name => 'concat_rnafold_result',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => 'cat #data_file_pattern# > #output_file#',
        data_file_pattern => catfile($self->o('ncrna_dir'), 'rna_fold_*.part'),
        output_file => catfile($self->o('ncrna_dir'), 'rna_fold_results.txt'),
      },
      -rc_name   => 'filter',
      -flow_into => {
        1 => 'fan_dump_features',
      },
    },

    {
      -logic_name => 'fan_dump_features',
      -module => 'Bio::EnsEMBL::Hive::RunnableDB::Dummy',
      -parameters => {
      },
      -rc_name => 'default',
      -flow_into  => {
        1 => WHEN(
            '-e "'.catfile($self->o('ncrna_dir'),'rna_fold_results.txt').'"' => ['dump_features']
            ),
      },
    },

    {
      -logic_name => 'dump_features',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => 'perl '.catfile($self->o('sncrna_analysis_script'), 'dump_prefilter_features.pl')
          .' '.$self->o('ncrna_db_name')
          .' '.$self->o('ncrna_db_host')
          .' '.$self->o('ncrna_db_port')
          .' '.$self->o('user_r')
          .' '.$self->o('ncrna_dir')
          .' blastmirna',
      },
      -rc_name   => 'filter',
      -flow_into => {
        1 => 'dump_annotated_dafs',
      },
    },

    {
      -logic_name => 'dump_annotated_dafs',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => "annotateBed -i #bedfile_dafs# -files #repeats_file# | bedtools nuc -fi #genome_file# -bed stdin -s | cut -f1-11,13 | grep -v '#' > #output_file# ",
        output_file => catfile($self->o('ncrna_dir'), 'annotated_dafs.tsv'),
        bedfile_dafs => catfile($self->o('ncrna_dir'), 'blastmirna_dafs.bed'),
        repeats_file => catfile($self->o('ncrna_dir'), 'repeats.bed'),
        genome_file => $self->o('faidx_genome_file'),
      },
      -rc_name   => 'filter',
      -flow_into => {
        1 => 'filter_mirnas'
      },
    },

    {
      -logic_name => 'filter_mirnas',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => 'PYENV_VERSION="#pyenv_virtualenv#" python '.catfile($self->o('sncrna_analysis_script'), 'FilterDafs.py')
          .' '.catfile($self->o('mirna_blast_path'), 'rfc_filters', $self->o('rfc_model'))
          .' '.catfile($self->o('mirna_blast_path'), 'rfc_filters', $self->o('rfc_scaler'))
          .' '.$self->o('ncrna_dir')
          .' '.catfile($self->o('ncrna_dir'), 'annotated_dafs.tsv')
          .' '.catfile($self->o('ncrna_dir'), 'rna_fold_results.txt')
          .' '.catfile($self->o('ncrna_dir'), 'identified_mirnas.bed')
          .' '.catfile($self->o('ncrna_dir'), 'mirnas_to_delete.txt'),
        pyenv_virtualenv => 'genebuild-mirna',
      },
      -rc_name   => 'filter',
      -flow_into => {
        1 => 'delete_flagged_mirnas',
      },
    },

    {
      -logic_name => 'delete_flagged_mirnas',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => 'perl '.catfile($self->o('ensembl_analysis_script'), 'genebuild', 'delete_genes.pl')
          .' -dbhost #expr(#target_db#->{-host})expr#'
          .' -dbport #expr(#target_db#->{-port})expr#'
          .' -dbuser #expr(#target_db#->{-user})expr#'
          .' -dbpass #expr(#target_db#->{-pass})expr#'
          .' -dbname #expr(#target_db#->{-dbname})expr#'
          .' -idfile '.catfile($self->o('ncrna_dir'), 'mirnas_to_delete.txt'),
        target_db => $self->o('ncrna_db'),
      },
      -rc_name   => 'filter',
      -flow_into => {
        1 => 'ncrna_sanity_checks',
      },
    },

    {
      -logic_name => 'ncrna_sanity_checks',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAnalysisSanityCheck',
      -parameters => {
        target_db => $self->o('ncrna_db'),
        sanity_check_type => 'gene_db_checks',
        min_allowed_feature_counts => get_analysis_settings('Bio::EnsEMBL::Analysis::Hive::Config::SanityChecksStatic',
            'gene_db_checks')->{$self->o('sanity_set')}->{'ncrna'},
      },
      -rc_name    => '4GB',
    },
  ];
}

sub resource_classes {
  my $self = shift;

  return {
    'default' => { LSF => $self->lsf_resource_builder('production', 900)},
    '4GB' => { LSF => $self->lsf_resource_builder('production', 4000)},
    '5GB' => { LSF => $self->lsf_resource_builder('production', 5000)},
    '6GB' => { LSF => $self->lsf_resource_builder('production', 6000)},
    '10GB' => { LSF => $self->lsf_resource_builder('production', 10000)},
    'blast' => { LSF => $self->lsf_resource_builder('production', 2900, undef, undef, 3)},
    'blast_retry' => { LSF => $self->lsf_resource_builder('production', 5900, undef, undef, 3)},
    'filter' => { LSF => $self->lsf_resource_builder('production', 4900)},
  }
}

1;


text:
import {Benchmark} from './types.js';

export {Size} from './types.js';

const benchmarks: Benchmark[] = [];

export function benchmark(spec: Benchmark) {
  benchmarks.push(spec);
}

export function getBenchmarks() {
  return benchmarks;
}


text:
package com.crawljax.core.configuration;

import org.apache.commons.configuration.PropertiesConfiguration;

/**
 * Reader for InputSpecification. For internal use only!
 *
 * @author Danny
 * @version $Id$
 */
public class InputSpecificationReader {

	private InputSpecification inputSpecification;

	/**
	 * Wrap around inputSpecification.
	 *
	 * @param inputSpecification
	 *            The inputSpecification to wrap around.
	 */
	public InputSpecificationReader(InputSpecification inputSpecification) {
		this.inputSpecification = inputSpecification;
	}

	/**
	 * @return The configuration of the inputspecification.
	 */
	public PropertiesConfiguration getConfiguration() {
		return inputSpecification.getConfiguration();
	}

}


text:
if defined?(Vendorize)
  #-----------------------------------------
  # This code only runs when running with
  # Vendorize in place, not when just running
  # with vendorized files
  #-----------------------------------------
  puts "VENDORIZING - running #{__FILE__}"
end

unless defined?(Vendorize)
  #-----------------------------------------
  # This code only runs when running
  # with vendorized files
  #-----------------------------------------
  puts "Booting with #{__FILE__}"

  module Kernel
    # With an IronRuby embedded app 'z.rb', IR will sometimes
    # put a full path of the form c:/x/y/z.rb in the
    # caller list. Sinatra doesn't see z.rb as the main
    # app in that case, so doesn't start. This patch
    # solves the issue. It has to come before the
    # require sinatra
    alias ir_sinatra_old_caller caller
    def caller(num = 0)
      re_main = Regexp.new(".*#{$0}:(\\d+.*)")
      re_thisfile = Regexp.new("^#{__FILE__}:")
      callers = ir_sinatra_old_caller(num)
      callers.reject{|f| f =~ re_thisfile}.map{|f| f.gsub(re_main, $0 + ':\1')}
    end
  end
end

# Fix for IronRuby 1.0 running Sinatra 'straight'
# See http://ironruby.codeplex.com/workitem/3895 and
# http://gist.github.com/397707#file_sinatra_static_file_patch.rb.
module Sinatra
  module Helpers
    class WorkingStaticFile
      attr_accessor :file

      def initialize(path, mode)
        self.file = File.open(path, mode)
      end

      def to_path
        return file.path
      end

      def each
        file.rewind
        while buf = file.read(8192)
          yield buf
        end
      end
    end

    class StaticFile < File
      def self.open(path, mode)
        WorkingStaticFile.new(path, mode)
      end
    end
  end
end


text:
<?php slot('title', __('Manage statuses')) ?>

  <?php include_partial('idProject/sub_menu_settings')?>

    <?php echo __('Statuses'); ?>
    <a id="add-log-time"class="button block-green medium-round" href="<?php echo url_for('@new_status') ?>">Add

  <?php if ($sf_user->hasFlash('notice')): ?>

      <?php echo __($sf_user->getFlash('notice')); ?>

  <?php endif;?>

  <?php if ($sf_user->hasFlash('error')): ?>

      <?php echo __($sf_user->getFlash('error')); ?>

  <?php endif;?>

          <?php echo __('Id') ?>
          <?php echo __('Name') ?>
          <?php echo __('Status type') ?>
          <?php echo __('Actions') ?>
          <?php echo __('Order Priorities') ?>

        <?php if ($status_list->count() !== false && $status_list->count() == 0): ?>

            <?php echo __('No Results') ?>

        <?php else: ?>
          <?php $count = count($status_list); ?>
          <?php $index = 1; ?>
          <?php foreach ($status_list as $status): ?>
          <tr class="sortable" id="status_<?php echo $status->getId() ?>" name="status_<?php echo $status->getId() ?>">

              <a href="<?php echo url_for('@edit_status?id='.$status->getId()) ?>"><?php echo $status->getId() ?>
              <?php echo $status->getName() ?>
              <?php echo $status->getStatusType() ?>
              <a href="<?php echo url_for('@edit_status?id='.$status->getId()) ?>" onClick="window.location = $(this).attr('href'); return false;" ><?php echo __('Edit') ?> | <?php echo link_to(__('Delete'), '@delete_status?id='.$status->getId(), array('onclick' => "var answer = confirm('".__("Do you really want to delete this status?")."'); if (answer) { window.location = \$(this).attr('href'); }; return false;")) ?>

<?php echo __('Drag me up and down'); ?>

                <?php if ($index > 1): ?>
                  <form action="<?php echo url_for("idStatus/orderStatus") ?>" method="post">
                    <input type="hidden" name="position" value="<?php echo $status->position ?>" />
                    <input type="hidden" name="move" value="up" />
                    <input type="submit" value="Up" class="button" />
                  </form>
                <?php endif; ?>

                <?php if ($index < $count): ?>
                  <form action="<?php echo url_for("idStatus/orderStatus") ?>" method="post">
                    <input type="hidden" name="position" value="<?php echo $status->position ?>" />
                    <input type="hidden" name="move" value="down" />
                    <input type="submit" value="Down" class="button" />
                  </form>
                <?php endif; ?>

            <?php $index++; ?>
          <?php endforeach; ?>
        <?php endif; ?>


text:
package org.spongepowered.common.data.processor.data.block;

import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.block.ImmutableMoistureData;
import org.spongepowered.api.data.manipulator.mutable.block.MoistureData;
import org.spongepowered.api.data.value.mutable.MutableBoundedValue;
import org.spongepowered.common.data.manipulator.mutable.block.SpongeMoistureData;
import org.spongepowered.common.data.processor.common.AbstractBlockOnlyDataProcessor;

public class MoistureDataProcessor extends AbstractBlockOnlyDataProcessor<Integer, MutableBoundedValue<Integer>, MoistureData, ImmutableMoistureData> {

    public MoistureDataProcessor() {
        super(Keys.MOISTURE);
    }

    @Override
    protected Integer getDefaultValue() {
        return 0;
    }

    @Override
    protected MoistureData createManipulator() {
        return new SpongeMoistureData(0, 0, 7);
    }
}


text:
<TITLE>Review for Scary Movie (2000)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Scary Movie (2000)

reviewed by
Shannon Patrick Sullivan

SCARY MOVIE (2000) / ***

Directed by Keenen Ivory Wayans. Screenplay by Phil Beauman, Jason
Friedberg, Buddy Johnson, Aaron Seltzer, Marlon Wayans, Shawn Wayans.
Starring Anna Faris, Marlon Wayans, Regina Hall. Running time: 86 minutes.
Rated AA for mature subject matter and offensive language by the MFCB.
Reviewed on July 7th, 2000.

By SHANNON PATRICK SULLIVAN

How do you review a film like "Scary Movie"? Certainly not on the basis of
plot. The "story" of a spoof is usually just a framework for gags -- to
assess it on that criterion would be like judging a dress on the quality
of the hanger. Acting isn't really all that important either, as long as
the performers possess a certain amount of charisma and some notion of
comic timing. Direction? Virtually irrelevant. Cinematography? Get real.

No, all that matters in deciding whether or not "Scary Movie" is any good
are the laughs. And "Scary Movie" is the first parody I've seen in years
that has laughs in droves. But fair warning first: I'm a big fan of the
"Naked Gun" movies. I enjoyed "Spaceballs". If your sense of humor runs
contrary to my own, this review likely won't apply much to you.

"Scary Movie" started life as two separate screenplays -- "Scream If You
Know What I Did Last Halloween" and "Last Summer I Screamed Because Friday
The 13th Fell On Halloween" -- which were merged into one by director
Keenen Ivory Wayans. Ironically, the final moniker was a working title for
"Scream", the progenitor of the current crop of teen-oriented slasher
films. If you haven't already guessed, "Scary Movie" is a pastiche
of this whole genre. If you've been avoiding these sorts of pictures, you
might want to give this one a pass too, as you might not get many of the
jokes.

The storyline of "Scary Movie" broadly follows the plot of "Scream", with
elements of other films (notably "Scream 2" and "I Know What You Did Last
Summer") thrown in for good measure. We again start off with a Big Star
making popcorn. In "Scream" it was Drew Barrymore (playing "Casey
Becker"), here it's Carmen Electra (playing "Drew Becker", wink wink). The
phone rings, and sure enough it's a serial killer on the other line,
wearing the same Ghostface get-up as in "Scream". The voice on the phone
wants to know what the noise is. Carmen explains she just farted. The
killer was referring to the popcorn.

Soon Carmen is racing through the house and across her lawn. She comes to
a signpost with arrows reading "Safety" and "Death" pointing in opposite
directions. You can probably guess the rest. The movie plays out
predictably from there, as teens are stalked and slain by the masked
villain -- or is it villains? But, really, who cares about the story?
It barely even makes sense, and the ending is particularly incredulous.

What is important is the way "Scary Movie" subverts its source material,
and this it does very well. The "Father Death" mask, for instance, has
gained the miraculous ability to reflect its owner's mood, generating some
bizarre visuals when the killer is toquing up. Toward the end, the(?)
murderer does a terrific imitation of Matthew Lillard, one of "Scream"'s
homicidal teenagers.

"Scary Movie" doesn't just target the slasher genre, either. Everything
from "The Matrix" to "Dawson's Creek" is up for grabs here, and there are
some great send-ups of human behaviour. One of my favourite scenes has
black actress Regina Hall attending a showing of "Shakespeare In Love". In
a terrific pastiche of rude moviegoers (and, in particular, the reputation
African-Americans have of talking back to the screen), Hall just doesn't
stop chattering. She even talks on her cell phone, loudly, to the disgust
of the all-white, upper-middle-class crowd. Ghostface slinks into the
audience to stab Hall, but the audience gets to her first, pulling out
their own weapons. "This is for 'Schindler's List'!" exclaims a
Hassidic Jew. You'll have to hear for yourself what film Hall ruined for
the Pope.

(When I saw "Scary Movie", there was a moron waving a laser pointer across
the screen during certain scenes -- the first time I've encountered this
particular brand of rudeness at a local theatre. Intriguingly, they
stopped doing it after the scene I've just described. Coincidence?)

Not all the jokes are winners, though, and "Scary Movie" is hamstrung by
following the plot of "Scream" a little too closely; greater variation
would have made for a funnier, more dynamic film. Some of the humor is
rather tired -- the gag of giving the characters cutesy, referential names
("Buffy" Gilmore) was even done already in "Scream 3". And sometimes
"Scary Movie" just doesn't know when enough is enough, like the running
gag about Ray (Shawn Wayans) being a closet homosexual.

Furthermore, whereas the truly great spoofs set you up with an obvious
joke, then knock you down by taking it one step further, "Scary Movie" is
often content to go only halfway. A parody of the confession scene from
"The Blair Witch Project", for example, is an awful lot like every other
"Blair Witch" parody of the past year.

No doubt the most controversial aspect of "Scary Movie" will be the sheer
explicitness of many jokes. Remember two years ago, when the "franks and
beans" scene in "There's Something About Mary" was considered
groundbreaking? Well, there's a "franks and beans" scene about every
fifteen minutes here, although for the most part they're pretty amusing,
fortunately. Consequently, parents may want to be wary of letting younger
children attend "Scary Movie". It strikes me as a movie for strictly high
school age at minimum, and even that might be pushing it.

Amongst the cast, the only real standout is newcomer Anna Faris, playing
Sidney -- er, Cindy Campbell, succeeding impressively at portraying the
virginal heroine while uttering and engaging in sheer filth. It's almost
eerie. Otherwise, the castmembers are basically just vehicles for the
jokes. There aren't characters here, just ciphers and cliches.

Yes indeed, "Scary Movie" is plotless, crude, and possessed of mostly
marginal performances -- all the things film critics are supposed to
abhor. But did I laugh my ass off anyway? You bet I did. Do I recommend
"Scary Movie"? God help me, yes.

Copyright © 2000 Shannon Patrick Sullivan.
Archived at The Popcorn Gallery,
  http://www.physics.mun.ca/~sps/movies/ScaryMovie.html

  _______________________________________________________________________
 / Shannon Patrick Sullivan  | "We are all in the gutter, but some of us \
|       shannon@mun.ca       |  are looking at the stars." - Oscar Wilde |
 \___________________________|__________________________________________/
  | Popcorn Gallery Movie Reviews    www.physics.mun.ca/~sps/movies.html |
  | Doctor Who: A Brief History of Time (Travel)            /drwho.html  |

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text: require 'dummy_app/init'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpClassLibrary
{
    public class Class1
    {
    }
}


text:
/*!
 * @file vxbase.h
 * @brief Contains base types for Visual Experience Engine which are not graphics-related.
 *
 * These classes support serializable objects, event management and infrastructure
 * for loading of files from the web.
 *
 * @see vcore
 * @author Nola Donato
 *
 */
#pragma once

#include "vcore/vcore.h"

namespace Vixen
{
	typedef	intptr	Window;
};

#include "base/vxcol.h"
#include "base/vxcol.inl"
#include "base/vxobj.h"
#include "base/vxarray.h"
#include "base/vxdict.h"
#include "base/vxgroup.h"
#include "base/vxmess.h"
#include "base/vxweakref.h"
#include "base/vxarray.inl"
#include "base/vxevent.h"
#include "base/vxevent.inl"
#include "base/vxobj.inl"
#include "base/vxmess.inl"
#include "base/vxweakref.inl"
#include "base/vxfile.h"
#include "base/vxload.h"
#include "base/vxworld.h"
#include "base/vxbitmap.h"
#include "base/vxmath.h"
#include "base/vxmatrix.h"
#include "base/vxmath.inl"
#include "base/vxmatrix.inl"
#include "base/vxbox.h"
#include "base/vxbox.inl"
#include "base/vxsphere.h"


text:
<!doctype html>

  <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <meta name="author" content="Haotian WU">

    <meta name="description" content="This is my first blog after I established this site using Hexo and random.Here are some tests for Hexo:
Code Test:1234$ hexo clean$ hexo generate$ hexo server$ hexo deploy
Mathjax Test:$$\sum_{i=1}...">

  <title>Hello World [ tripleday ]</title>

    <link rel="shortcut icon" href="/favicon.ico">

  <link rel="stylesheet" href="/css/random.css">
<link rel="stylesheet" href="/css/vegas.min.css">
<link rel="stylesheet" href="/css/highlight-railscasts.css">
<link rel="stylesheet" href="/css/jquery.fancybox.css">
<link rel="stylesheet" href="/css/iconfont/iconfont.css">
<link rel="stylesheet" href="/css/jquery.fancybox-thumbs.css">
<link rel="stylesheet" href="/css/plyr.css">

        CentOS 6.5 下scrapy与ghost.py的安装干货

tripleday

Home

Archives

Tags

Categories

About

        <button>Menu</button>

Hello World

      Created at 2016-06-12

        Updated at 2018-05-17

      Category

        Site Est

      Tag

        English

          /

        Hexo

This is my first blog after I established this site using Hexo and random.
Here are some tests for Hexo:

Code Test:

1
2
3
4

$ hexo clean
$ hexo generate
$ hexo server
$ hexo deploy

Mathjax Test:

$$\sum_{i=1}^n a_i=0$$

$$
\begin{eqnarray}
f(x_1,x_2,\ldots,x_n) = x_1^2 + x_2^2 + \cdots + x_n^2
\end{eqnarray}
$$

$$
\begin{eqnarray}
\nabla\cdot\vec{E} &=& \frac{\rho}{\epsilon_0} \\
\nabla\cdot\vec{B} &=& 0 \\
\nabla\times\vec{E} &=& -\frac{\partial B}{\partial t} \\
\nabla\times\vec{B} &=& \mu_0\left(\vec{J}+\epsilon_0\frac{\partial E}{\partial t} \right)
\end{eqnarray}
$$

PDF Test:

    <embed src="http://tripleday.cn/uploads/pdf/Clean%20Code.pdf" width="100%" height="550" type="application/pdf">

iFrame Test:

Picture Test:

Youtube Test:

Youku Test:

  <button class="btn-hide-toc btn-hide-toc-show" style="display: none" onclick="TOCToggle()">Show TOC</button>
  <button class="btn-hide-toc btn-hide-toc-hide" onclick="TOCToggle()">Hide TOC</button>

Table of Content

Code Test:

Mathjax Test:

PDF Test:

iFrame Test:

Picture Test:

Youtube Test:

Youku Test:

    ← Prev post CentOS 6.5 下scrapy与ghost.py的安装干货

      Site by Haotian WU using
      Hexo & Random

Please enable JavaScript to view the comments powered by Disqus.

Life is short, you need Python.

          

          

          

          

          

Hide


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Datadog;

namespace Azure.ResourceManager.Datadog.Models
{
    /// <summary> Response of a list operation. </summary>
    internal partial class DatadogMonitorResourceListResponse
    {
        /// <summary> Initializes a new instance of DatadogMonitorResourceListResponse. </summary>
        internal DatadogMonitorResourceListResponse()
        {
            Value = new ChangeTrackingList<DatadogMonitorResourceData>();
        }

        /// <summary> Initializes a new instance of DatadogMonitorResourceListResponse. </summary>
        /// <param name="value"> Results of a list operation. </param>
        /// <param name="nextLink"> Link to the next set of results, if any. </param>
        internal DatadogMonitorResourceListResponse(IReadOnlyList<DatadogMonitorResourceData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> Results of a list operation. </summary>
        public IReadOnlyList<DatadogMonitorResourceData> Value { get; }
        /// <summary> Link to the next set of results, if any. </summary>
        public string NextLink { get; }
    }
}


text:
require_relative 'spec_helper'
require_relative 'builder'

RSpec.describe 'Iyzipay' do
  before :all do
    @options = Iyzipay::Options.new
    @options.api_key = SpecOptions::API_KEY
    @options.secret_key = SpecOptions::SECRET_KEY
    @options.base_url = SpecOptions::BASE_URL
  end

  it 'should create listing payment' do
    payment_card = {
        cardHolderName: 'John Doe',
        cardNumber: '5528790000000008',
        expireYear: '2030',
        expireMonth: '12',
        cvc: '123',
        registerCard: 0
    }
    buyer = {
        id: 'BY789',
        name: 'John',
        surname: 'Doe',
        gsmNumber: '+905350000000',
        email: 'email@email.com',
        identityNumber: '74300864791',
        lastLoginDate: '2015-10-05 12:43:35',
        registrationDate: '2013-04-21 15:12:09',
        registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
        ip: '85.34.78.112',
        city: 'Istanbul',
        country: 'Turkey',
        zipCode: '34732'
    }
    address = {
        contactName: 'Jane Doe',
        city: 'Istanbul',
        country: 'Turkey',
        address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
        zipCode: '34732'
    }

    item1 = {
        id: 'BI101',
        name: 'Binocular',
        category1: 'Collectibles',
        category2: 'Accessories',
        itemType: Iyzipay::Model::BasketItemType::PHYSICAL,
        price: '0.3'
    }
    item2 = {
        id: 'BI102',
        name: 'Game code',
        category1: 'Game',
        category2: 'Online Game Items',
        itemType: Iyzipay::Model::BasketItemType::VIRTUAL,
        price: '0.5'
    }
    item3 = {
        id: 'BI103',
        name: 'Usb',
        category1: 'Electronics',
        category2: 'Usb / Cable',
        itemType: Iyzipay::Model::BasketItemType::PHYSICAL,
        price: '0.2'
    }
    request = {
        locale: Iyzipay::Model::Locale::TR,
        conversationId: '123456789',
        price: '1',
        paidPrice: '1.1',
        currency: Iyzipay::Model::Currency::TRY,
        installment: 1,
        basketId: 'B67832',
        paymentChannel: Iyzipay::Model::PaymentChannel::WEB,
        paymentGroup: Iyzipay::Model::PaymentGroup::LISTING,
        paymentCard: payment_card,
        buyer: buyer,
        billingAddress: address,
        shippingAddress: address,
        basketItems: [item1, item2, item3]
    }
    payment = Iyzipay::Model::Payment.new.create(request, @options)
    begin
      $stdout.puts payment.inspect
      payment = JSON.parse(payment)
      expect(payment['status']).to eq('success')
      expect(payment['locale']).to eq('tr')
      expect(payment['systemTime']).not_to be_nil
      expect(payment['conversationId']).to eq('123456789')
      expect(payment['price']).to eq(1)
      expect(payment['paidPrice']).to eq(1.1)
      expect(payment['installment']).to eq(1)
    rescue
      $stderr.puts 'oops'
      raise
    end
  end

  it 'should create marketplace payment' do
    # create sub merchant
    sub_merchant = Builder::SubMerchantBuilder.new.create_personal_sub_merchant(@options)

    payment_card = {
        cardHolderName: 'John Doe',
        cardNumber: '5528790000000008',
        expireYear: '2030',
        expireMonth: '12',
        cvc: '123',
        registerCard: 0
    }
    buyer = {
        id: 'BY789',
        name: 'John',
        surname: 'Doe',
        gsmNumber: '+905350000000',
        email: 'email@email.com',
        identityNumber: '74300864791',
        lastLoginDate: '2015-10-05 12:43:35',
        registrationDate: '2013-04-21 15:12:09',
        registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
        ip: '85.34.78.112',
        city: 'Istanbul',
        country: 'Turkey',
        zipCode: '34732'
    }
    address = {
        contactName: 'Jane Doe',
        city: 'Istanbul',
        country: 'Turkey',
        address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
        zipCode: '34732'
    }

    item1 = {
        id: 'BI101',
        name: 'Binocular',
        category1: 'Collectibles',
        category2: 'Accessories',
        itemType: Iyzipay::Model::BasketItemType::PHYSICAL,
        price: '0.3',
        subMerchantKey: sub_merchant['subMerchantKey'],
        subMerchantPrice: '0.27'
    }
    item2 = {
        id: 'BI102',
        name: 'Game code',
        category1: 'Game',
        category2: 'Online Game Items',
        itemType: Iyzipay::Model::BasketItemType::VIRTUAL,
        price: '0.5',
        subMerchantKey: sub_merchant['subMerchantKey'],
        subMerchantPrice: '0.42'
    }
    item3 = {
        id: 'BI103',
        name: 'Usb',
        category1: 'Electronics',
        category2: 'Usb / Cable',
        itemType: Iyzipay::Model::BasketItemType::PHYSICAL,
        price: '0.2',
        subMerchantKey: sub_merchant['subMerchantKey'],
        subMerchantPrice: '0.18'
    }
    request = {
        locale: Iyzipay::Model::Locale::TR,
        conversationId: '123456789',
        price: '1',
        paidPrice: '1.1',
        currency: Iyzipay::Model::Currency::TRY,
        installment: 1,
        basketId: 'B67832',
        paymentChannel: Iyzipay::Model::PaymentChannel::WEB,
        paymentGroup: Iyzipay::Model::PaymentGroup::PRODUCT,
        paymentCard: payment_card,
        buyer: buyer,
        billingAddress: address,
        shippingAddress: address,
        basketItems: [item1, item2, item3]
    }
    payment = Iyzipay::Model::Payment.new.create(request, @options)
    begin
      $stdout.puts payment.inspect
      payment = JSON.parse(payment)
      expect(payment['status']).to eq('success')
      expect(payment['locale']).to eq('tr')
      expect(payment['systemTime']).not_to be_nil
      expect(payment['conversationId']).to eq('123456789')
      expect(payment['price']).to eq(1)
      expect(payment['paidPrice']).to eq(1.1)
      expect(payment['installment']).to eq(1)
    rescue
      $stderr.puts 'oops'
      raise
    end
  end

  it 'should create payment with registered card' do
    # create card
    card = Builder::CardBuilder.new.create_card(@options)

    payment_card = {
        cardUserKey: card['cardUserKey'],
        cardToken: card['cardToken']
    }
    buyer = {
        id: 'BY789',
        name: 'John',
        surname: 'Doe',
        gsmNumber: '+905350000000',
        email: 'email@email.com',
        identityNumber: '74300864791',
        lastLoginDate: '2015-10-05 12:43:35',
        registrationDate: '2013-04-21 15:12:09',
        registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
        ip: '85.34.78.112',
        city: 'Istanbul',
        country: 'Turkey',
        zipCode: '34732'
    }
    address = {
        contactName: 'Jane Doe',
        city: 'Istanbul',
        country: 'Turkey',
        address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
        zipCode: '34732'
    }

    item1 = {
        id: 'BI101',
        name: 'Binocular',
        category1: 'Collectibles',
        category2: 'Accessories',
        itemType: Iyzipay::Model::BasketItemType::PHYSICAL,
        price: '0.3'
    }
    item2 = {
        id: 'BI102',
        name: 'Game code',
        category1: 'Game',
        category2: 'Online Game Items',
        itemType: Iyzipay::Model::BasketItemType::VIRTUAL,
        price: '0.5'
    }
    item3 = {
        id: 'BI103',
        name: 'Usb',
        category1: 'Electronics',
        category2: 'Usb / Cable',
        itemType: Iyzipay::Model::BasketItemType::PHYSICAL,
        price: '0.2'
    }
    request = {
        locale: Iyzipay::Model::Locale::TR,
        conversationId: '123456789',
        price: '1',
        paidPrice: '1.1',
        currency: Iyzipay::Model::Currency::TRY,
        installment: 1,
        basketId: 'B67832',
        paymentChannel: Iyzipay::Model::PaymentChannel::WEB,
        paymentGroup: Iyzipay::Model::PaymentGroup::LISTING,
        paymentCard: payment_card,
        buyer: buyer,
        billingAddress: address,
        shippingAddress: address,
        basketItems: [item1, item2, item3]
    }
    payment = Iyzipay::Model::Payment.new.create(request, @options)
    begin
      $stdout.puts payment.inspect
      payment = JSON.parse(payment)
      expect(payment['status']).to eq('success')
      expect(payment['locale']).to eq('tr')
      expect(payment['systemTime']).not_to be_nil
      expect(payment['conversationId']).to eq('123456789')
      expect(payment['price']).to eq(1)
      expect(payment['paidPrice']).to eq(1.1)
      expect(payment['installment']).to eq(1)
    rescue
      $stderr.puts 'oops'
      raise
    end
  end

  it 'should retrieve payment' do
    # create payment
    payment = Builder::PaymentBuilder.new.create_standard_listing_payment(@options)

    request = {
        locale: Iyzipay::Model::Locale::TR,
        conversationId: '123456789',
        paymentId: payment['paymentId'],
        paymentConversationId: '123456789'
    }

    retrieved_payment = Iyzipay::Model::Payment.new.retrieve(request, @options)
    begin
      $stdout.puts retrieved_payment.inspect
      retrieved_payment = JSON.parse(retrieved_payment)
      expect(retrieved_payment['status']).to eq('success')
      expect(retrieved_payment['locale']).to eq('tr')
      expect(retrieved_payment['systemTime']).not_to be_nil
      expect(retrieved_payment['conversationId']).to eq('123456789')
      expect(retrieved_payment['price']).to eq(1)
      expect(retrieved_payment['paidPrice']).to eq(1.1)
      expect(retrieved_payment['installment']).to eq(1)
      expect(retrieved_payment['paymentId']).to eq(payment['paymentId'])
    rescue
      $stderr.puts 'oops'
      raise
    end
  end

  after :each do
  end
end


text:
#ifndef _LINEAR_H
#define _LINEAR_H

struct linear_hash
{
  struct real_dev *dev0, *dev1;
};

struct linear_data
{
  struct linear_hash *hash_table; /* Dynamically allocated */
  struct real_dev *smallest;
  int nr_zones;
};

#endif

#ifndef _LINEAR_H
#define _LINEAR_H

struct linear_hash
{
  struct real_dev *dev0, *dev1;
};

struct linear_data
{
  struct linear_hash *hash_table; /* Dynamically allocated */
  struct real_dev *smallest;
  int nr_zones;
};

#endif


text:
<?php

/**
 * @file
 * Contains Drupal\locale\Tests\LocaleUpdateInterfaceTest.
 */

namespace Drupal\locale\Tests;

use Drupal\Component\Utility\SafeMarkup;

/**
 * Tests for the user interface of project interface translations.
 *
 * @group locale
 */
class LocaleUpdateInterfaceTest extends LocaleUpdateBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('locale_test_translate');

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'translate interface'));
    $this->drupalLogin($admin_user);
  }

  /**
   * Tests the user interfaces of the interface translation update system.
   *
   * Testing the Available updates summary on the side wide status page and the
   * Available translation updates page.
   */
  public function testInterface() {
    // No language added.
    // Check status page and Available translation updates page.
    $this->drupalGet('admin/reports/status');
    $this->assertNoText(t('Translation update status'), 'No status message');

    $this->drupalGet('admin/reports/translations');
    $this->assertRaw(t('No translatable languages available. Add a language first.', array('@add_language' => \Drupal::url('entity.configurable_language.collection'))), 'Language message');

    // Add German language.
    $this->addLanguage('de');

    // Override Drupal core translation status as 'up-to-date'.
    $status = locale_translation_get_status();
    $status['drupal']['de']->type = 'current';
    \Drupal::state()->set('locale.translation_status', $status);

    // One language added, all translations up to date.
    $this->drupalGet('admin/reports/status');
    $this->assertText(t('Translation update status'), 'Status message');
    $this->assertText(t('Up to date'), 'Translations up to date');
    $this->drupalGet('admin/reports/translations');
    $this->assertText(t('All translations up to date.'), 'Translations up to date');

    // Set locale_test_translate module to have a local translation available.
    $status = locale_translation_get_status();
    $status['locale_test_translate']['de']->type = 'local';
    \Drupal::state()->set('locale.translation_status', $status);

    // Check if updates are available for German.
    $this->drupalGet('admin/reports/status');
    $this->assertText(t('Translation update status'), 'Status message');
    $this->assertRaw(t('Updates available for: @languages. See the Available translation updates page for more information.', array('@languages' => t('German'), '@updates' => \Drupal::url('locale.translate_status'))), 'Updates available message');
    $this->drupalGet('admin/reports/translations');
    $this->assertText(t('Updates for: @modules', array('@modules' => 'Locale test translate')), 'Translations avaiable');

    // Set locale_test_translate module to have a dev release and no
    // translation found.
    $status = locale_translation_get_status();
    $status['locale_test_translate']['de']->version = '1.3-dev';
    $status['locale_test_translate']['de']->type = '';
    \Drupal::state()->set('locale.translation_status', $status);

    // Check if no updates were found.
    $this->drupalGet('admin/reports/status');
    $this->assertText(t('Translation update status'), 'Status message');
    $this->assertRaw(t('Missing translations for: @languages. See the Available translation updates page for more information.', array('@languages' => t('German'), '@updates' => \Drupal::url('locale.translate_status'))), 'Missing translations message');
    $this->drupalGet('admin/reports/translations');
    $this->assertText(t('Missing translations for one project'), 'No translations found');
    $this->assertText(SafeMarkup::format('@module (@version). !info', array('@module' => 'Locale test translate', '@version' => '1.3-dev', '!info' => t('No translation files are provided for development releases.'))), 'Release details');
    $this->assertText(t('No translation files are provided for development releases.'), 'Release info');

    // Override Drupal core translation status as 'no translations found'.
    $status = locale_translation_get_status();
    $status['drupal']['de']->type = '';
    $status['drupal']['de']->timestamp = 0;
    $status['drupal']['de']->version = '8.1.1';
    \Drupal::state()->set('locale.translation_status', $status);

    // Check if Drupal core is not translated.
    $this->drupalGet('admin/reports/translations');
    $this->assertText(t('Missing translations for 2 projects'), 'No translations found');
    $this->assertText(t('@module (@version).', array('@module' => t('Drupal core'), '@version' => '8.1.1')), 'Release details');

    // Override Drupal core translation status as 'translations available'.
    $status = locale_translation_get_status();
    $status['drupal']['de']->type = 'local';
    $status['drupal']['de']->files['local']->timestamp = REQUEST_TIME;
    $status['drupal']['de']->files['local']->info['version'] = '8.1.1';
    \Drupal::state()->set('locale.translation_status', $status);

    // Check if translations are available for Drupal core.
    $this->drupalGet('admin/reports/translations');
    $this->assertText(t('Updates for: !project', array('!project' => t('Drupal core'))), 'Translations found');
    $this->assertText(SafeMarkup::format('@module (@date)', array('@module' => t('Drupal core'), '@date' => format_date(REQUEST_TIME, 'html_date'))), 'Core translation update');
    $update_button = $this->xpath('//input[@type="submit"][@value="' . t('Update translations') . '"]');
    $this->assertTrue($update_button, 'Update translations button');
  }

}


text:
import logging

from django.core.urlresolvers import reverse  # noqa
from django.utils.translation import ugettext_lazy as _  # noqa

from horizon import exceptions
from horizon import tables

from openstack_dashboard import api
from contrail_openstack_dashboard.openstack_dashboard.dashboards.project.networking.ports import \
    tables as project_tables

LOG = logging.getLogger(__name__)

class DeletePort(tables.DeleteAction):
    data_type_singular = _("Port")
    data_type_plural = _("Ports")

    def delete(self, request, obj_id):
        try:
            api.neutron.port_delete(request, obj_id)
        except Exception:
            msg = _('Failed to delete subnet %s') % obj_id
            LOG.info(msg)
            network_id = self.table.kwargs['network_id']
            redirect = reverse('horizon:admin:networking:detail',
                               args=[network_id])
            exceptions.handle(request, msg, redirect=redirect)

class CreatePort(tables.LinkAction):
    name = "create"
    verbose_name = _("Create Port")
    url = "horizon:admin:networking:addport"
    classes = ("ajax-modal", "btn-create")

    def get_link_url(self, datum=None):
        network_id = self.table.kwargs['network_id']
        return reverse(self.url, args=(network_id,))

class UpdatePort(tables.LinkAction):
    name = "update"
    verbose_name = _("Edit Port")
    url = "horizon:admin:networking:editport"
    classes = ("ajax-modal", "btn-edit")

    def get_link_url(self, port):
        network_id = self.table.kwargs['network_id']
        return reverse(self.url, args=(network_id, port.id))

class PortsTable(tables.DataTable):
    name = tables.Column("name",
                         verbose_name=_("Name"),
                         link="horizon:admin:networking:ports:detail")
    fixed_ips = tables.Column(
        project_tables.get_fixed_ips, verbose_name=_("Fixed IPs"))
    device_id = tables.Column(
        project_tables.get_attached, verbose_name=_("Device Attached"))
    status = tables.Column("status", verbose_name=_("Status"))
    admin_state = tables.Column("admin_state",
                                verbose_name=_("Admin State"))

    class Meta:
        name = "ports"
        verbose_name = _("Ports")
        table_actions = (project_tables.PortFilterAction, CreatePort, DeletePort)
        row_actions = (UpdatePort, DeletePort,)