text:
'''
    this script merges the daily product sales excel sheets into one
'''

import json
import os.path
import xlrd
from posix import listdir
from os.path import isfile, join
from openpyxl import Workbook

def process_file(f, ws_new, file_count):
    # open current file's workbook and sheet
    wb = xlrd.open_workbook(f)
    sheet_names = wb.sheet_names()
    ws = wb.sheet_by_name(sheet_names[0])

    # get the number of rows of the sheet
    num_rows = ws.nrows - 1

    # get the date of the current sheet
    d = ws.cell_value(3, 6)
    date = d[-8:].split('/')
    date = '20{}-{}-{}'.format(date[2], date[1], date[0])

    global daily_sales
    # get daily total gross sales
    sales = ws.cell_value(num_rows, 13)
    # add daily sales to dictionary
    daily_sales[date] = sales

    cell_count = 2
    global row_count

    # our header row is always the same in each file
    header_row = 4

    # copy over header from first file
    if (file_count == 0):

        global num_cols
        num_cols = ws.ncols - 1

        # add date header
        c = ws_new.cell(row = row_count, column = 1)
        c.value = 'Date'

        # go through each cell in current header row
        for curr_cell in range(num_cols):
            # copy over each non-empty cell to new excel sheet
             if (ws.cell_type(header_row, curr_cell) != 0):
                c = ws_new.cell(row = row_count, column = cell_count)
                hrow = ws.cell_value(header_row, curr_cell)
                hrow_next = ws.cell_value(header_row + 1, curr_cell)
                # some headers span over two rows
                c.value = hrow if not hrow_next else hrow + ' ' + hrow_next

                cell_count += 1

                # we don't want anything after product sales
                if "Unit" in hrow:
                    num_cols = curr_cell + 1;
                    break;

        row_count += 1

    # process each row
    for curr_row in range(6, ws.nrows - 1):

        # reset cell_count
        cell_count = 2

        # go through each cell
        for curr_cell in range(num_cols):
            # if first cell in row not empty
            if ws.cell_type(curr_row, 0) != 0:
                if ws.cell_type(curr_row, curr_cell) != 0:
                    c = ws_new.cell(row = row_count, column = cell_count)
                    c.value = ws.cell_value(curr_row, curr_cell)
                    cell_count += 1
            # some entries span over two rows
            elif(ws.cell_type(curr_row, 4) != 0):
                    c = ws_new.cell(row = row_count-1, column = 5)
                    c.value = ws.cell_value(curr_row - 1, 4) + ' ' + ws.cell_value(curr_row, 4)

        # add date
        if(ws.cell_type(curr_row, 0) != 0):
            c = ws_new.cell(row = row_count, column = 1)
            c.value = date

            row_count += 1

    print('Done: ' + date)

def process_dir(data_dir_path, output_file_path):
    # get the list of files in the directory
    onlyfiles = [ f for f in listdir(data_dir_path) if isfile(join(data_dir_path,f))]

    # crate a new workbook and sheet
    wb_new = Workbook()
    sheet_names = wb_new.get_sheet_names()
    ws_new = wb_new.get_sheet_by_name(sheet_names[0])

    # keep track of number of files processed
    global file_count
    file_count = 0

    # keep track of the row number in the new merged file
    global row_count
    row_count = 1

    # save daily sales
    global daily_sales
    daily_sales = {}

    # process each file in given path
    for f in onlyfiles:
        process_file(data_dir_path + f, ws_new, file_count)
        file_count += 1

    # finally save daily sales json
    with open(output_file_path + 'daily_sale_figures.json', 'w', encoding = 'utf-8') as fp:
        json.dump(daily_sales, fp)

    # finally save the new excel file
    wb_new.save(output_file_path + 'daily_product_sales.xlsx')

def main():
    # path for data files
    dir_path = '..' + os.sep + '..' + os.sep + 'data' + os.sep + 'peData' + os.sep
    data_dir_path = dir_path + 'daily_product_sales' + os.sep

    process_dir(data_dir_path, dir_path)

if __name__ == "__main__":
    main()


text:
using System;

namespace Demo.UnitsOfMeasurement
{
    public partial struct Kilometer : IQuantity<double>, IEquatable<Kilometer>, IComparable<Kilometer>, IFormattable
    {
        #region Fields
        internal readonly double m_value;
        #endregion

        #region Properties / IQuantity<double>
        public double Value { get { return m_value; } }
        Unit<double> IQuantity<double>.Unit { get { return Kilometer.Proxy; } }
        #endregion

        #region Constructor(s)
        public Kilometer(double value)
        {
            m_value = value;
        }
        #endregion

        #region Conversions
        public static explicit operator Kilometer(double q) { return new Kilometer(q); }
        public static explicit operator Kilometer(Millimeter q) { return new Kilometer((Kilometer.Factor / Millimeter.Factor) * q.m_value); }
        public static explicit operator Kilometer(Centimeter q) { return new Kilometer((Kilometer.Factor / Centimeter.Factor) * q.m_value); }
        public static explicit operator Kilometer(Meter q) { return new Kilometer((Kilometer.Factor / Meter.Factor) * q.m_value); }
        public static explicit operator Kilometer(Inch q) { return new Kilometer((Kilometer.Factor / Inch.Factor) * q.m_value); }
        public static explicit operator Kilometer(Foot q) { return new Kilometer((Kilometer.Factor / Foot.Factor) * q.m_value); }
        public static explicit operator Kilometer(Yard q) { return new Kilometer((Kilometer.Factor / Yard.Factor) * q.m_value); }
        public static explicit operator Kilometer(Mile q) { return new Kilometer((Kilometer.Factor / Mile.Factor) * q.m_value); }
        public static Kilometer From(IQuantity<double> q)
        {
            if (q.Unit.Family != Kilometer.Family)
            {
				throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" to \"Kilometer\"", q.GetType().Name));
            }
            return new Kilometer((Kilometer.Factor / q.Unit.Factor) * q.Value);
        }
        #endregion

        #region IObject / IEquatable<Kilometer>
        public override int GetHashCode() { return m_value.GetHashCode(); }
        public override bool /* IObject */ Equals(object obj) { return (obj is Kilometer) && Equals((Kilometer)obj); }
        public bool /* IEquatable<Kilometer> */ Equals(Kilometer other) { return this.m_value == other.m_value; }
        #endregion

        #region Comparison / IComparable<Kilometer>
        public static bool operator ==(Kilometer lhs, Kilometer rhs) { return lhs.m_value == rhs.m_value; }
        public static bool operator !=(Kilometer lhs, Kilometer rhs) { return lhs.m_value != rhs.m_value; }
        public static bool operator <(Kilometer lhs, Kilometer rhs) { return lhs.m_value < rhs.m_value; }
        public static bool operator >(Kilometer lhs, Kilometer rhs) { return lhs.m_value > rhs.m_value; }
        public static bool operator <=(Kilometer lhs, Kilometer rhs) { return lhs.m_value <= rhs.m_value; }
        public static bool operator >=(Kilometer lhs, Kilometer rhs) { return lhs.m_value >= rhs.m_value; }
        public int /* IComparable<Kilometer> */ CompareTo(Kilometer other) { return this.m_value.CompareTo(other.m_value); }
        #endregion

        #region Arithmetic
        // Inner:
        public static Kilometer operator +(Kilometer lhs, Kilometer rhs) { return new Kilometer(lhs.m_value + rhs.m_value); }
        public static Kilometer operator -(Kilometer lhs, Kilometer rhs) { return new Kilometer(lhs.m_value - rhs.m_value); }
        public static Kilometer operator ++(Kilometer q) { return new Kilometer(q.m_value + 1d); }
        public static Kilometer operator --(Kilometer q) { return new Kilometer(q.m_value - 1d); }
        public static Kilometer operator -(Kilometer q) { return new Kilometer(-q.m_value); }
        public static Kilometer operator *(double lhs, Kilometer rhs) { return new Kilometer(lhs * rhs.m_value); }
        public static Kilometer operator *(Kilometer lhs, double rhs) { return new Kilometer(lhs.m_value * rhs); }
        public static Kilometer operator /(Kilometer lhs, double rhs) { return new Kilometer(lhs.m_value / rhs); }
        public static double operator /(Kilometer lhs, Kilometer rhs) { return lhs.m_value / rhs.m_value; }
        // Outer:
        public static Kilometer_Hour operator /(Kilometer lhs, Hour rhs) { return new Kilometer_Hour(lhs.m_value / rhs.m_value); }
        public static Hour operator /(Kilometer lhs, Kilometer_Hour rhs) { return new Hour(lhs.m_value / rhs.m_value); }
        #endregion

        #region Formatting
        public static string String(double q, string format = null, IFormatProvider fp = null)
        {
            return string.Format(fp, format ?? Kilometer.Format, q, Kilometer.Symbol.Default);
        }

        public override string ToString() { return String(m_value); }
        public string ToString(string format) { return String(m_value, format); }
        public string ToString(IFormatProvider fp) { return String(m_value, null, fp); }
        public string /* IFormattable */ ToString(string format, IFormatProvider fp) { return String(m_value, format, fp); }
        #endregion

        #region Static fields and properties (DO NOT CHANGE!)
        public static readonly Dimension Sense = Meter.Sense;
        public const int Family = Meter.Family;
        public static readonly SymbolCollection Symbol = new SymbolCollection("km");
        public static readonly Unit<double> Proxy = new Kilometer_Proxy();
        public const double Factor = Meter.Factor / 1000d;
        public static string Format { get { return s_format; } set { s_format = value; } }
        private static string s_format = "{0} {1}";
        #endregion

        #region Predefined quantities
        public static readonly Kilometer One = new Kilometer(1d);
        public static readonly Kilometer Zero = new Kilometer(0d);
        #endregion
    }

    public partial class Kilometer_Proxy : Unit<double>
    {
        #region Properties
        public override Dimension Sense { get { return Kilometer.Sense; } }
        public override int Family { get { return Kilometer.Family; } }
        public override double Factor { get { return Kilometer.Factor; } }
        public override SymbolCollection Symbol { get { return Kilometer.Symbol; } }
        public override string Format { get { return Kilometer.Format; } set { Kilometer.Format = value; } }
        #endregion

        #region Constructor(s)
        public Kilometer_Proxy() :
            base(typeof(Kilometer))
        {
        }
        #endregion

        #region Methods
        public override IQuantity<double> Create(double value)
        {
            return new Kilometer(value);
        }
        public override IQuantity<double> From(IQuantity<double> quantity)
        {
            return Kilometer.From(quantity);
        }
        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = {
	updateState(satisfied, rising) {
		return {
			tempChecker: {
				state: satisfied,
				rising: rising
			}
		};
	}
};


text:
Repositories
========

Simple Repository Class and Interface for FluentKit


text:
class ReviewerFilter
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :state, :track_id

  def initialize(params = {})
    return unless params[:reviewer_filter]

    @state = params[:reviewer_filter][:state]
    @track_id = params[:reviewer_filter][:track_id]
  end

  def apply(scope)
    scope = scope.with_state(@state.to_sym) if @state.present?
    scope = scope.for_track(@track_id) if @track_id.present?
    scope
  end

  def persisted?
    false
  end
end


text:
package lib.phenix.com.swipetorefresh.progressindicator.indicator;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

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

/**
 * Created by Jack on 2015/10/16.
 */
public class BallClipRotateIndicator extends BaseIndicatorController {

    float scaleFloat=1,degrees;

    @Override
    public void draw(Canvas canvas, Paint paint) {
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);

        float circleSpacing=12;
        float x = (getWidth()) / 2;
        float y=(getHeight()) / 2;
        canvas.translate(x, y);
        canvas.scale(scaleFloat, scaleFloat);
        canvas.rotate(degrees);
        RectF rectF=new RectF(-x+circleSpacing,-y+circleSpacing,0+x-circleSpacing,0+y-circleSpacing);
        canvas.drawArc(rectF, -45, 270, false, paint);
    }

    @Override
    public List<Animator> createAnimation() {
        List<Animator> animators=new ArrayList<>();
        ValueAnimator scaleAnim=ValueAnimator.ofFloat(1,0.6f,0.5f,1);
        scaleAnim.setDuration(750);
        scaleAnim.setRepeatCount(-1);
        scaleAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                scaleFloat = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        scaleAnim.start();

        ValueAnimator rotateAnim=ValueAnimator.ofFloat(0,180,360);
        rotateAnim.setDuration(750);
        rotateAnim.setRepeatCount(-1);
        rotateAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                degrees = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        rotateAnim.start();
        animators.add(scaleAnim);
        animators.add(rotateAnim);
        return animators;
    }

}


text:
#pragma once
#ifndef URASANDESU_PRIG_IMETHODSIGEQUALTOFWD_H
#define URASANDESU_PRIG_IMETHODSIGEQUALTOFWD_H

namespace Urasandesu { namespace Prig {

    namespace IMethodSigEqualToDetail {

        struct IMethodSigEqualToImpl;

    }   // namespace IMethodSigEqualToDetail {

    struct IMethodSigEqualTo;

}}   // namespace Urasandesu { namespace Prig {

#endif  // URASANDESU_PRIG_IMETHODSIGEQUALTOFWD_H


text:
namespace Microsoft.AspNetCore.Routing.Matching;

internal sealed class ZeroEntryJumpTable : JumpTable
{
    private readonly int _defaultDestination;
    private readonly int _exitDestination;

    public ZeroEntryJumpTable(int defaultDestination, int exitDestination)
    {
        _defaultDestination = defaultDestination;
        _exitDestination = exitDestination;
    }

    public override int GetDestination(string path, PathSegment segment)
    {
        return segment.Length == 0 ? _exitDestination : _defaultDestination;
    }

    public override string DebuggerToString()
    {
        return $"{{ $+: {_defaultDestination}, $0: {_exitDestination} }}";
    }
}


text:
package org.darcstarsolutions.threetaps.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Created by mharris on 5/26/15.
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


text:
using System.ComponentModel;

namespace EncompassRest.Loans.Enums
{
    /// <summary>
    /// AppraisalPropertyType
    /// </summary>
    public enum AppraisalPropertyType
    {
        /// <summary>
        /// IND-Single Prop-Ind Appraisal
        /// </summary>
        [Description("IND-Single Prop-Ind Appraisal")]
        IND = 0,
        /// <summary>
        /// MCRV
        /// </summary>
        MCRV = 1,
        /// <summary>
        /// LAPP-Lender
        /// </summary>
        [Description("LAPP-Lender")]
        LAPP = 2,
        /// <summary>
        /// MBL-Manufactured Home
        /// </summary>
        [Description("MBL-Manufactured Home")]
        MBL = 3,
        /// <summary>
        /// HUD-HUD Conversion
        /// </summary>
        [Description("HUD-HUD Conversion")]
        HUD = 4,
        /// <summary>
        /// PMC-Property Management Case
        /// </summary>
        [Description("PMC-Property Management Case")]
        PMC = 5
    }
}


text:
import sys
from twisted.internet import reactor

from mainbot import MainBotFactory

# TODO: better way to add plugins
from plugins.creative_quit import CreativeQuitPlugin
from plugins.puppy_plugin.puppy_plugin import PuppyCommandPlugin
from plugins.link_log.link_log import LinkCheckLogPlugin
from plugins.taunt_user import SeanzResponse
from plugins.taunt_user import AlbertResponse

def _tokenize_channels(raw_str):
    channels = raw_str.split(' ')
    return [str(channel).strip() for channel in channels]

def _print_instr():
    print """
    To run this, you need to provide the path to the
    config file (like irc_credentials.ini). You must
    also indicate channels, separated by spaces in a
    single quoted string.

    Example:
    $ python event.py irc_credentials.ini '#channel1 #channel2'
    """

if __name__ == "__main__":

    try:
        me, config_file, channel_string = sys.argv
        channels = _tokenize_channels(channel_string)
    except (ValueError, IndexError) as error:
        _print_instr()
    else:
        command_plugins = [PuppyCommandPlugin, CreativeQuitPlugin]
        taunt_plugins = [SeanzResponse]
        message_plugins = [LinkCheckLogPlugin]

        reactor.connectTCP('irc.freenode.net',
                            6667,
                            MainBotFactory(config_file,
                                           channels,
                                           command_plugins,
                                           message_plugins,
                                           taunt_plugins,
                                           ))
        reactor.run()


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:transitionName="web_view"
    xmlns:android="http://schemas.android.com/apk/res/android">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/card_color">
            <include
                layout="@layout/info_header"
                android:id="@+id/info_header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginRight="20dp"
                android:layout_marginEnd="20dp"
                />
            <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_below="@id/info_header"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:id="@+id/thumb_nail"
                android:background="@drawable/image_shape"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/title_text"
                android:textSize="20sp"
                android:layout_below="@id/thumb_nail"
                android:textColor="@color/title_text_color"
                android:layout_marginTop="15dp"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:maxLines="5"
                android:ellipsize="end"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/subject_text"
                android:layout_below="@id/title_text"
                android:textSize="15sp"
                android:layout_marginTop="10dp"
                android:layout_alignLeft="@id/title_text"
                android:layout_alignStart="@+id/title_text"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:paddingBottom="15dp"
                android:layout_above="@+id/icon_container"
                android:ellipsize="end"
                />
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:id="@+id/icon_container"
                android:layout_marginBottom="10dp">
                <ImageView
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:id="@+id/favourite_icon"
                    android:src="@drawable/ic_favorite_border_black_24dp"/>
                <ImageView
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:src="@drawable/ic_share_black_24dp"
                    android:id="@+id/share_icon"
                    android:layout_toRightOf="@id/favourite_icon"
                    android:layout_toEndOf="@id/favourite_icon"
                    android:layout_marginLeft="5dp"
                    android:layout_marginStart="5dp"
                    />
            </RelativeLayout>
        </RelativeLayout>
    </android.support.v7.widget.CardView>


text:
import datetime
import json
import numpy as np
import pandas as pd
import dask.array as da
import dask.bag as db
import dask
from tabulate import tabulate
from dama.abc.data import AbsData
from dama.abc.conn import AbsConn
from dama.data.it import Iterator, BaseIterator, BatchIterator
from dama.utils.core import Hash, Login, Metadata, Chunks, Shape
from dama.abc.driver import AbsDriver
from dama.drivers.core import Memory
from dama.drivers.sqlite import Sqlite
from dama.utils.logger import log_config
from dama.utils.config import get_settings
from dama.utils.decorators import cache, clean_cache
from dama.utils.files import get_dir_file_size
from dama.utils.order import order_table
from dama.connexions.core import GroupManager
from pydoc import locate

settings = get_settings("paths")
log = log_config(__name__)

class Data(AbsData):
    def __init__(self, name: str = None, driver: AbsDriver = None, group_name: str = None,
                 chunks=None, auto_chunks=False, metadata_path: str = None):

        if driver is None:
            self.driver = Memory()
        else:
            self.driver = driver

        if name is None and not isinstance(self.driver, Memory):
            raise Exception("I can't build a dataset without a name, plese add a name to this dataset.")

        if self.driver.persistent is True:
            if metadata_path is not None:
                self.metadata_path = metadata_path
            else:
                self.metadata_path = settings["metadata_path"]
            self.metadata_driver = Sqlite(login=Login(table="data"), path=self.metadata_path)
        else:
            self.metadata_path = None
            self.metadata_driver = None

        self.name = name
        self.header_map = ["author", "description"]
        self.group_name = group_name
        self.dtypes = None
        self.hash = None
        self.author = None
        self.description = None
        self.timestamp = None
        self.compressor_params = None
        self.chunksize = chunks
        self.from_ds_hash = None
        self.auto_chunks = auto_chunks
        if self.driver.path is None:
            self.driver.path = settings["data_path"]
        self.driver.build_url(self.name, group_level=self.group_name)

    @property
    def author(self):
        return self._get_attr('author')

    @author.setter
    def author(self, value):
        if value is not None:
            self._set_attr('author', value)

    @property
    def dtype(self):
        return self.data.dtype

    @property
    def description(self):
        return self._get_attr('description')

    @description.setter
    def description(self, value):
        if value is not None:
            self._set_attr('description', value)

    @property
    def timestamp(self):
        return self._get_attr('timestamp')

    @timestamp.setter
    def timestamp(self, value):
        if value is not None:
            self._set_attr('timestamp', value)

    @property
    def hash(self):
        return self._get_attr('hash')

    @hash.setter
    def hash(self, value):
        if value is not None:
            self._set_attr('hash', value)

    @property
    def compressor_params(self):
        return json.loads(self._get_attr('compressor_params'))

    @compressor_params.setter
    def compressor_params(self, value):
        if value is not None:
            self._set_attr('compressor_params', json.dumps(value))

    @classmethod
    def module_cls_name(cls):
        return "{}.{}".format(cls.__module__, cls.__name__)

    @property
    @cache
    def data(self) -> AbsConn:
        return self.driver.manager(chunks=self.chunksize)

    @data.setter
    @clean_cache
    def data(self, v):
        pass

    def clean_data_cache(self):
        self.data = None

    @property
    def from_ds_hash(self):
        return self._get_attr('from_ds_hash')

    @from_ds_hash.setter
    def from_ds_hash(self, value):
        if value is not None:
            self._set_attr('from_ds_hash', value)

    def open(self):
        self.driver.open()

        if self.driver.mode in ["w", "a", "r+"]:
            if len(self.driver.compressor_params) > 0:
                self.compressor_params = self.driver.compressor_params

        if self.auto_chunks is True and self.driver.mode in ["a", "r"]:
            try:
                self.chunksize = Chunks.build_from_shape(self.driver.shape, self.driver.dtypes)
            except KeyError as e:
                log.error(e)
        else:
            if isinstance(self.chunksize, tuple) and self.driver.mode in ["a", "r"]:
                groups = self.driver.groups
                if groups is not None:
                    self.chunksize = Chunks.build_from(self.chunksize, groups)
            elif self.driver.mode == "w" or self.chunksize is None:
                pass
            elif isinstance(self.chunksize, Chunks) and self.driver.mode in ["a", "r"]:
                pass
            else:
                raise Exception("chunks value {} not allowed".format(self.chunksize))

    def close(self):
        self.driver.close()
        self.data = None

    def __getitem__(self, key):
        return self.data[key]

    def __setitem__(self, key, value):
        raise NotImplementedError

    def __iter__(self):
        return self

    def __next__(self):
        return next(self.data)

    def _set_attr(self, name, value):
        if value is not None:
            log.debug("SET attribute {name} {value}".format(name=name, value=value))
            self.driver.attrs[name] = value

    def _get_attr(self, name):
        try:
            return self.driver.attrs[name]
        except KeyError:
            log.debug("Not found attribute {} in file {}".format(name, self.url))
            return None
        except IOError as e:
            log.debug(e)
            log.debug("Error opening {} in file {}".format(name, self.url))
            return None

    def destroy(self):
        hash_hex = self.hash
        self.driver.destroy()
        if self.driver.persistent is True:
            with Metadata(self.metadata_driver) as metadata:
                metadata.invalid(hash_hex)

    @property
    def url(self) -> str:
        return self.driver.url

    @property
    def metadata_url(self) -> str:
        return self.metadata_driver.url

    def __len__(self):
        return len(self.groups)

    def __repr__(self):
        return repr(self.data)

    @property
    def size(self):
        return self.shape[0]

    @property
    def shape(self) -> Shape:
        return self.data.shape

    @property
    def groups(self) -> tuple:
        if self.data is not None:
            return self.data.groups

    @property
    def dtypes(self) -> np.dtype:
        return self.data.dtypes

    @dtypes.setter
    def dtypes(self, value):
        if value is not None:
            self.driver.set_schema(value)

    def info(self):
        print('       ')
        print('Name: {}'.format(self.name))
        print('Author: {}'.format(self.author))
        print('Description: {}'.format(self.description))
        print('URL path: {}'.format(self.driver.url))
        print('Hash: {}'.format(self.hash))
        print('       ')
        headers = ["group", "shape", "dtype"]
        table = []
        shape = self.shape
        for group, (dtype, _) in self.dtypes.fields.items():
            table.append([group, shape[group], dtype])
        print(order_table(headers, table, "Group"))

    def metadata(self) -> dict:
        meta_dict = dict()
        meta_dict["hash"] = self.hash
        meta_dict["path"] = self.driver.path
        meta_dict["metadata_path"] = self.metadata_path
        meta_dict["group_name"] = self.group_name
        meta_dict["driver_module"] = self.driver.module_cls_name()
        meta_dict["driver_name"] = self.driver.cls_name()
        meta_dict["name"] = self.name
        meta_dict["size"] = get_dir_file_size(self.url)
        meta_dict["timestamp"] = self.timestamp
        meta_dict["author"] = self.author
        meta_dict["num_groups"] = len(self.groups)
        meta_dict["description"] = self.description if self.description is None else ""
        meta_dict["from_ds_hash"] = self.from_ds_hash
        return meta_dict

    def metadata_to_json(self, f):
        metadata = self.metadata()
        json.dump(metadata, f)

    def write_metadata(self):
        if self.driver.persistent is True:
            with Metadata(self.metadata_driver, self.metadata()) as metadata:
                dtypes = np.dtype([("hash", object), ("name", object), ("author", object),
                                   ("description", object), ("size", int), ("driver_module", object),
                                   ("path", object), ("driver_name", object), ("group_name", object),
                                   ("timestamp", np.dtype("datetime64[ns]")), ("num_groups", int),
                                   ("is_valid", bool), ("from_ds_hash", object)])
                timestamp = metadata["timestamp"]
                metadata["timestamp"] = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M UTC')
                metadata["group_name"] = "s/n" if self.group_name is None else self.group_name
                metadata["is_valid"] = True
                metadata.set_schema(dtypes, unique_key=["hash", ["path", "name", "driver_name", "group_name"]])
                metadata.insert_update_data(keys=["hash", ["path", "name", "driver_name", "group_name"]])

    def calc_hash(self, with_hash: str) -> str:
        hash_obj = Hash(hash_fn=with_hash)
        header = [getattr(self, attr) for attr in self.header_map]
        header = [attr for attr in header if attr is not None]
        hash_obj.hash.update("".join(header).encode("utf-8"))
        for group in self.groups:
            it = Iterator(self.data[group]).batchs(chunks=self.chunksize)
            hash_obj.update(it.only_data())
        return str(hash_obj)

    def from_data(self, data, with_hash: str = "sha1", from_ds_hash: str = None, start_i: int = 0):
        if isinstance(data, da.Array):
            data = GroupManager.from_da(data)
            if self.chunksize is None:
                self.chunksize = data.chunksize
            elif isinstance(self.chunksize, tuple):
                self.chunksize = Chunks.build_from(self.chunksize, data.groups)
        elif isinstance(data, Iterator):
            if self.chunksize is None:
                self.chunksize = Chunks.build_from_shape(data.shape, data.dtypes)
            elif isinstance(self.chunksize, tuple):
                self.chunksize = Chunks.build_from(self.chunksize, data.groups)
            data = data.batchs(chunks=self.chunksize, start_i=start_i)
            self.chunksize = data.chunksize
        elif isinstance(data, BatchIterator):
            if self.chunksize is None:
                self.chunksize = data.chunksize
            elif isinstance(self.chunksize, tuple):
                self.chunksize = Chunks.build_from(self.chunksize, data.groups)
        elif isinstance(data, dict) and not isinstance(data, AbsConn):
            if self.chunksize is None:
                shape, dtypes = Shape.get_shape_dtypes_from_dict(data)
                self.chunksize = Chunks.build_from_shape(shape, dtypes)
            elif isinstance(self.chunksize, tuple):
                self.chunksize = Chunks.build_from(self.chunksize, tuple(data.keys()))
            data = GroupManager.convert(data, chunks=self.chunksize)
        elif isinstance(data, AbsConn):
            if self.chunksize is None:
                self.chunksize = data.chunksize
            elif isinstance(self.chunksize, tuple):
                self.chunksize = Chunks.build_from(self.chunksize, data.groups)
        elif not isinstance(data, BaseIterator):
            data = Iterator(data)
            if self.chunksize is None:
                self.chunksize = Chunks.build_from_shape(data.shape, data.dtypes)
            elif isinstance(self.chunksize, tuple):
                self.chunksize = Chunks.build_from(self.chunksize, data.groups)
            data = data.batchs(chunks=self.chunksize, start_i=start_i)
            self.chunksize = data.chunksize
        self.dtypes = data.dtypes
        self.driver.set_data_shape(data.shape)
        if isinstance(data, BatchIterator) or isinstance(data, Iterator):
            self.driver.batchs_writer(data)
        elif isinstance(data, AbsConn):
            self.driver.store(data)
        else:
            raise NotImplementedError

        if with_hash is not None:
            c_hash = self.calc_hash(with_hash=with_hash)
        else:
            c_hash = None

        self.from_ds_hash = from_ds_hash
        self.hash = c_hash
        self.timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M UTC")
        self.write_metadata()

    def from_loader(self, data_list: list, loader_fn, npartitions: int = 1, with_hash: str = "sha1"):
        def concat_partitions(part1: list, part2: list):
            if not isinstance(part1, list):
                part1 = [part1]
            if not isinstance(part2, list):
                part2 = [part2]
            return GroupManager.concat(part1 + part2, axis=0)

        url_bag_partition = db.from_sequence(data_list, npartitions=npartitions)
        fold_loader = url_bag_partition.map(loader_fn).fold(binop=self.add_to_list, combine=concat_partitions,
                                                            initial=[])
        da_group = fold_loader.compute()
        self.from_data(da_group, with_hash=with_hash)

    @staticmethod
    def add_to_list(base_list, data) -> list:
        it = Iterator(data)
        groups = it.groups
        if len(groups) == 1:
            group_items = [(groups[0], data)]
        else:
            group_items = [(group, data[group]) for group in groups]
        dagroup_dict = GroupManager.convert(group_items, Chunks.build_from_shape(it.shape, it.dtypes))
        return base_list + [dagroup_dict]

    def to_df(self) -> pd.DataFrame:
        return self.data.to_df()

    def to_ndarray(self, dtype=None) -> np.ndarray:
        return self.data.to_ndarray(dtype=dtype)

    def concat(self, datasets: tuple, axis=0):
        da_groups = []
        managers = set([])
        for ds in datasets:
            da_groups.append(ds.data)
            managers.add(type(ds.data))
        if len(managers) == 1:
            manager = managers.pop()
            da_group = manager.concat(da_groups, axis=axis)
            self.from_data(da_group)
        else:
            raise NotImplementedError

    def stadistics(self):
        headers = ["group", "mean", "std dev", "min", "25%", "50%", "75%", "max", "nonzero", "nonan", "unique", "dtype"]
        self.chunksize = Chunks.build_from_shape(self.shape, self.dtypes)
        table = []
        for group, (dtype, _) in self.dtypes.fields.items():
            values = dict()
            values["dtype"] = dtype
            values["group"] = group
            darray = self.data[group].da
            if dtype == np.dtype(float) or dtype == np.dtype(int):
                da_mean = da.around(darray.mean(), decimals=3)
                da_std = da.around(darray.std(), decimals=3)
                da_min = da.around(darray.min(), decimals=3)
                da_max = da.around(darray.max(), decimals=3)
                result = dask.compute([da_mean, da_std, da_min, da_max])[0]
                values["mean"] = result[0] if not np.isnan(result[0]) else da.around(da.nanmean(darray), decimals=3).compute()
                values["std dev"] = result[1] if not np.isnan(result[0]) else da.around(da.nanstd(darray), decimals=3).compute()
                values["min"] = result[2] if not np.isnan(result[0]) else da.around(da.nanmin(darray), decimals=3).compute()
                values["max"] = result[3] if not np.isnan(result[0]) else da.around(da.nanmax(darray), decimals=3).compute()
                if len(self.shape[group]) == 1:
                    da_percentile = da.around(da.percentile(darray, [25, 50, 75]), decimals=3)
                    result = da_percentile.compute()
                    values["25%"] = result[0]
                    values["50%"] = result[1]
                    values["75%"] = result[2]
                else:
                    values["25%"] = "-"
                    values["50%"] = "-"
                    values["75%"] = "-"
                values["nonzero"] = da.count_nonzero(darray).compute()
                values["nonan"] = da.count_nonzero(da.notnull(darray)).compute()
                values["unique"] = "-"
            else:
                values["mean"] = "-"
                values["std dev"] = "-"
                values["min"] = "-"
                values["max"] = "-"
                values["25%"] = "-"
                values["50%"] = "-"
                values["75%"] = "-"
                values["nonzero"] = "-"
                values["nonan"] = da.count_nonzero(da.notnull(darray)).compute()
                vunique = darray.to_dask_dataframe().fillna('').nunique().compute()
                values["unique"] = vunique

            row = []
            for column in headers:
                row.append(values[column])
            table.append(row)

        print("# rows {}".format(self.shape[0]))
        return tabulate(table, headers)

    @staticmethod
    def load(hash_hex: str, metadata_driver: AbsDriver, metadata_path: str = None, auto_chunks: bool = True) -> 'Data':
        with Metadata(metadata_driver) as metadata:
            query = "SELECT name, driver_module, path, group_name, hash FROM {} WHERE hash = ?".format(
                metadata_driver.login.table)
            data = metadata.query(query, (hash_hex,))
            if len(data) == 0:
                log.warning(
                    "Resource {} does not exists in table '{}' in url {}".format(hash_hex,
                                                                                metadata_driver.login.table,
                                                                                metadata_driver.url))
            else:
                row = data[0]
                data_driver = locate(row[1])
                path = row[2]
                group_name = None if row[3] == "s/n" else row[3]
                name = row[0]
                return Data(name=name, group_name=group_name, driver=data_driver(path=path, mode="r"),
                            metadata_path=metadata_path, auto_chunks=auto_chunks)


text:
@interface JCHUPhotoViewController : UIViewController

@property (nonatomic, strong) UIImage *image;

@end


text:
from raptiformica.settings import conf
from raptiformica.settings.types import list_types_from_config
from tests.testcase import TestCase

class TestListTypesFromConfig(TestCase):
    def setUp(self):
        self.get_config = self.set_up_patch(
            'raptiformica.settings.types.get_config'
        )
        self.get_config.return_value = {
            conf().KEY_VALUE_PATH: {
                'server': {
                    'headless': {},
                    'workstation': {}
                }
            }
        }

    def test_list_types_from_config_gets_config(self):
        list_types_from_config('server')

        self.get_config.assert_called_once_with()

    def test_list_types_from_config_lists_types_from_config(self):
        ret = list_types_from_config('server')

        self.assertCountEqual(ret, ['headless', 'workstation'])

    def test_list_types_from_config_raises_keyerror_if_type_is_not_configured(self):
        with self.assertRaises(KeyError):
            list_types_from_config('compute')


text:
package com.metapatrol.gitlab.ci.runner.client.messages.response;

import com.metapatrol.gitlab.ci.runner.client.messages.response.api.Response;
import com.metapatrol.gitlab.ci.runner.client.messages.payload.response.RegisterRunnerResponsePayload;

/**
 * @author Denis Neuling (denisneuling@gmail.com)
 */
public class RegisterRunnerResponse extends Response<RegisterRunnerResponsePayload>{
}


text:
from __future__ import print_function
from __future__ import absolute_import
import os

import numpy as np
from numpy.testing.decorators import skipif
import tables

from metatlas.mzml_loader import mzml_to_hdf, get_test_data
from metatlas.h5_query import (
    get_chromatogram, get_data, get_spectrogram, get_heatmap,
    get_info)
from metatlas.plotting import (
    plot_heatmap, plot_spectrogram, plot_chromatogram
)

from metatlas.helpers import dill2plots as dp

from metatlas.helpers import metatlas_get_data_helper_fun as ma_data
from metatlas import metatlas_objects as metob
from metatlas.object_helpers import ON_NERSC
from ipywidgets import interact, interactive, fixed

@skipif(not ON_NERSC)
def test_interact_get_metatlas_files():
    experiment = '%violacein%'
    name = '%_%'
    most_recent = False
    files = dp.get_metatlas_files(experiment=experiment, name=name, most_recent=most_recent)
    assert len(files) == 1350

@skipif(not ON_NERSC)
def test_make_empty_fileinfo_sheet():
    experiment = '%violacein%'
    name = '%_%'
    most_recent = False
    f = dp.get_metatlas_files(experiment=experiment, name=name, most_recent=most_recent)
    temp_file_name = '/global/homes/b/bpb/Downloads/empty_violacein_384_finfo.tab'
    dp.make_empty_fileinfo_sheet(temp_file_name, f)

    # see if the file exits
    assert os.path.exists(temp_file_name)

    # let's read a line or two and prform a test on the content
    #with open(temp_file_name, 'r') as fin:


text:
require "sagn/admin/version"

module Sagn
  module Admin
    # Your code goes here...
  end
end


text:
package breeze.linalg

import breeze.generic.UFunc
import org.netlib.util.intW
import com.github.fommil.netlib.LAPACK.{getInstance=>lapack}

/**
 * Computes the cholesky decomposition A of the given real symmetric
 * positive definite matrix X such that X = A A.t.
 *
 * TODO: For higher dimensionalities, the return value really should be a sparse matrix
 *       due to its inherent lower triangular nature.
 */
object cholesky extends UFunc {
  implicit object ImplCholesky_DM extends Impl[DenseMatrix[Double], DenseMatrix[Double]] {
    def apply(X: DenseMatrix[Double]): DenseMatrix[Double] = {
      requireNonEmptyMatrix(X)

      // As LAPACK doesn't check if the given matrix is in fact symmetric,
      // we have to do it here (or get rid of this time-waster as long as
      // the caller of this function is clearly aware that only the lower
      // triangular portion of the given matrix is used and there is no
      // check for symmetry).
      requireSymmetricMatrix(X)

      // Copy the lower triangular part of X. LAPACK will store the result in A
      val A: DenseMatrix[Double] = lowerTriangular(X)

      val N = X.rows
      val info = new intW(0)
      lapack.dpotrf(
        "L" /* lower triangular */,
        N /* number of rows */, A.data, scala.math.max(1, N) /* LDA */,
        info
      )
      // A value of info.`val` < 0 would tell us that the i-th argument
      // of the call to dpotrf was erroneous (where i == |info.`val`|).
      assert(info.`val` >= 0)

      if (info.`val` > 0)
        throw new NotConvergedException(NotConvergedException.Iterations)

      A
    }

  }
}


text:
********
Mac (using homebrew -- recommended for mac)
********

We have provided some scripts to simplify the installation of prerequisites.  However, we do assume that you have already installed

* XQuartz / X11
* XCode and the command line tools (``xcode-select --install``)

Now you can install the prerequistes::

	brew update
	brew install cmake
	cd drake-distro
	make options # use the gui to choose which externals you want, then press c to configure, then g to generate makefiles and exit
	make download-all
	./install_prereqs.sh homebrew

Finally, add the line::

	export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/opt/X11/lib/pkgconfig

to your ``.bash_profile`` or ``.bashrc``.

When you're done with these platform-specific steps, return to :doc:`from_source` to complete and test your installation.


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;

namespace IdentityModel;

/// <summary>
/// Helper class to create ClaimsPrincipal
/// </summary>
public static class Principal
{
    /// <summary>
    /// Gets an anoymous ClaimsPrincipal.
    /// </summary>
    public static ClaimsPrincipal Anonymous => new ClaimsPrincipal(Identity.Anonymous);

    /// <summary>
    /// Creates a ClaimsPrincipal using the specified authentication type and claims.
    /// </summary>
    /// <param name="authenticationType">Type of the authentication.</param>
    /// <param name="claims">The claims.</param>
    /// <returns></returns>
    public static ClaimsPrincipal Create(string authenticationType, params Claim[] claims)
    {
        return new ClaimsPrincipal(Identity.Create(authenticationType, claims));
    }

    /// <summary>
    /// Creates a ClaimsPrincipal based on information found in an X509 certificate.
    /// </summary>
    /// <param name="certificate">The certificate.</param>
    /// <param name="authenticationType">Type of the authentication.</param>
    /// <param name="includeAllClaims">if set to <c>true</c> [include all claims].</param>
    /// <returns></returns>
    public static ClaimsPrincipal CreateFromCertificate(X509Certificate2 certificate, string authenticationType = "X.509", bool includeAllClaims = false)
    {
        return new ClaimsPrincipal(Identity.CreateFromCertificate(certificate, authenticationType, includeAllClaims));
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>NEGATED :only-child pseudo-class</title>

  <link rel="first" href="css3-modsel-1.xml" title="Groups of selectors"/>
  <link rel="prev" href="css3-modsel-81.xml" title="NEGATED :only-child pseudo-class"/>
  <link rel="next" href="css3-modsel-82.xml" title="NEGATED :only-of-type pseudo-class"/>
  <link rel="last" href="css3-modsel-d4.xml" title="Dynamic updating of :first-child and :last-child"/>
  <link rel="up" href="./index.html"/>
  <link rel="top" href="../../index.html"/>

This paragraph should have a green background.

This div contains only one paragraph.

This paragraph should be unstyled.


text:
namespace autofill {
// Default encryptor used in Autofill table.
class SystemEncryptor : public AutofillTableEncryptor {
 public:
  SystemEncryptor() = default;
  ~SystemEncryptor() override = default;

  bool EncryptString16(const base::string16& plaintext,
                       std::string* ciphertext) const override;

  bool DecryptString16(const std::string& ciphertext,
                       base::string16* plaintext) const override;

 private:
  DISALLOW_COPY_AND_ASSIGN(SystemEncryptor);
};

}  // namespace autofill

#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_WEBDATA_SYSTEM_ENCRYPTOR_H_


text:
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery                                    |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2014 Piwigo Team                  http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify  |
// | it under the terms of the GNU General Public License as published by  |
// | the Free Software Foundation                                          |
// |                                                                       |
// | This program is distributed in the hope that it will be useful, but   |
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
// | General Public License for more details.                              |
// |                                                                       |
// | You should have received a copy of the GNU General Public License     |
// | along with this program; if not, write to the Free Software           |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA.                                                                  |
// +-----------------------------------------------------------------------+
$lang['Choose what should be the default state for each panel, or disable the animation:'] = 'وضعیت پیشفرضِ هر پنل را انتخاب کنید، یا حالت انیمیشن آنها را غیر فعال کنید:';
$lang['Comments Panel'] = 'پنلِ توضیحات';
$lang['Disable the animation'] = 'غیر فعال کردنِ انیمیشن';
$lang['Displayed'] = 'نمایش داده شود';
$lang['Elegant, Configuration Page'] = 'پیکربندیِ Elegant';
$lang['Hidden'] = 'پنهان';
$lang['Main Menu Panel'] = 'پنلِ منوی اصلی';
$lang['Panels options'] = 'گزینه‌های پنل‌ها';
$lang['Photo Description Panel'] = 'پنلِ توضیحاتِ عکس';
?>


text:
using Slagen.Domain.Services;

namespace Slagen.Domain.Specs.Stubs
{
    public class TestCommandHandler : ICommandHandler<TestCommand>
    {
        public TestCommand CommandHandled { get; private set; }

        public void Handle(IUserSession userIssuingCommand, TestCommand command)
        {
            CommandHandled = command;
            if (NotifyObservers != null) NotifyObservers(new TestEvent(command));
        }

        public event DomainEvent NotifyObservers;
    }
}


text:
FOUNDATION_EXPORT double Pods_TwitterDemoVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_TwitterDemoVersionString[];


text:
package org.apache.shardingsphere.driver.jdbc.core.statement;

import org.apache.shardingsphere.driver.jdbc.base.AbstractShardingSphereDataSourceForReadwriteSplittingTest;
import org.junit.Test;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public final class ReadwriteSplittingStatementTest extends AbstractShardingSphereDataSourceForReadwriteSplittingTest {

    @Test(expected = SQLException.class)
    public void assertQueryWithNull() throws SQLException {
        try (Statement statement = getReadwriteSplittingDataSource().getConnection().createStatement()) {
            statement.executeQuery(null);
        }
    }

    @Test(expected = SQLException.class)
    public void assertQueryWithEmptyString() throws SQLException {
        try (Statement statement = getReadwriteSplittingDataSource().getConnection().createStatement()) {
            statement.executeQuery("");
        }
    }

    @Test
    public void assertGetGeneratedKeys() throws SQLException {
        try (Statement statement = getReadwriteSplittingDataSource().getConnection().createStatement()) {
            statement.executeUpdate("INSERT INTO t_config(status) VALUES('OK');", Statement.RETURN_GENERATED_KEYS);
            ResultSet generatedKeys = statement.getGeneratedKeys();
            assertTrue(generatedKeys.next());
            int columnCount = generatedKeys.getMetaData().getColumnCount();
            for (int index = 0; index < columnCount; index++) {
                assertNotNull(generatedKeys.getObject(index + 1));
                assertNotNull(generatedKeys.getMetaData().getColumnLabel(index + 1));
                assertNotNull(generatedKeys.getMetaData().getColumnName(index + 1));
            }
            assertFalse(generatedKeys.next());
        }
    }
}


text:
package liqp.tags;

import liqp.nodes.LNode;

import java.util.Map;

class Unless extends Tag {

    /*
     * Mirror of if statement
     */
    @Override
    public Object render(Map<String, Object> context, LNode... nodes) {

        for (int i = 0; i < nodes.length - 1; i += 2) {

            Object exprNodeValue = nodes[i].render(context);
            LNode blockNode = nodes[i + 1];

            if (!super.asBoolean(exprNodeValue)) {
                return blockNode.render(context);
            }
        }

        return "";
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" type="text/css" href="css/index.css">

    <title>Corodva TaobaoBaichuan Plugin Exmaple</title>

        <button type="button" id="bt_item" class="btn btn-primary btn-block">打开原生商品页面</button>
        <button type="button" id="bt_itemh5" class="btn btn-primary btn-block">打开H5商品页面</button>
        <button type="button" id="bt_order" class="btn btn-primary btn-block">打开订单页面</button>
        <button type="button" id="bt_cart" class="btn btn-primary btn-block">打开购物车页面</button>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2013 Simeon Malchev
  ~
  ~ 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.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.vibur</groupId>
    <artifactId>vibur-dbcp-hibernate3</artifactId>
    <version>22.0-SNAPSHOT</version>
    <packaging>bundle</packaging>

    <name>Vibur DBCP - Hibernate3 Integration</name>
    <description>Hibernate3 integration for Vibur DBCP.</description>
    <url>http://www.vibur.org</url>
    <inceptionYear>2013</inceptionYear>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <!--<parent>-->
        <!--<groupId>org.sonatype.oss</groupId>-->
        <!--<artifactId>oss-parent</artifactId>-->
        <!--<version>7</version>-->
    <!--</parent>-->

    <scm>
        <connection>scm:git:https://github.com/vibur/vibur-dbcp-hibernate3.git/</connection>
        <developerConnection>scm:git:https://github.com/vibur/vibur-dbcp-hibernate3.git/</developerConnection>
        <url>https://github.com/vibur/vibur-dbcp-hibernate3/tree/master/</url>
      <tag>HEAD</tag>
  </scm>

    <developers>
        <developer>
            <name>Simeon Malchev</name>
            <email>simeon.malchev@gmail.com</email>
            <id>simeonmalchev</id>
            <url>http://simeonmalchev.com</url>
            <timezone>+10</timezone>
            <roles>
                <role>owner</role>
                <role>developer</role>
            </roles>
        </developer>
    </developers>

    <organization>
        <name>vibur.org</name>
        <url>http://www.vibur.org</url>
    </organization>

    <issueManagement>
        <system>https://github.com</system>
        <url>https://github.com/vibur/vibur-dbcp-hibernate3/issues</url>
    </issueManagement>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <java.version>1.7</java.version>
        <vibur.osgi.version>22.0</vibur.osgi.version>
        <concurrentlinkedhashmap-lru.version>1.4.2</concurrentlinkedhashmap-lru.version>
        <slf4j.version>1.7.13</slf4j.version>
        <hibernate-core.version>3.6.10.Final</hibernate-core.version>

        <junit.version>4.12</junit.version>
        <mockito-all.version>1.10.19</mockito-all.version>
        <hsqldb.version>2.3.3</hsqldb.version>
        <javassist.version>3.20.0-GA</javassist.version>

        <maven.compiler.plugin.version>2.3.2</maven.compiler.plugin.version>
        <maven.bundle.plugin.version>3.0.0</maven.bundle.plugin.version>
        <maven.release.plugin.version>2.4.2</maven.release.plugin.version>
        <maven.javadoc.plugin.version>2.8</maven.javadoc.plugin.version>
        <maven.jar.plugin.version>2.4</maven.jar.plugin.version>
        <maven.source.plugin.version>2.1.2</maven.source.plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.vibur</groupId>
            <artifactId>vibur-dbcp</artifactId>
            <version>22.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.concurrentlinkedhashmap</groupId>
            <artifactId>concurrentlinkedhashmap-lru</artifactId>
            <version>${concurrentlinkedhashmap-lru.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.vibur</groupId>
            <artifactId>vibur-dbcp</artifactId>
            <version>22.0-SNAPSHOT</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Hibernate3 dependency, optional. -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate-core.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>${javassist.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>${hsqldb.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>sqltool</artifactId>
            <version>${hsqldb.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>${mockito-all.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>${maven.bundle.plugin.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-Name>${project.artifactId}</Bundle-Name>
                        <Export-Package>
                            org.vibur.dbcp.integration
                        </Export-Package>
                        <Import-Package>
                            org.hibernate;version="[3.6,4)",
                            org.hibernate.cfg;version="[3.6,4)",
                            org.hibernate.connection;version="[3.6,4)",
                            org.vibur.dbcp;version="[${version;==;${vibur.osgi.version}},${version;+;${vibur.osgi.version}})"
                        </Import-Package>
                        <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
                    </instructions>
                </configuration>
                <executions>
                    <execution>
                        <id>bundle-manifest</id>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>manifest</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>${maven.release.plugin.version}</version>
				<dependencies>
					<dependency>
						<groupId>org.apache.maven.scm</groupId>
						<artifactId>maven-scm-provider-gitexe</artifactId>
						<version>1.8.1</version>
					</dependency>
				</dependencies>
                <configuration>
                    <goals>deploy</goals>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${maven.javadoc.plugin.version}</version>
                <configuration>
                    <additionalparam>-Xdoclint:none</additionalparam>
                    <reportOutputDirectory>${project.basedir}</reportOutputDirectory>
                    <destDir>doc</destDir>
                </configuration>
                <executions>
                    <execution>
                        <id>aggregate</id>
                        <goals>
                            <goal>aggregate</goal>
                        </goals>
                        <phase>site</phase>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>${maven.jar.plugin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>${maven.source.plugin.version}</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>deploy-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
import * as functions from "firebase-functions";
import vision from "@google-cloud/vision";

const client = new vision.ImageAnnotatorClient();

// This will allow only requests with an auth token to access the Vision
// API, including anonymous ones.
// It is highly recommended to limit access only to signed-in users. This may
// be done by adding the following condition to the if statement:
//    || context.auth.token?.firebase?.sign_in_provider === 'anonymous'
//
// For more fine-grained control, you may add additional failure checks, ie:
//    || context.auth.token?.firebase?.email_verified === false
// Also see: https://firebase.google.com/docs/auth/admin/custom-claims
export const annotateImage = functions.https.onCall(async (data, context) => {
  if (!context.auth) {
    throw new functions.https.HttpsError(
      "unauthenticated",
      "annotateImage must be called while authenticated."
    );
  }
  try {
    return await client.annotateImage(JSON.parse(data));
  } catch (e) {
    throw new functions.https.HttpsError("internal", e.message, e.details);
  }
});


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * @see BxBaseServiceLogin
 */
class BxTemplServiceLogin extends BxBaseServiceLogin
{
    public function __construct()
    {
        parent::__construct();
    }
}

/** @} */


text:
package org.appyx.utli.jkvo;

/**
 * This interface is used in combination with JKVObservable
 */
public interface JKVObserver {

	String KVO_WILL_CHANGE = "org.appyx.util.jkvo.kvo.will.change";
	String KVO_DID_CHANGE = "org.appyx.util.jkvo.kvo.did.change";

	/**
	 * This method is triggered if an observed value will/did change
	 *
	 * @param value  The observed value
	 * @param tag    The observing identifier
	 * @param change can either be KVO_WILL_CHANGE or KVO_DID_CHANGE
	 */
	void observeValue(Object value, String tag, String change);
}


text:
"use strict";

describe("Backlog", function () {});

exports.create = function create(_ref) {
  var document = _ref.document;

  return document.data;
};


text:
package wseemann.media.romote.tasks;

import android.content.Context;
import android.util.Log;

import com.jaku.api.DeviceRequests;
import com.jaku.api.QueryRequests;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import wseemann.media.romote.model.ClientScanResult;
import wseemann.media.romote.model.Device;
import wseemann.media.romote.utils.WifiApManager;
import wseemann.media.romote.utils.DBUtils;

public class AvailableDevicesTask implements Callable {

    private static final String TAG = AvailableDevicesTask.class.getName();

    private Context context;
    private boolean filterPairedDevices;

    public AvailableDevicesTask(final Context context) {
        this(context, true);
    }

    public AvailableDevicesTask(final Context context, boolean filterPairedDevices) {
        this.context = context;
        this.filterPairedDevices = filterPairedDevices;
    }

    public List<Device> call() {
        // Retrieve all Devices.
        List<wseemann.media.romote.model.Device> devices = new ArrayList();

        if (filterPairedDevices) {
            devices = DBUtils.getAllDevices(context);
        }

        List<Device> availableDevices = new ArrayList<Device>();

        try {
            List<Device> rokuDevices = new ArrayList<>();

            final WifiApManager wifiApManager = new WifiApManager(context);

            if (wifiApManager.isWifiApEnabled()) {
                // Scan the mobile access point for devices
                rokuDevices.addAll(scanAccessPointForDevices());
            } else {
                List<com.jaku.model.Device> jakuDevices = DeviceRequests.discoverDevices();

                for (com.jaku.model.Device jakuDevice: jakuDevices) {
                    rokuDevices.add(Device.Companion.fromDevice(jakuDevice));
                }
            }

            for (Device device: rokuDevices) {
                boolean exists = false;

                for (int j = 0; j < devices.size(); j++) {
                    if (devices.get(j).getSerialNumber().equals(device.getSerialNumber())) {
                        exists = true;
                        break;
                    }
                }

                if (!exists) {
                    availableDevices.add(device);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // Done!
        return availableDevices;
    }

    private ArrayList<Device> scanAccessPointForDevices() {
        ArrayList<Device> availableDevices = new ArrayList<Device>();

        final WifiApManager wifiApManager = new WifiApManager(context);

        if (wifiApManager.isWifiApEnabled()) {
            ArrayList<ClientScanResult> clients = wifiApManager.getClientList(false, 3000);

            Log.d(TAG, "Access point scan completed.");

            if (clients != null) {
                Log.d(TAG, "Found " + clients.size() + " connected devices.");

                for (ClientScanResult clientScanResult: clients) {
                    Log.d(TAG, "Device: " + clientScanResult.getDevice() +
                            " HW Address: " + clientScanResult.getHWAddr() +
                            " IP Address:  " + clientScanResult.getIpAddr());

                    try {
                        Device device = Device.Companion.fromDevice(QueryRequests.queryDeviceInfo("http://" + clientScanResult.getIpAddr() + ":8060"));
                        device.setHost("http://" + clientScanResult.getIpAddr() + ":8060");
                        availableDevices.add(device);
                    } catch (IOException ex) {
                        Log.e(TAG, "Invalid device: " + ex.getMessage());
                    }
                }
            }
        }

        return availableDevices;
    }
}


text:
package org.apache.felix.dm.runtime.itest.tests;

/**
 * @author Felix Project Team
 */
public class BundleDependencyAnnotationParallelTest extends BundleDependencyAnnotationTest {
    public BundleDependencyAnnotationParallelTest() {
        setParallel();
    }
}


text:
from __future__ import absolute_import, division, print_function

from numbers import Number

import numpy as np
from scipy.sparse import issparse

from pymor.core import NUMPY_INDEX_QUIRK
from pymor.la.interfaces import VectorArrayInterface, VectorSpace
from pymor.tools.floatcmp import float_cmp

class NumpyVectorArray(VectorArrayInterface):
    """|VectorArray| implementation via |NumPy arrays|.

    This is the default |VectorArray| type used by all |Operators|
    implemented directly in pyMOR. Reduced |Operators| will also
    expect |NumpyVectorArrays|.

    Note that this class is just a thin wrapper around the underlying
    |NumPy array|. Thus, while operations like
    :meth:`~VectorArrayInterface.axpy` or :meth:`VectorArrayInterface.dot`
    will be quite efficient, removing or appending vectors will
    be costly.
    """

    def __init__(self, instance, dtype=None, copy=False, order=None, subok=False):
        assert not isinstance(instance, np.matrixlib.defmatrix.matrix)
        if isinstance(instance, np.ndarray):
            if copy:
                self._array = instance.copy()
            else:
                self._array = instance
        elif issparse(instance):
            self._array = np.array(instance.todense(), copy=False)
        elif hasattr(instance, 'data'):
            self._array = instance.data
            if copy:
                self._array = self._array.copy()
        else:
            self._array = np.array(instance, dtype=dtype, copy=copy, order=order, subok=subok, ndmin=2)
        if self._array.ndim != 2:
            assert self._array.ndim == 1
            self._array = np.reshape(self._array, (1, -1))
        self._len = len(self._array)

    @classmethod
    def make_array(cls, subtype=None, count=0, reserve=0):
        assert isinstance(subtype, Number)
        assert count >= 0
        assert reserve >= 0
        va = NumpyVectorArray(np.empty((0, 0)))
        va._array = np.zeros((max(count, reserve), subtype))
        va._len = count
        return va

    @property
    def data(self):
        return self._array[:self._len]

    def __len__(self):
        return self._len

    @property
    def subtype(self):
        return self._array.shape[1]

    @property
    def dim(self):
        return self._array.shape[1]

    def copy(self, ind=None):
        assert self.check_ind(ind)

        if NUMPY_INDEX_QUIRK and self._len == 0:
            return NumpyVectorArray(self._array[:0], copy=True)

        if ind is None:
            return NumpyVectorArray(self._array[:self._len], copy=True)
        else:
            C = NumpyVectorArray(self._array[ind], copy=False)
            if not C._array.flags['OWNDATA']:
                C._array = np.array(C._array)
            return C

    def append(self, other, o_ind=None, remove_from_other=False):
        assert other.check_ind(o_ind)
        assert self.dim == other.dim
        assert other is not self or not remove_from_other

        if NUMPY_INDEX_QUIRK and other._len == 0:
            o_ind = None

        if o_ind is None:
            len_other = other._len
            if len_other <= self._array.shape[0] - self._len:
                self._array[self._len:self._len + len_other] = other._array
            else:
                self._array = np.vstack((self._array[:self._len], other._array[:len_other]))
            self._len += len_other
        else:
            if not hasattr(o_ind, '__len__'):
                len_other = 1
                o_ind = [o_ind]
            else:
                len_other = len(o_ind)
            if len_other <= self._array.shape[0] - self._len:
                other._array.take(o_ind, axis=0, out=self._array[self._len:self._len + len_other])
            else:
                self._array = np.append(self._array[:self._len], other._array[o_ind], axis=0)
            self._len += len_other
        if remove_from_other:
            other.remove(o_ind)

    def remove(self, ind=None):
        assert self.check_ind(ind)

        if ind is None:
            self._array = np.zeros((0, self.dim))
            self._len = 0
        else:
            if hasattr(ind, '__len__'):
                if len(ind) == 0:
                    return
                remaining = sorted(set(xrange(len(self))) - set(ind))
                self._array = self._array[remaining]
            else:
                assert -self._len < ind < self._len
                self._array = self._array[range(ind) + range(ind + 1, self._len)]
            self._len = self._array.shape[0]
        if not self._array.flags['OWNDATA']:
            self._array = self._array.copy()

    def replace(self, other, ind=None, o_ind=None, remove_from_other=False):
        assert self.check_ind_unique(ind)
        assert other.check_ind(o_ind)
        assert self.dim == other.dim
        assert other is not self or not remove_from_other

        if NUMPY_INDEX_QUIRK:
            if self._len == 0 and hasattr(ind, '__len__'):
                ind = None
            if other._len == 0 and hasattr(o_ind, '__len__'):
                o_ind = None

        if ind is None:
            if o_ind is None:
                if other is self:
                    return
                assert other._len == self._len
                self._array = other._array[:other._len].copy()
            else:
                if not hasattr(o_ind, '__len__'):
                    o_ind = [o_ind]
                assert self._len == len(o_ind)
                self._array = other._array[o_ind]
            self._len = self._array.shape[0]
        else:
            len_ind = self.len_ind(ind)
            other_array = np.array(self._array) if other is self else other._array
            if o_ind is None:
                assert len_ind == other._len
                self._array[ind] = other_array[:other._len]
            else:
                len_oind = other.len_ind(o_ind)
                assert len_ind == len_oind
                self._array[ind] = other_array[o_ind]
        assert self._array.flags['OWNDATA']

        if remove_from_other:
            other.remove(o_ind)

    def almost_equal(self, other, ind=None, o_ind=None, rtol=None, atol=None):
        assert self.check_ind(ind)
        assert other.check_ind(o_ind)
        assert self.dim == other.dim

        if NUMPY_INDEX_QUIRK:
            if self._len == 0 and hasattr(ind, '__len__'):
                ind = None
            if other._len == 0 and hasattr(o_ind, '__len__'):
                o_ind = None

        A = self._array[:self._len] if ind is None else \
            self._array[ind] if hasattr(ind, '__len__') else self._array[ind:ind + 1]
        B = other._array[:other._len] if o_ind is None else \
            other._array[o_ind] if hasattr(o_ind, '__len__') else other._array[o_ind:o_ind + 1]

        R = np.all(float_cmp(A, B, rtol=rtol, atol=atol), axis=1).squeeze()
        if R.ndim == 0:
            R = R[np.newaxis, ...]
        return R

    def scal(self, alpha, ind=None):
        assert self.check_ind_unique(ind)
        assert isinstance(alpha, Number) \
            or isinstance(alpha, np.ndarray) and alpha.shape == (self.len_ind(ind),)

        if NUMPY_INDEX_QUIRK and self._len == 0:
            return

        if isinstance(alpha, np.ndarray) and not isinstance(ind, Number):
            alpha = alpha[:, np.newaxis]
        if ind is None:
            self._array[:self._len] *= alpha
        else:
            self._array[ind] *= alpha

    def axpy(self, alpha, x, ind=None, x_ind=None):
        assert self.check_ind_unique(ind)
        assert x.check_ind(x_ind)
        assert self.dim == x.dim
        assert self.len_ind(ind) == x.len_ind(x_ind) or x.len_ind(x_ind) == 1
        assert isinstance(alpha, Number) \
            or isinstance(alpha, np.ndarray) and alpha.shape == (self.len_ind(ind),)

        if NUMPY_INDEX_QUIRK:
            if self._len == 0 and hasattr(ind, '__len__'):
                ind = None
            if x._len == 0 and hasattr(x_ind, '__len__'):
                x_ind = None

        if np.all(alpha == 0):
            return

        B = x._array[:x._len] if x_ind is None else x._array[x_ind]

        if np.all(alpha == 1):
            if ind is None:
                self._array[:self._len] += B
            elif isinstance(ind, Number) and B.ndim == 2:
                self._array[ind] += B.reshape((B.shape[1],))
            else:
                self._array[ind] += B
        elif np.all(alpha == -1):
            if ind is None:
                self._array[:self._len] -= B
            elif isinstance(ind, Number) and B.ndim == 2:
                self._array[ind] -= B.reshape((B.shape[1],))
            else:
                self._array[ind] -= B
        else:
            if isinstance(alpha, np.ndarray):
                alpha = alpha[:, np.newaxis]
            if ind is None:
                self._array[:self._len] += (B * alpha)
            elif isinstance(ind, Number):
                self._array[ind] += (B * alpha).reshape((-1,))
            else:
                self._array[ind] += (B * alpha)

    def dot(self, other, pairwise, ind=None, o_ind=None):
        assert self.check_ind(ind)
        assert other.check_ind(o_ind)
        assert self.dim == other.dim

        if NUMPY_INDEX_QUIRK:
            if self._len == 0 and hasattr(ind, '__len__'):
                ind = None
            if other._len == 0 and hasattr(o_ind, '__len__'):
                o_ind = None

        A = self._array[:self._len] if ind is None else \
            self._array[ind] if hasattr(ind, '__len__') else self._array[ind:ind + 1]
        B = other._array[:other._len] if o_ind is None else \
            other._array[o_ind] if hasattr(o_ind, '__len__') else other._array[o_ind:o_ind + 1]

        if pairwise:
            assert self.len_ind(ind) == other.len_ind(o_ind)
            return np.sum(A * B, axis=1)
        else:
            return A.dot(B.T)

    def lincomb(self, coefficients, ind=None):
        assert self.check_ind(ind)
        assert 1 <= coefficients.ndim <= 2

        if NUMPY_INDEX_QUIRK and self._len == 0:
            ind = None

        if coefficients.ndim == 1:
            coefficients = coefficients[np.newaxis, ...]

        assert ind is None and coefficients.shape[1] == len(self) \
            or not hasattr(ind, '__len__') and coefficients.shape[1] == 1 \
            or hasattr(ind, '__len__') and coefficients.shape[1] == len(ind)

        if ind is None:
            return NumpyVectorArray(coefficients.dot(self._array[:self._len]), copy=False)
        elif hasattr(ind, '__len__'):
            return NumpyVectorArray(coefficients.dot(self._array[ind]), copy=False)
        else:
            return NumpyVectorArray(coefficients.dot(self._array[ind:ind + 1]), copy=False)

    def l1_norm(self, ind=None):
        assert self.check_ind(ind)

        if NUMPY_INDEX_QUIRK and self._len == 0:
            ind = None

        A = self._array[:self._len] if ind is None else \
            self._array[ind] if hasattr(ind, '__len__') else self._array[ind:ind + 1]

        return np.sum(np.abs(A), axis=1)

    def l2_norm(self, ind=None):
        assert self.check_ind(ind)

        if NUMPY_INDEX_QUIRK and self._len == 0:
            ind = None

        A = self._array[:self._len] if ind is None else \
            self._array[ind] if hasattr(ind, '__len__') else self._array[ind:ind + 1]

        return np.sum(np.power(A, 2), axis=1)**(1/2)

    def components(self, component_indices, ind=None):
        assert self.check_ind(ind)
        assert isinstance(component_indices, list) and (len(component_indices) == 0 or min(component_indices) >= 0) \
            or (isinstance(component_indices, np.ndarray) and component_indices.ndim == 1
                and (len(component_indices) == 0 or np.min(component_indices) >= 0))
        # NumPy 1.9 is quite permissive when indexing arrays of size 0, so we have to add the
        # following check:
        assert self._len > 0 \
            or (isinstance(component_indices, list)
                and (len(component_indices) == 0 or max(component_indices) < self.dim)) \
            or (isinstance(component_indices, np.ndarray) and component_indices.ndim == 1
                and (len(component_indices) == 0 or np.max(component_indices) < self.dim))

        if NUMPY_INDEX_QUIRK and (self._len == 0 or self.dim == 0):
            assert isinstance(component_indices, list) \
                and (len(component_indices) == 0 or max(component_indices) < self.dim) \
                or isinstance(component_indices, np.ndarray) \
                and component_indices.ndim == 1 \
                and (len(component_indices) == 0 or np.max(component_indices) < self.dim)
            return np.zeros((self.len_ind(ind), len(component_indices)))

        if ind is None:
            return self._array[:self._len, component_indices]
        else:
            if not hasattr(ind, '__len__'):
                ind = [ind]
            return self._array[:, component_indices][ind, :]

    def amax(self, ind=None):
        assert self.dim > 0
        assert self.check_ind(ind)

        if NUMPY_INDEX_QUIRK and self._len == 0:
            ind = None

        if self._array.shape[1] == 0:
            l = self.len_ind(ind)
            return np.ones(l) * -1, np.zeros(l)

        A = self._array[:self._len] if ind is None else \
            self._array[ind] if hasattr(ind, '__len__') else self._array[ind:ind + 1]

        A = np.abs(A)
        max_ind = np.argmax(A, axis=1)
        max_val = A[np.arange(len(A)), max_ind]
        return max_ind, max_val

    def __str__(self):
        return self._array[:self._len].__str__()

    def __repr__(self):
        return 'NumpyVectorArray({})'.format(self._array[:self._len].__str__())

def NumpyVectorSpace(dim):
    """Shorthand for |VectorSpace| `(NumpyVectorArray, dim)`."""
    return VectorSpace(NumpyVectorArray, dim)


text:
#include "config.h"

#include "core/svg/graphics/filters/SVGFilter.h"

namespace blink {

SVGFilter::SVGFilter(const IntRect& absoluteSourceDrawingRegion, const FloatRect& targetBoundingBox, const FloatRect& filterRegion, bool effectBBoxMode)
    : Filter(targetBoundingBox, filterRegion, 1.0f)
    , m_absoluteSourceDrawingRegion(absoluteSourceDrawingRegion)
    , m_effectBBoxMode(effectBBoxMode)
{
}

float SVGFilter::applyHorizontalScale(float value) const
{
    if (m_effectBBoxMode)
        value *= targetBoundingBox().width();
    return Filter::applyHorizontalScale(value);
}

float SVGFilter::applyVerticalScale(float value) const
{
    if (m_effectBBoxMode)
        value *= targetBoundingBox().height();
    return Filter::applyVerticalScale(value);
}

FloatPoint3D SVGFilter::resolve3dPoint(const FloatPoint3D& point) const
{
    if (!m_effectBBoxMode)
        return point;
    return FloatPoint3D(point.x() * targetBoundingBox().width() + targetBoundingBox().x(),
        point.y() * targetBoundingBox().height() + targetBoundingBox().y(),
        point.z() * sqrtf(targetBoundingBox().size().diagonalLengthSquared() / 2));
}

PassRefPtrWillBeRawPtr<SVGFilter> SVGFilter::create(const IntRect& absoluteSourceDrawingRegion, const FloatRect& targetBoundingBox, const FloatRect& filterRegion, bool effectBBoxMode)
{
    return adoptRefWillBeNoop(new SVGFilter(absoluteSourceDrawingRegion, targetBoundingBox, filterRegion, effectBBoxMode));
}

} // namespace blink


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

	<bean id="TestRegistry" name="TestRegistry"
		class="org.socraticgrid.hl7.services.orders.functional.ServiceRegistry"
		scope="singleton" primary="true">
		<property name="serviceMap">
			<map>
				<entry key="test">
					<bean
						class="org.socraticgrid.hl7.services.orders.engines.fulfillment.DoNothingFulfillmentEngine" />
				</entry>

				<entry
					key="org.socraticgrid.hl7.services.orders.model.types.order.LabOrder" value-ref="LabOrder">
				</entry>
				<entry key="MedicationOrder">
					<bean
						class="org.socraticgrid.hl7.services.orders.engines.fulfillment.DoNothingFulfillmentEngine" />
				</entry>
				<entry
					key="org.socraticgrid.hl7.services.orders.model.types.order.MedicationOrder" value-ref="MedicationOrder">
				</entry>
			</map>
		</property>
	</bean>
	<bean
		class="org.socraticgrid.hl7.services.orders.engines.fulfillment.FulfillmentServiceEngine"
		name="MedicationOrder" id="MedicationOrder">
		<property name="endpoint"
			value="http://172.31.5.104/csp/cpm/OrderFulfillment.Service.FulfillmentPort.cls"></property>
	</bean>

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


text:
![UK Transport Banner](http://smallstoneapps.s3.amazonaws.com/dots/marketing/header_01.png)

This is a simple custom watchface for the [Pebble Smartwatch][1] using dots to display the current time.

![Available on the Pebble App Store](http://wearewearable.com/appstore/PebbleAppStore.png)

#### Screenshots

![Screenshot 01](http://smallstoneapps.s3.amazonaws.com/dots/screenshots/dots_2-0_01.png)

#### Installation

*You will need the latest Pebble 2.0 (BETA5) installed on your Pebble for this app to run.*

[![Install QR Code](http://smallstoneapps.s3.amazonaws.com/dots/qr/dots_2-0_qr.png)][2]

**Latest PBW:** [Dots 2.0][2]

--

[![Analytics](https://ga-beacon.appspot.com/UA-37478501-3/smallstoneapps/dots/readme)](https://github.com/igrigorik/ga-beacon)

[1]: http://getpebble.com
[2]: http://smallstoneapps.s3.amazonaws.com/dots/builds/dots_2-0.pbw


text:
<?xml version="1.0" encoding="UTF-8"?>
<patientSearch>
   <!-- min and max -1 means no length check -->
   <!-- id format="LLLLLLNNLNNLNNNL" means 'L'etter 'N'umber -->
   <!-- validation contains the fields which are mandatory -->
   <!-- more then one validation means or -->
   <!-- only one input field no validation necessary because minimum value which has to be filled out is 1 -->
   <country code="DE">
      <searchFields>
         <id label="patient.data.pseudonym" min="-1" max="-1" domain="2.16.17.710.790.1000.990.1" />
         <id label="patient.data.tan.code" min="-1" max="-1" domain="2.16.17.710.790.1000.990.1" />
      </searchFields>
      <validation>
         <field label="patient.data.pseudonym" />
         <field label="patient.data.tan.code" />
      </validation>
   </country>
</patientSearch>


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2017] 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

=pod

=head1 NAME

Bio::EnsEMBL::Compara::Production::Projection::Writer::ProjectedFileWriter

=head1 DESCRIPTION

This class writes out to a file location given at construction time using
Text::CSV. If this is not present this class will not work.

=head1 AUTHOR

Andy Yates (ayatesatebiacuk)

=head1 CONTACT

This modules is part of the EnsEMBL project (http://www.ensembl.org)

Questions can be posted to the dev mailing list: http://lists.ensembl.org/mailman/listinfo/dev

=cut

package Bio::EnsEMBL::Compara::Production::Projection::Writer::ProjectedFileWriter;

use strict;
use warnings;
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Scalar qw(assert_ref);
use Bio::EnsEMBL::Utils::Exception qw(throw);

use File::Copy;
use IO::Handle;
use IO::File;

use base qw(Bio::EnsEMBL::Compara::Production::Projection::Writer::BaseWriter);

=head2 new()

  Arg[-file] : required if file_handle is not given;
  Arg[-file_handle] : required if file is not given;
  Description : New method used for a new instance of the given object.
                Required fields are indicated accordingly. Fields are specified
                using the Arguments syntax (case insensitive).

=cut

sub new {
  my ( $class, @args ) = @_;
  my $self = $class->SUPER::new(@args);
  my ( $file, $file_handle ) = rearrange( [qw(file file_handle)], @args );

  confess(
'The attribute file or file_handle must be specified during construction or provide a builder subroutine'
  ) if !defined $file && ! defined $file_handle;
  $self->{file} = $file if defined $file;
  $self->{file_handle} = $file_handle if defined $file_handle;

  return $self;
}

=head2 write_projection()

Writes the projection data to configured file handle or to the given
file location. The output is a CSV of the following columns:

=over 8

=item DBEntry accession

=item Source's stable ID i.e. the object the transferred accession was originally attached to

=item Target's stable ID i.e. the end point for this transfer

=item Source's % identity

=item Target's % identity

=item Type of homology

=back

=cut

sub write_projection {
  my ($self, $p) = @_;
  my $csv = $self->_csv_writer();
  my $fh = $self->file_handle();
  $csv->combine(@{
    $self->_projection_to_array($p)
  }) or throw('Could not create line '.Text::CSV->error_input());
  my $str = $csv->string();
  $fh->print($str, "\n");
  return;
}

sub _projection_to_array {
  my ($self, $p) = @_;
  return [
    $p->entry()->primary_id(),
    $p->from()->stable_id(),
    $p->from_identity(),
    $p->to()->stable_id(),
    $p->to_identity(),
    $p->type()
  ];
}

=head2 file()

  Description : Getter for the file name

=cut

sub file {
  my ($self) = @_;
  return $self->{file};
}

=head2 file_handle()

  Description : Getter for the file handle

=cut

sub file_handle {
  my ($self, $file_handle) = @_;
  if(! defined $self->{file_handle}) {
    $self->{file_handle} = $self->_build_file_handle();
    $self->{_self_generated_file_handle} = 1;
  }
  return $self->{file_handle};
}

sub _build_file_handle {
  my ($self) = @_;
  my $f = $self->file();
  # - means go to STDOUT
  if($f eq '-') {
    return IO::Handle->new_from_fd(fileno(STDOUT), 'w');
  }
  else {
    if( -f $f ) {
      warn("The file $f already exists; moving out of the way to ${f}.old");
      move($f, $f.'.old');
    }
    return IO::File->new($f, 'w');
  }
}

=head2 close()

Used to close down the underlying file handle

=cut

sub close {
  my ($self) = @_;
  close $self->file_handle();
}

sub _csv_writer {
  my ($self, $_csv_writer) = @_;
  if(! defined $self->{_csv_writer}) {
    eval {require Text::CSV};
    throw('Cannot bring in Text::CSV : '.$@) if $@;
    my $csv = Text::CSV->new() or throw('Cannot use CSV: '.Text::CSV->error_diag());
    $self->{_csv_writer} = $csv;
  }
  return $self->{_csv_writer};
}

=head2 DESTROY

Destroys the file handle generated by this object if we were not given
one during construction

=cut

sub DESTROY {
  my ($self) = @_;
  if($self->{_self_generated_file_handle} && $self->file_handle()->opened()) {
    $self->file_handle()->close();
  }
  return;
}

1;


text:
package pl.touk.nussknacker.engine.process.registrar

import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.functions.ProcessFunction
import org.apache.flink.util.Collector
import pl.touk.nussknacker.engine.process.compiler.FlinkMetricsProviderForScenario
import pl.touk.nussknacker.engine.util.metrics.common.OneSourceMetrics

private[registrar] class SourceMetricsFunction[T](sourceId: String) extends ProcessFunction[T, T] {

  @transient private var metrics: OneSourceMetrics = _

  override def open(parameters: Configuration): Unit = {
    metrics = new OneSourceMetrics(sourceId)
    val metricsProvider = new FlinkMetricsProviderForScenario(getRuntimeContext)
    metrics.registerOwnMetrics(metricsProvider)
  }

  override def processElement(value: T, ctx: ProcessFunction[T, T]#Context, out: Collector[T]): Unit = {
    metrics.process(ctx.timestamp())
    out.collect(value)
  }

}


text:
package app;

import app.contracts.*;
import app.core.BattlefieldImplementation;
import app.core.EngineImpl;
import app.factory.ActionFactoryImpl;
import app.factory.TargetableFactoryImpl;
import app.io.ConsoleReader;
import app.io.ConsoleWriter;

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {

        Reader reader = new ConsoleReader();
        Writer writer = new ConsoleWriter();
        ActionFactory actionFactory = new ActionFactoryImpl();
        TargetableFactory targetableFactory = new TargetableFactoryImpl();
        Battlefield battleField = new BattlefieldImplementation(writer, targetableFactory, actionFactory);

        Engine engine = new EngineImpl(writer,reader,battleField);
        engine.run();

    }
}


text:
all: build

build:
	@docker build --tag=${USER}/nginx .


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe "/users/login.html.erb" do

  def render_it
    render "/users/login.html.erb"
  end

  before do
    @user = stub("user")
    assigns[:user] = @user

    template.expect_render(
      :partial => 'users/login', :locals => { :user => @user }
    ).and_return(%|
|)

    template.expect_render(
      :partial => "users/signup", :locals => { :user => @user }
    ).and_return(%|
|)
  end

  it "renders the /users/_login.html.erb partial" do
    render_it
    response.should have_tag("#login_partial")
  end

  it "renders the /users/_signup.html.erb partial" do
    render_it
    response.should have_tag("#signup_partial")
  end

end


text:
using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NullDesk.Extensions.Mailer.Core;

namespace NullDesk.Extensions.Mailer.SendGrid.Tests.Infrastructure
{
    public class FactoryMailFixture : IDisposable
    {
        public FactoryMailFixture()
        {
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddDebug(LogLevel.Debug);

            var sendGridSettings = new SendGridMailerSettings
            {
                ApiKey = "abc",
                FromDisplayName = "xunit",
                FromEmailAddress = "xunit@nowhere.com"
            };

            var logger = loggerFactory.CreateLogger<SendGridMailer>();

            Mail.Register(() => new SendGridMailerFake(
                new OptionsWrapper<SendGridMailerSettings>(sendGridSettings),
                logger,
                Store));
        }

        public MailerFactory Mail { get; } = new MailerFactory();

        public IHistoryStore Store { get; set; } = new InMemoryHistoryStore();

        public void Dispose()
        {
        }
    }
}