text:
using Accelerator.EBS.SharedServices.Providers;

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

namespace Accelerator.EBS.SharedServices
{
    public class ServiceRequest : ModelObjectBase
    {
        public static string CreateUpdateURL { get; set; }
        public static string LookupURL { get; set; }

        public string ErrorMessage { get; set; }

        public decimal? RequestID { get; set; }
        public string RequestNumber { get; set; }

        public DateTime RequestDate { get; set; }
        public DateTime? IncidentOccurredDate { get; set; }
        public string RequestType { get; set; }
        public decimal? RequestTypeID { get; set; }
        public string Status { get; set; }
        public decimal? StatusID { get; set; }
        public string Severity { get; set; }
        public decimal? SeverityID { get; set; }
        public string Summary { get; set; }
        public string Owner { get; set; }
        public string Notes { get; set; }
        public string SerialNumber { get; set; }
        public decimal? ContractID { get; set; }
        public string ContactOrgID { get; set; }

        public string IncidentRef { get; set; }
        public string IncidentID { get; set; }
        public string EbsContactID { get; set; }
        public decimal? SrObjVerNum { get; set; }
        public decimal? ProductID { get; set; }
        public string Product { get; set; }
        public string ProductDescription { get; set; }
        public decimal? OwnerID { get; set; }
        public decimal? CreatedByID { get; set; }

        public string RnowHost { get; set; }

        private static IEBSProvider _provider = null;

        public bool Create(int _logIncidentId = 0, int _logContactId = 0)
        {

            if (_provider == null)
            {
                throw new Exception("EBS Provider not initialized.");
            }

            ServiceRequest req = ServiceRequest._provider.CreateSR(this, _logIncidentId, _logContactId);

            this.RequestID = req.RequestID;
            this.RequestNumber = req.RequestNumber;
            this.ErrorMessage = req.ErrorMessage;

            return String.IsNullOrWhiteSpace(this.ErrorMessage);
        }

        public bool Update(int _logIncidentId = 0, int _logContactId = 0)
        {

            if (_provider == null)
            {
                throw new Exception("EBS Provider not initialized.");
            }

            ServiceRequest req = ServiceRequest._provider.UpdateSR(this, _logIncidentId, _logContactId);

            this.RequestID = req.RequestID;
            this.RequestNumber = req.RequestNumber;
            this.ErrorMessage = req.ErrorMessage;

            return String.IsNullOrWhiteSpace(this.ErrorMessage);
        }

        public ServiceRequest Lookup(decimal incident_id, string incident_num, int _logIncidentId = 0, int _logContactId = 0)
        {
            return ServiceRequest._provider.LookupSR(incident_id, incident_num, _logIncidentId,  _logContactId);
        }

        public static Dictionary<string, string> LookupDetail(decimal incident_id, string incident_num, int _logIncidentId = 0, int _logContactId = 0)
        {
            return ServiceRequest._provider.LookupSRDetail(incident_id, incident_num, _logIncidentId, _logContactId);
        }

        public static Dictionary<string, string> getDetailSchema()
        {
            return ServiceRequest._provider.getServiceRequestDetailSchema();
        }

        public static ServiceRequest[] LookupSRbyContactPartyID(decimal contact_id, int _logIncidentId = 0, int _logContactId = 0)
        {
            return ServiceRequest._provider.LookupSRbyContactPartyID(contact_id, _logIncidentId, _logContactId);
        }

        public static void InitEBSProvider()
        {
            Type t = Type.GetType(ServiceProvider);

            try
            {
                _provider = Activator.CreateInstance(t) as IEBSProvider;
                _provider.InitForSR(CreateUpdateURL, LookupURL, ServiceUsername, ServicePassword, ServiceClientTimeout);
                _provider.log = ConfigurationSetting.logWrap;
            }
            catch (Exception ex)
            {
                if (ConfigurationSetting.logWrap != null)
                {
                    string logMessage = "Error in init Provider in Service Request Model. Error: " + ex.Message;
                    string logNote = "";
                    ConfigurationSetting.logWrap.ErrorLog(logMessage: logMessage, logNote: logNote);
                }

                throw;
            }
        }

        public  KeyValuePair<String, String> rnStatusToServerStatus(int rnStatusID){
            return ServiceRequest._provider.rnStatusToServerStatus(rnStatusID);
        }
        public  KeyValuePair<String, String> rnSeverityToServerSeverity(int rnSeverityID)
        {
            return ServiceRequest._provider.rnSeverityToServerSeverity(rnSeverityID);
        }
        public  KeyValuePair<String, String> rnRequestTypeToServerRequestType(int rnRequestTypeID)
        {
            return ServiceRequest._provider.rnRequestTypeToServerRequestType(rnRequestTypeID);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE DataKinds         #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators     #-}

module HttpServer where

import           Control.Monad.Except
import qualified DB
import qualified Network.HTTP.Types            as Http
import qualified Network.Wai                   as Wai
import qualified Network.Wai.Middleware.Static as WaiStatic
import           Servant
import           Types

type API = Lists

type Lists = "lists" :> Get '[JSON] [List]

httpApp :: Wai.Application
httpApp request respond =
  if isRequestForIndex request
  then respond $ Wai.responseLBS Http.status400 [] "REST API under construction."
  else WaiStatic.static apiApp request respond

apiApp :: Wai.Application
apiApp = Servant.serve (Servant.Proxy :: Servant.Proxy API) api

api :: Servant.Server API
api = getLists

isRequestForIndex :: Wai.Request -> Bool
isRequestForIndex request = null (Wai.pathInfo request)

getLists :: Handler [List]
getLists = liftIO . DB.runDB $ DB.selectAllLists


text:
require 'test/unit'
require './src-gen-umple/student_'
require './src-gen-umple/mentor_'
require './src-gen-umple/program_'

module CruiseAssociations
class DoActivityTest < Test::Unit::TestCase

  def test_doActivity
  end
    course = new CourseC
    course.flip
    course.flip
    course.flip

    sleep(3)
    assert_equal("Excepted more then 5, but only produced " + course.numberOfLogs, true,course.numberOfLogs > 5)
    assert_equal("Open Entry", course.getLog(0))
    assert_equal("Do Activity On Open",course.getLog(1))
    assert_equal("Closed Entry",course.getLog(2))
    assert_equal("Open Entry",course.getLog(3))
  end

end


text:
package org.support.project.knowledge.control.protect;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.support.project.common.log.Log;
import org.support.project.common.log.LogFactory;
import org.support.project.common.util.RandomUtil;
import org.support.project.common.util.StringUtils;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.knowledge.control.Control;
import org.support.project.knowledge.dao.TokensDao;
import org.support.project.knowledge.entity.TokensEntity;
import org.support.project.web.boundary.Boundary;
import org.support.project.web.common.HttpStatus;
import org.support.project.web.control.service.Get;
import org.support.project.web.control.service.Post;

@DI(instance = Instance.Prototype)
public class TokenControl extends Control {
    /** ログ */
    private static final Log LOG = LogFactory.getLog(TokenControl.class);

    private DateFormat gateDayFormat() {
        return new SimpleDateFormat("yyyy-MM-dd");
    }

    /**
     * 現在のTokenの状態を見る
     */
    @Get(publishToken = "csrf")
    public Boundary index() {
        LOG.trace("access to index");
        String expires = "";
        TokensEntity entity = TokensDao.get().selectOnUserId(getLoginUserId());
        if (entity == null) {
            entity = new TokensEntity();
            entity.setToken("");
        } else {
            expires = gateDayFormat().format(entity.getExpires());
        }
        setAttribute("token", entity.getToken());
        setAttribute("expires", expires);
        return forward("index.jsp");
    }

    /**
     * Tokenの発行/更新
     */
    @Post(subscribeToken = "csrf")
    public Boundary save() {
        LOG.trace("access to save");
        String expires = getParam("expires");
        if (StringUtils.isEmpty(expires)) {
            expires = "9999-12-31";
        }
        Date date;
        try {
            date = gateDayFormat().parse(expires);
        } catch (ParseException e) {
            return sendError(HttpStatus.SC_400_BAD_REQUEST, "BAD_REQUEST");
        }

        TokensEntity entity = TokensDao.get().selectOnUserId(getLoginUserId());
        if (entity == null) {
            entity = new TokensEntity();
            entity.setToken(RandomUtil.randamGen(64));
            entity.setUserId(getLoginUserId());
        }
        entity.setExpires(new Timestamp(date.getTime()));
        TokensDao.get().save(entity);
        addMsgSuccess("message.success.save");
        return index();
    }

    /**
     * Tokenの削除
     */
    @Post(subscribeToken = "csrf")
    public Boundary delete() {
        TokensEntity entity = TokensDao.get().selectOnUserId(getLoginUserId());
        if (entity != null) {
            TokensDao.get().physicalDelete(entity);
        }
        addMsgSuccess("message.success.delete");
        return index();
    }
}


text:
package com.github.abel533.echarts.code;

/**
 * @author liuzh
 */
public enum Symbol {
    none, auto,
    circle, rectangle, triangle, diamond,
    emptyCircle, emptyRectangle, emptyTriangle, emptyDiamond,
    heart, droplet, pin, arrow, star,
    emptyheart, emptydroplet, emptypin, emptyarrow, emptystar,
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface NSObject (SWPhotoLibraryAuthorization)

+ (void)requestPhotoLibraryAuthorizationWithCompletion:(void(^_Nullable)(BOOL isAuthorized))completedBlock alertViewController:(UIViewController *_Nullable)alertViewController;
+ (NSNumber *)sw_isHavePhotoLibarayAuthorizationWithAlertViewController:(UIViewController *_Nullable)alertViewController;

@end

NS_ASSUME_NONNULL_END


text:
var fs = require("fs");
var path = require("path");
var less = require("less");

// collect files
var folders = ["../android", "../blackberry", "../iphone", "../custom"];
var files = [];
folders.forEach(function(folder){
	files = files.concat(fs.readdirSync(folder).map(function(file){
		return folder + "/" + file;
	}));
});
files = files.filter(function(file){
	return file && /\.less$/.test(file) && !/variables\.less$/.test(file);
});

// compile files
files.forEach(function(file){
	console.log("compiling " + file);
	fs.readFile(file, "utf-8", function(error, data){
		if(error){
			console.error(error.message);
			process.exit(1);
		}
		var parser = new(less.Parser)({paths: [path.dirname(file)], filename: file, optimization: 1});
		parser.parse(data, function(error, tree){
			if(error){
				less.writeError(error);
				process.exit(1);
			}
			try{
				var css = tree.toCSS({compress: false});
				var fd = fs.openSync(file.replace(".less", ".css"), "w");
				fs.writeSync(fd, css, 0, "utf-8");
			}catch(error){
				less.writeError(error);
				process.exit(2);
			}
		});
	});
});


text:
package cn.geekiot.sparklebike.adapter;

import android.app.AlarmManager;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.cobox.cosmart.devicebridge.Config;
import com.cobox.cosmart.devicebridge.Device;

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

import cn.geekiot.sparklebike.R;
import cn.geekiot.sparklebike.page.DeviceDetailsActivity;

public class DiscoverDeviceAdapter extends RecyclerView.Adapter {

    private static final String TAG = "DiscoverDeviceAdapter";

    private static String[]       sDeviceTypeNameList         = {/* Load during construction */};
    private static int[]          sDeviceIconHintColorList    = {/* Load during construction */};
    private static String         sDefaultDeviceType          = null;
    private static ColorStateList sDefaultDeviceIconTintColor = null;

    private List<Device>        mDeviceList          = null;
    private RecyclerView        mHostView            = null;
    private OnItemClickListener mOnItemClickListener = null;

    public interface OnItemClickListener {
        void onItemClick(View view, int position, long id);
    }

    public class DeviceViewHolder extends RecyclerView.ViewHolder {
        private Context              mContext                = null;
        private CardView             mRootCardView           = null;
        private ImageView            mImgIcon                = null;
        private TextView             mTxvTitle               = null;
        private TextView             mTxvType                = null;
        private TextView             mTxvMAC                 = null;
        private TextView             mTxvCapabilities        = null;
        private TextView             mTxvLevelAndFreq        = null;
        private ImageButton          mBtnMore                = null;
        private Drawable             mDefaultIcon            = null;

        public DeviceViewHolder(ViewGroup parentView, int viewType) {
            super(LayoutInflater.from(parentView.getContext()).inflate(R.layout.item_discovered_device, parentView, false));

            mContext         = parentView.getContext();
            mRootCardView    = (CardView) itemView.findViewById(R.id.CardView_ItemRootLayout);
            mTxvTitle        = (TextView) itemView.findViewById(R.id.TextView_Title);
            mTxvType         = (TextView) itemView.findViewById(R.id.TextView_Type);
            mTxvMAC          = (TextView) itemView.findViewById(R.id.TextView_MAC);
            mTxvCapabilities = (TextView) itemView.findViewById(R.id.TextView_Capabilities);
            mTxvLevelAndFreq = (TextView) itemView.findViewById(R.id.TextView_LevelAndFrequency);
            mImgIcon         = (ImageView) itemView.findViewById(R.id.ImageView_Icon);
            mBtnMore         = (ImageButton) itemView.findViewById(R.id.ImageButton_More);
            mDefaultIcon     = mContext.getResources().getDrawable(R.mipmap.ic_rounter);
            initializeListeners();

            this.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e("Cocoonshu", "[onClick] ItemView clicked");
                }
            });
        }

        private void initializeListeners() {
            mBtnMore.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.e("Cocoonshu", "[onClick] ButtonMore");
                }

            });

            mRootCardView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                Log.e("Cocoonshu", "[onClick] Item");
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(
                                DeviceViewHolder.this.itemView,
                                DeviceViewHolder.this.getAdapterPosition(),
                                DeviceViewHolder.this.getItemId());
                    }
                }

            });
        }

        public void updateContent(Device device) {
            if (device == null) {
                mTxvTitle.setText("-");
                mTxvType.setText("-");
                mTxvCapabilities.setText("-");
                mTxvLevelAndFreq.setText("- / -");
                mTxvMAC.setText(sDefaultDeviceType);
                mImgIcon.setImageDrawable(mDefaultIcon);
                mImgIcon.setBackgroundTintList(sDefaultDeviceIconTintColor);
                mImgIcon.setTag(sDefaultDeviceIconTintColor);
                mImgIcon.setTag(sDeviceIconHintColorList[0]);
            } else {
                mTxvTitle.setText(device.getSSID());
                mTxvCapabilities.setText(device.getCapabilities());
                mTxvLevelAndFreq.setText(device.getLevel() + " dBm / " + device.getFrequency() + " MHz");
                mTxvMAC.setText(device.getMAC() == null ? "" : device.getMACString());

                if (device.getSSID().startsWith(Config.COSMART_DEVICE_SSID_PREFIX)) {
                    mTxvType.setText(sDeviceTypeNameList[1]);
                    mImgIcon.setImageDrawable(mDefaultIcon);
                    mImgIcon.setBackgroundTintList(ColorStateList.valueOf(sDeviceIconHintColorList[1]));
                    mImgIcon.setTag(sDeviceIconHintColorList[1]);
                } else {
                    mTxvType.setText(sDefaultDeviceType);
                    mImgIcon.setImageDrawable(mDefaultIcon);
                    mImgIcon.setBackgroundTintList(sDefaultDeviceIconTintColor);
                    mImgIcon.setTag(sDeviceIconHintColorList[0]);
                }
            }
        }
    }

    public DiscoverDeviceAdapter(RecyclerView hostView) {
        mHostView = hostView;
        loadDeviceResourceList(hostView.getContext());
    }

    private void loadDeviceResourceList(Context context) {
        Resources resources = context.getResources();
        if (resources != null) {
            sDeviceTypeNameList         = resources.getStringArray(R.array.DeviceTypeName);
            sDeviceIconHintColorList    = resources.getIntArray(R.array.IconTintColor);
            sDefaultDeviceType          = sDeviceTypeNameList.length > 0 ? sDeviceTypeNameList[0] : null;
            sDefaultDeviceIconTintColor = sDeviceIconHintColorList.length > 0 ? ColorStateList.valueOf(sDeviceIconHintColorList[0]) : null;
        }
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    public Device getItemContent(int position) {
        return mDeviceList.get(position);
    }

    public void updateFromDeviceList(List<Device> deviceList) {
        if (mDeviceList == null) {
            mDeviceList = new ArrayList<Device>(deviceList);
        } else {
            synchronized (mDeviceList) {
                mDeviceList.clear();
                mDeviceList = new ArrayList<Device>(deviceList);
            }
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new DeviceViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ((DeviceViewHolder)holder).updateContent(mDeviceList.get(position));
    }

    @Override
    public int getItemCount() {
        if (mDeviceList == null) {
            return 0;
        } else {
            synchronized (mDeviceList) {
                return mDeviceList == null ? 0 : mDeviceList.size();
            }
        }
    }

}


text:
package org.zalando.riptide;

import com.google.common.reflect.TypeToken;
import org.apiguardian.api.API;
import org.springframework.http.client.ClientHttpResponse;
import org.zalando.fauxpas.ThrowingConsumer;
import org.zalando.fauxpas.ThrowingRunnable;

import static org.apiguardian.api.API.Status.STABLE;
import static org.zalando.fauxpas.TryWith.tryWith;

/**
 *
 * @see RoutingTree
 */
@API(status = STABLE)
@FunctionalInterface
public interface Route {

    /**
     * Executes this route against the specific response. It's within the responsibility of a {@link Route route}
     * implementation to ensure the stream is consumed (optional) and properly closed. A fully consumed response stream
     * allows for connection reuse and is therefore highly encouraged. Making sure that every response is properly
     * closed ensures that stale connections are not exhausting the connection pool.
     *
     * Most {@link Route routes} will do both operations internally, but the responsibility can be handed over to the
     * caller of the {@link Route route} by unmarshalling the stream into a {@link java.io.Closeable} or
     * {@link AutoCloseable} bean.
     *
     * @param response the client response
     * @param reader a utility to unmarshall the response into Java beans
     * @throws Exception if anything goes wrong during route execution, primarily used for {@link java.io.IOException}
     */
    void execute(final ClientHttpResponse response, final MessageReader reader) throws Exception;

    default Route merge(final Route other) {
        return other;
    }

    static Route call(final ThrowingRunnable<? extends Exception> runnable) {
        return (response, reader) ->
                tryWith(response, (ClientHttpResponse ignored) -> runnable.tryRun());
    }

    static Route call(final ThrowingConsumer<ClientHttpResponse, ? extends Exception> consumer) {
        return (response, reader) ->
                tryWith(response, consumer);
    }

    static <I> Route call(final Class<I> type, final ThrowingConsumer<I, ? extends Exception> consumer) {
        return call(TypeToken.of(type), consumer);
    }

    static <I> Route call(final TypeToken<I> type, final ThrowingConsumer<I, ? extends Exception> consumer) {
        return (response, reader) -> {

            final I body = reader.read(type, response);
            consumer.tryAccept(body);
        };
    }

}


text:
package forwarder

import (
	context "context"
	fmt "fmt"
	proto "github.com/golang/protobuf/proto"
	empty "github.com/golang/protobuf/ptypes/empty"
	connection "github.com/networkservicemesh/networkservicemesh/controlplane/api/connection"
	crossconnect "github.com/networkservicemesh/networkservicemesh/controlplane/api/crossconnect"
	grpc "google.golang.org/grpc"
	codes "google.golang.org/grpc/codes"
	status "google.golang.org/grpc/status"
	math "math"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package

// Message sent by forwarder module informing NSM of any changes in its
// operations parameters or constraints
type MechanismUpdate struct {
	RemoteMechanisms     []*connection.Mechanism `protobuf:"bytes,1,rep,name=remote_mechanisms,json=remoteMechanisms,proto3" json:"remote_mechanisms,omitempty"`
	LocalMechanisms      []*connection.Mechanism `protobuf:"bytes,2,rep,name=local_mechanisms,json=localMechanisms,proto3" json:"local_mechanisms,omitempty"`
	XXX_NoUnkeyedLiteral struct{}                `json:"-"`
	XXX_unrecognized     []byte                  `json:"-"`
	XXX_sizecache        int32                   `json:"-"`
}

func (m *MechanismUpdate) Reset()         { *m = MechanismUpdate{} }
func (m *MechanismUpdate) String() string { return proto.CompactTextString(m) }
func (*MechanismUpdate) ProtoMessage()    {}
func (*MechanismUpdate) Descriptor() ([]byte, []int) {
	return fileDescriptor_19bff53f4d11db23, []int{0}
}

func (m *MechanismUpdate) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_MechanismUpdate.Unmarshal(m, b)
}
func (m *MechanismUpdate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_MechanismUpdate.Marshal(b, m, deterministic)
}
func (m *MechanismUpdate) XXX_Merge(src proto.Message) {
	xxx_messageInfo_MechanismUpdate.Merge(m, src)
}
func (m *MechanismUpdate) XXX_Size() int {
	return xxx_messageInfo_MechanismUpdate.Size(m)
}
func (m *MechanismUpdate) XXX_DiscardUnknown() {
	xxx_messageInfo_MechanismUpdate.DiscardUnknown(m)
}

var xxx_messageInfo_MechanismUpdate proto.InternalMessageInfo

func (m *MechanismUpdate) GetRemoteMechanisms() []*connection.Mechanism {
	if m != nil {
		return m.RemoteMechanisms
	}
	return nil
}

func (m *MechanismUpdate) GetLocalMechanisms() []*connection.Mechanism {
	if m != nil {
		return m.LocalMechanisms
	}
	return nil
}

func init() {
	proto.RegisterType((*MechanismUpdate)(nil), "forwarder.MechanismUpdate")
}

func init() { proto.RegisterFile("forwarder.proto", fileDescriptor_19bff53f4d11db23) }

var fileDescriptor_19bff53f4d11db23 = []byte{
	// 302 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x92, 0xcd, 0x4e, 0x02, 0x31,
	0x10, 0xc7, 0xb3, 0x1a, 0x35, 0xd4, 0x03, 0xd0, 0x44, 0x43, 0x7a, 0x32, 0x9e, 0x3c, 0x15, 0x83,
	0x47, 0x2f, 0x2a, 0xd1, 0xc4, 0x03, 0x17, 0x12, 0x8f, 0x6a, 0x4a, 0x19, 0xa0, 0xb1, 0xed, 0xd4,
	0xb6, 0x48, 0x78, 0x06, 0x1f, 0xc0, 0xd7, 0x35, 0x4b, 0x97, 0xdd, 0xc5, 0xe8, 0x9e, 0xbc, 0x34,
	0x33, 0xff, 0x99, 0xfe, 0xe6, 0xa3, 0x25, 0xed, 0x19, 0xfa, 0x95, 0xf0, 0x53, 0xf0, 0xdc, 0x79,
	0x8c, 0x48, 0x5b, 0xa5, 0xc0, 0x9e, 0xe7, 0x2a, 0x2e, 0x96, 0x13, 0x2e, 0xd1, 0xf4, 0x2d, 0xc4,
	0x15, 0xfa, 0xb7, 0x00, 0xfe, 0x43, 0x49, 0x30, 0x10, 0x16, 0xbf, 0x49, 0x12, 0x6d, 0xf4, 0xa8,
	0x9d, 0x16, 0x16, 0xfa, 0xc2, 0xa9, 0x5c, 0xb0, 0x20, 0xa3, 0x42, 0x5b, 0x33, 0x53, 0x25, 0x26,
	0xfe, 0x01, 0xef, 0x31, 0x84, 0x02, 0xbc, 0xe3, 0x14, 0x25, 0x7a, 0x2e, 0xae, 0x1d, 0x84, 0x3e,
	0x18, 0x17, 0xd7, 0xe9, 0x4c, 0x91, 0xf3, 0xaf, 0x8c, 0xb4, 0x47, 0x20, 0x17, 0xc2, 0xaa, 0x60,
	0x9e, 0xdc, 0x54, 0x44, 0xa0, 0x77, 0xa4, 0xeb, 0xc1, 0x60, 0x84, 0x57, 0xb3, 0x8d, 0x84, 0x5e,
	0x76, 0xb6, 0x7f, 0x71, 0x3c, 0x38, 0xe1, 0xb5, 0xf6, 0xcb, 0x7b, 0xe3, 0x4e, 0xca, 0x2f, 0x85,
	0x40, 0x6f, 0x48, 0x47, 0xa3, 0x14, 0xba, 0x8e, 0xd8, 0x6b, 0x42, 0xb4, 0x37, 0xe9, 0x15, 0x61,
	0xf0, 0x99, 0x91, 0xd6, 0xc3, 0xf6, 0x0d, 0xe8, 0x2d, 0x39, 0x1a, 0xc3, 0xfb, 0x12, 0x42, 0xa4,
	0x8c, 0xef, 0x4c, 0x38, 0xcc, 0x9d, 0x61, 0x72, 0x58, 0x43, 0x8c, 0x5e, 0x93, 0x83, 0xa1, 0xc6,
	0x00, 0x8d, 0x80, 0x53, 0x3e, 0x47, 0x9c, 0x6b, 0x48, 0xeb, 0x99, 0x2c, 0x67, 0xfc, 0x3e, 0xdf,
	0xd6, 0xe0, 0x85, 0x74, 0xab, 0xde, 0x46, 0x68, 0x55, 0x44, 0x4f, 0x1f, 0x49, 0xb7, 0x30, 0x6b,
	0x93, 0xff, 0x41, 0x60, 0x8c, 0x57, 0x5f, 0xec, 0xc7, 0xc6, 0x2f, 0xb3, 0xc9, 0xe1, 0x26, 0xfb,
	0xea, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x7a, 0x88, 0x27, 0xe6, 0x88, 0x02, 0x00, 0x00,
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6

// ForwarderClient is the client API for Forwarder service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type ForwarderClient interface {
	Request(ctx context.Context, in *crossconnect.CrossConnect, opts ...grpc.CallOption) (*crossconnect.CrossConnect, error)
	Close(ctx context.Context, in *crossconnect.CrossConnect, opts ...grpc.CallOption) (*empty.Empty, error)
}

type forwarderClient struct {
	cc grpc.ClientConnInterface
}

func NewForwarderClient(cc grpc.ClientConnInterface) ForwarderClient {
	return &forwarderClient{cc}
}

func (c *forwarderClient) Request(ctx context.Context, in *crossconnect.CrossConnect, opts ...grpc.CallOption) (*crossconnect.CrossConnect, error) {
	out := new(crossconnect.CrossConnect)
	err := c.cc.Invoke(ctx, "/forwarder.Forwarder/Request", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *forwarderClient) Close(ctx context.Context, in *crossconnect.CrossConnect, opts ...grpc.CallOption) (*empty.Empty, error) {
	out := new(empty.Empty)
	err := c.cc.Invoke(ctx, "/forwarder.Forwarder/Close", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// ForwarderServer is the server API for Forwarder service.
type ForwarderServer interface {
	Request(context.Context, *crossconnect.CrossConnect) (*crossconnect.CrossConnect, error)
	Close(context.Context, *crossconnect.CrossConnect) (*empty.Empty, error)
}

// UnimplementedForwarderServer can be embedded to have forward compatible implementations.
type UnimplementedForwarderServer struct {
}

func (*UnimplementedForwarderServer) Request(ctx context.Context, req *crossconnect.CrossConnect) (*crossconnect.CrossConnect, error) {
	return nil, status.Errorf(codes.Unimplemented, "method Request not implemented")
}
func (*UnimplementedForwarderServer) Close(ctx context.Context, req *crossconnect.CrossConnect) (*empty.Empty, error) {
	return nil, status.Errorf(codes.Unimplemented, "method Close not implemented")
}

func RegisterForwarderServer(s *grpc.Server, srv ForwarderServer) {
	s.RegisterService(&_Forwarder_serviceDesc, srv)
}

func _Forwarder_Request_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(crossconnect.CrossConnect)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(ForwarderServer).Request(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/forwarder.Forwarder/Request",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(ForwarderServer).Request(ctx, req.(*crossconnect.CrossConnect))
	}
	return interceptor(ctx, in, info, handler)
}

func _Forwarder_Close_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(crossconnect.CrossConnect)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(ForwarderServer).Close(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/forwarder.Forwarder/Close",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(ForwarderServer).Close(ctx, req.(*crossconnect.CrossConnect))
	}
	return interceptor(ctx, in, info, handler)
}

var _Forwarder_serviceDesc = grpc.ServiceDesc{
	ServiceName: "forwarder.Forwarder",
	HandlerType: (*ForwarderServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Request",
			Handler:    _Forwarder_Request_Handler,
		},
		{
			MethodName: "Close",
			Handler:    _Forwarder_Close_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "forwarder.proto",
}

// MechanismsMonitorClient is the client API for MechanismsMonitor service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type MechanismsMonitorClient interface {
	MonitorMechanisms(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (MechanismsMonitor_MonitorMechanismsClient, error)
}

type mechanismsMonitorClient struct {
	cc grpc.ClientConnInterface
}

func NewMechanismsMonitorClient(cc grpc.ClientConnInterface) MechanismsMonitorClient {
	return &mechanismsMonitorClient{cc}
}

func (c *mechanismsMonitorClient) MonitorMechanisms(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (MechanismsMonitor_MonitorMechanismsClient, error) {
	stream, err := c.cc.NewStream(ctx, &_MechanismsMonitor_serviceDesc.Streams[0], "/forwarder.MechanismsMonitor/MonitorMechanisms", opts...)
	if err != nil {
		return nil, err
	}
	x := &mechanismsMonitorMonitorMechanismsClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type MechanismsMonitor_MonitorMechanismsClient interface {
	Recv() (*MechanismUpdate, error)
	grpc.ClientStream
}

type mechanismsMonitorMonitorMechanismsClient struct {
	grpc.ClientStream
}

func (x *mechanismsMonitorMonitorMechanismsClient) Recv() (*MechanismUpdate, error) {
	m := new(MechanismUpdate)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// MechanismsMonitorServer is the server API for MechanismsMonitor service.
type MechanismsMonitorServer interface {
	MonitorMechanisms(*empty.Empty, MechanismsMonitor_MonitorMechanismsServer) error
}

// UnimplementedMechanismsMonitorServer can be embedded to have forward compatible implementations.
type UnimplementedMechanismsMonitorServer struct {
}

func (*UnimplementedMechanismsMonitorServer) MonitorMechanisms(req *empty.Empty, srv MechanismsMonitor_MonitorMechanismsServer) error {
	return status.Errorf(codes.Unimplemented, "method MonitorMechanisms not implemented")
}

func RegisterMechanismsMonitorServer(s *grpc.Server, srv MechanismsMonitorServer) {
	s.RegisterService(&_MechanismsMonitor_serviceDesc, srv)
}

func _MechanismsMonitor_MonitorMechanisms_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(empty.Empty)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(MechanismsMonitorServer).MonitorMechanisms(m, &mechanismsMonitorMonitorMechanismsServer{stream})
}

type MechanismsMonitor_MonitorMechanismsServer interface {
	Send(*MechanismUpdate) error
	grpc.ServerStream
}

type mechanismsMonitorMonitorMechanismsServer struct {
	grpc.ServerStream
}

func (x *mechanismsMonitorMonitorMechanismsServer) Send(m *MechanismUpdate) error {
	return x.ServerStream.SendMsg(m)
}

var _MechanismsMonitor_serviceDesc = grpc.ServiceDesc{
	ServiceName: "forwarder.MechanismsMonitor",
	HandlerType: (*MechanismsMonitorServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "MonitorMechanisms",
			Handler:       _MechanismsMonitor_MonitorMechanisms_Handler,
			ServerStreams: true,
		},
	},
	Metadata: "forwarder.proto",
}


text:
package cmd

import (
	"fmt"
	"io"
	"io/ioutil"
	"path"

	"github.com/renstrom/dedent"
	"github.com/spf13/cobra"

	kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
	kubeadmapiext "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1alpha1"
	"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/validation"
	"k8s.io/kubernetes/cmd/kubeadm/app/discovery"
	kubenode "k8s.io/kubernetes/cmd/kubeadm/app/node"
	kubeconfigphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/kubeconfig"
	"k8s.io/kubernetes/cmd/kubeadm/app/preflight"
	kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
	"k8s.io/kubernetes/pkg/api"
	clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api"
	"k8s.io/kubernetes/pkg/runtime"
)

var (
	joinDoneMsgf = dedent.Dedent(`
		Node join complete:
		* Certificate signing request sent to master and response
		  received.
		* Kubelet informed of new secure connection details.

		Run 'kubectl get nodes' on the master to see this machine join.
		`)
)

// NewCmdJoin returns "kubeadm join" command.
func NewCmdJoin(out io.Writer) *cobra.Command {
	versioned := &kubeadmapiext.NodeConfiguration{}
	api.Scheme.Default(versioned)
	cfg := kubeadmapi.NodeConfiguration{}
	api.Scheme.Convert(versioned, &cfg, nil)

	var skipPreFlight bool
	var cfgPath string

	cmd := &cobra.Command{
		Use:   "join <master address>",
		Short: "Run this on any machine you wish to join an existing cluster",
		Run: func(cmd *cobra.Command, args []string) {
			j, err := NewJoin(cfgPath, args, &cfg, skipPreFlight)
			kubeadmutil.CheckErr(err)
			kubeadmutil.CheckErr(j.Validate())
			kubeadmutil.CheckErr(j.Run(out))
		},
	}

	cmd.PersistentFlags().StringVar(&cfgPath, "config", cfgPath, "Path to kubeadm config file")

	cmd.PersistentFlags().BoolVar(
		&skipPreFlight, "skip-preflight-checks", false,
		"skip preflight checks normally run before modifying the system",
	)

	cmd.PersistentFlags().Var(
		discovery.NewDiscoveryValue(&cfg.Discovery), "discovery",
		"The discovery method kubeadm will use for connecting nodes to the master",
	)

	return cmd
}

type Join struct {
	cfg *kubeadmapi.NodeConfiguration
}

func NewJoin(cfgPath string, args []string, cfg *kubeadmapi.NodeConfiguration, skipPreFlight bool) (*Join, error) {

	fmt.Println("[kubeadm] WARNING: kubeadm is in alpha, please do not use it for production clusters.")

	if cfgPath != "" {
		b, err := ioutil.ReadFile(cfgPath)
		if err != nil {
			return nil, fmt.Errorf("unable to read config from %q [%v]", cfgPath, err)
		}
		if err := runtime.DecodeInto(api.Codecs.UniversalDecoder(), b, cfg); err != nil {
			return nil, fmt.Errorf("unable to decode config from %q [%v]", cfgPath, err)
		}
	}

	if !skipPreFlight {
		fmt.Println("[preflight] Running pre-flight checks")

		// First, check if we're root separately from the other preflight checks and fail fast
		if err := preflight.RunRootCheckOnly(); err != nil {
			return nil, err
		}

		// Then continue with the others...
		if err := preflight.RunJoinNodeChecks(cfg); err != nil {
			return nil, err
		}
	} else {
		fmt.Println("[preflight] Skipping pre-flight checks")
	}

	// Try to start the kubelet service in case it's inactive
	preflight.TryStartKubelet()

	return &Join{cfg: cfg}, nil
}

func (j *Join) Validate() error {
	return validation.ValidateNodeConfiguration(j.cfg).ToAggregate()
}

// Run executes worked node provisioning and tries to join an existing cluster.
func (j *Join) Run(out io.Writer) error {
	clusterInfo, err := kubenode.RetrieveTrustedClusterInfo(j.cfg.Discovery.Token)
	if err != nil {
		return err
	}

	var cfg *clientcmdapi.Config
	// TODO: delete this first block when we move Token to the discovery interface
	if j.cfg.Discovery.Token != nil {
		connectionDetails, err := kubenode.EstablishMasterConnection(j.cfg.Discovery.Token, clusterInfo)
		if err != nil {
			return err
		}
		err = kubenode.CheckForNodeNameDuplicates(connectionDetails)
		if err != nil {
			return err
		}
		cfg, err = kubenode.PerformTLSBootstrapDeprecated(connectionDetails)
		if err != nil {
			return err
		}
	} else {
		cfg, err = discovery.For(j.cfg.Discovery)
		if err != nil {
			return err
		}
		if err := kubenode.PerformTLSBootstrap(cfg); err != nil {
			return err
		}
	}

	err = kubeconfigphase.WriteKubeconfigToDisk(path.Join(kubeadmapi.GlobalEnvParams.KubernetesDir, kubeconfigphase.KubeletKubeConfigFileName), cfg)
	if err != nil {
		return err
	}

	fmt.Fprintf(out, joinDoneMsgf)
	return nil
}


text:
@interface FNAVGetAVNewsList : NSObject

+ (void)getAVNewsListWithTid:(NSString *)tid :(NSInteger)pageCount :(void(^)(NSArray *))complete;

@end


text:
 Behaviour Driven Development for Lua 5.1, 5.2 & 5.3.
 Copyright (C) 2013-2018 Gary V. Vaughan
]]

local _ENV = {
   load = load,
   loadstring = loadstring,
   pcall = pcall,
   setfenv = function() end,
   select = select,
   type = type,
   unpack = table.unpack or unpack,
   xpcall = xpcall,

   open = io.open,
   config = package.config,
   searchpath = package.searchpath,
   gmatch = string.gmatch,
   gsub = string.gsub,
   match = string.match,
   concat = table.concat,
}
setfenv(1, _ENV)

-- Lua 5.1 load implementation does not handle string argument.
if not pcall(load, '_=1') then
   local loadfunction = load
   load = function(...)
      if type(...) == 'string' then
         return loadstring(...)
      end
      return loadfunction(...)
   end
end

local dirsep, pathsep, path_mark = match(config, '^(%S+)\n(%S+)\n(%S+)\n')

local searchpath = searchpath or function(name, path, sep, rep)
   name = gsub(name, sep or '%.', rep or dirsep)

   local errbuf = {}
   for template in gmatch(path, '[^' .. pathsep .. ']+') do
      local filename = gsub(template, path_mark, name)
      local fh = open(filename, 'r')
      if fh then
         fh:close()
         return filename
      end
      errbuf[#errbuf + 1] = "\tno file '" .. filename .. "'"
   end
   return nil, concat(errbuf, '\n')
end

do
   local have_xpcall_args
   local function catch(arg) have_xpcall_args = arg end
   xpcall(catch, function() end, true)

   if have_xpcall_args ~= true then
      local _xpcall = xpcall
      xpcall = function(fn, errh, ...)
         local args, n = {...}, select('#', ...)
         return _xpcall(function() return fn(unpack(args, 1, n)) end, errh)
      end
   end
end

--[[ ----------------- ]]--
--[[ Public Interface. ]]--
--[[ ----------------- ]]--

return {
   load = load,
   searchpath = searchpath,
   xpcall = xpcall,
}


text:
package com.github.joshholl.intellij.csharp.lang.psi.impl;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.github.joshholl.intellij.csharp.lang.lexer.CSharpTokenTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.github.joshholl.intellij.csharp.lang.psi.*;

public class CSharpUnaryOperatorDeclaratorImpl extends ASTWrapperPsiElement implements CSharpUnaryOperatorDeclarator {

  public CSharpUnaryOperatorDeclaratorImpl(ASTNode node) {
    super(node);
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof CSharpVisitor) ((CSharpVisitor)visitor).visitUnaryOperatorDeclarator(this);
    else super.accept(visitor);
  }

  @Override
  @NotNull
  public CSharpOverloadableUnaryOperator getOverloadableUnaryOperator() {
    return findNotNullChildByClass(CSharpOverloadableUnaryOperator.class);
  }

  @Override
  @NotNull
  public List<CSharpType> getTypeList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, CSharpType.class);
  }

}


text:
<?php
/**
 * Series dedicated to TV broadcast and associated online delivery.
 *
 * @see    http://schema.org/TVSeries
*/
abstract class TypeTVSeries extends TypeCreativeWork
{
	/**
	 * The Schema.org Type Scope
	 *
	 * @var string
	 */
	protected static $scope = 'https://schema.org/TVSeries';

	/**
	 * An actor, e.g. in tv, radio, movie, video games etc. Actors can be associated with individual items or with a series, episode, clip. Supersedes actors.
	 * Expected Type: Person
	 *
	 * @var	array
	 */
	protected static $actor = array('value' => 'actor',
		'expectedTypes' => array('Person')
	);

	/**
	 * A director of e.g. tv, radio, movie, video games etc. content. Directors can be associated with individual items or with a series, episode, clip. Supersedes directors.
	 * Expected Type: Person
	 *
	 * @var	array
	 */
	protected static $director = array('value' => 'director',
		'expectedTypes' => array('Person')
	);

	/**
	 * An episode of a tv, radio or game media within a series or season. Supersedes episodes.
	 * Expected Type: Episode
	 *
	 * @var	array
	 */
	protected static $episode = array('value' => 'episode',
		'expectedTypes' => array('Episode')
	);

	/**
	 * The composer of the soundtrack.
	 * Expected Type: MusicGroup, Person
	 *
	 * @var	array
	 */
	protected static $musicBy = array('value' => 'musicBy',
		'expectedTypes' => array('MusicGroup', 'Person')
	);

	/**
	 * The number of episodes in this season or series.
	 * Expected Type: Number
	 *
	 * @var	array
	 */
	protected static $numberOfEpisodes = array('value' => 'numberOfEpisodes',
		'expectedTypes' => array('Number')
	);

	/**
	 * The number of seasons in this series.
	 * Expected Type: Number
	 *
	 * @var	array
	 */
	protected static $numberOfSeasons = array('value' => 'numberOfSeasons',
		'expectedTypes' => array('Number')
	);

	/**
	 * The production company or studio responsible for the item e.g. series, video game, episode etc.
	 * Expected Type: Organization
	 *
	 * @var	array
	 */
	protected static $productionCompany = array('value' => 'productionCompany',
		'expectedTypes' => array('Organization')
	);

	/**
	 * A season in a media series. Supersedes seasons.
	 * Expected Type: Season
	 *
	 * @var	array
	 */
	protected static $season = array('value' => 'season',
		'expectedTypes' => array('Season')
	);

	/**
	 * The trailer of a movie or tv/radio series, season, episode, etc.
	 * Expected Type: VideoObject
	 *
	 * @var	array
	 */
	protected static $trailer = array('value' => 'trailer',
		'expectedTypes' => array('VideoObject')
	);

	/**
	 * Return the 'actor' Property value
	 *
	 * @return	string
	 */
	public static function pActor()
	{
		return self::getValue(self::$actor);
	}

	/**
	 * Return the 'director' Property value
	 *
	 * @return	string
	 */
	public static function pDirector()
	{
		return self::getValue(self::$director);
	}

	/**
	 * Return the 'episode' Property value
	 *
	 * @return	string
	 */
	public static function pEpisode()
	{
		return self::getValue(self::$episode);
	}

	/**
	 * Return the 'musicBy' Property value
	 *
	 * @return	string
	 */
	public static function pMusicBy()
	{
		return self::getValue(self::$musicBy);
	}

	/**
	 * Return the 'numberOfEpisodes' Property value
	 *
	 * @return	string
	 */
	public static function pNumberOfEpisodes()
	{
		return self::getValue(self::$numberOfEpisodes);
	}

	/**
	 * Return the 'numberOfSeasons' Property value
	 *
	 * @return	string
	 */
	public static function pNumberOfSeasons()
	{
		return self::getValue(self::$numberOfSeasons);
	}

	/**
	 * Return the 'productionCompany' Property value
	 *
	 * @return	string
	 */
	public static function pProductionCompany()
	{
		return self::getValue(self::$productionCompany);
	}

	/**
	 * Return the 'season' Property value
	 *
	 * @return	string
	 */
	public static function pSeason()
	{
		return self::getValue(self::$season);
	}

	/**
	 * Return the 'trailer' Property value
	 *
	 * @return	string
	 */
	public static function pTrailer()
	{
		return self::getValue(self::$trailer);
	}
}


text:
from functools import wraps
from blog import loginmanager
from flask_login import current_user

def admin_login_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if not current_user.is_authenticated or not current_user.is_admin():
            return loginmanager.unauthorized()
        return func(*args, **kwargs)
    return decorated_view


text:
require 'spec_helper'

RSpec.describe OneviewSDK::API3000::Synergy::EnclosureGroup do
  include_context 'shared context'

  it 'inherits from OneviewSDK::API2800::Synergy::EnclosureGroup' do
    expect(described_class).to be < OneviewSDK::API2800::Synergy::EnclosureGroup
  end
end


text:
<?php

namespace JPC\MongoDB\ODM\Factory;

use JPC\MongoDB\ODM\DocumentManager;
use JPC\MongoDB\ODM\Subscriber\ModelEventSubscriber;
use MongoDB\Client;
use MongoDB\Database;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 * Factory to create document manager easily
 */
class DocumentManagerFactory
{

    /**
     * Repository factory class
     * @var string
     */
    protected $repositoryFactoryClass;

    /**
     * Already opened connexions
     * @var Client
     */
    protected $connexions = [];

    /**
     * Already created document managers
     * @var DocumentManager
     */
    protected $managers = [];

    /**
     * Class metadata factory
     * @var ClassMetadataFactory
     */
    protected $classMetadataFactory;

    /**
     * Create a document manager factory
     *
     * @param   string  $repositoryFactoryClass class of repository factory
     */
    public function __construct($repositoryFactoryClass = null)
    {
        $this->repositoryFactoryClass = isset($repositoryFactoryClass) ? $repositoryFactoryClass : "JPC\MongoDB\ODM\Factory\RepositoryFactory";

        $this->classMetadataFactory = new ClassMetadataFactory();
    }

    /**
     * Create new DocumentManager from mongouri and DB name
     *
     * @param   string                  $mongouri       mongodb uri (mongodb://user:pass@example.org/auth_db)
     * @param   string                  $dbName         name of the DB where to work
     * @param   boolean                 $debug          Enable debug mode or not
     * @param   mixed                   $managerId      Manager unique id
     * @param   boolean                 $newConnection  Force to open new connection
     *
     * @return DocumentManager      A DocumentManager connected to mongouri specified
     */
    public function createDocumentManager($mongouri, $dbName, $debug = false, $managerId = "", $newConnection = false, $options = [])
    {

        if (!isset($this->connexions[$mongouri])) {
            $client = new Client($mongouri);
        }

        if (!isset($this->managers[$managerId])) {
            $database = new Database($client->getManager(), $dbName, $options);

            $class = $this->repositoryFactoryClass;

            $eventDispatcher = new EventDispatcher();
            if (isset($options['event_subscribers'])) {
                foreach ($options['event_subscribers'] as $subscriber) {
                    $eventDispatcher->addSubscriber($subscriber);
                }
            }
            $modelEventSubscriber = new ModelEventSubscriber();
            $eventDispatcher->addSubscriber($modelEventSubscriber);

            $repositoryFactory = new $class($eventDispatcher, null, $this->classMetadataFactory);

            $this->managers[$managerId] = new DocumentManager(
                $client,
                $database,
                $repositoryFactory,
                $debug,
                $options,
                [],
                $eventDispatcher
            );
        }

        return $this->managers[$managerId];
    }

    /**
     * Clear all document manager caches, unpersist all objects
     *
     * @return void
     */
    public function clearAll()
    {
        foreach ($this->managers as $manager) {
            $manager->clear();
        }
    }
}


text:
@interface SqViewController ()

@end

@implementation SqViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

//    if(sqlite3_open([[self getDBPath] UTF8String], &db) != SQLITE_OK) {
//        sqlite3_close(db);
//    }
//
//    char *errmsg;
//    const char *createsql = "CREATE TABLE IF NOT EXISTS INFO (ID INTEGER PRIMARY KEY AUTOINCREMENT, NUM TEXT, CLASSNAME TEXT,NAME TEXT)";
//    if (sqlite3_exec(db, createsql, NULL, NULL, &errmsg)!=SQLITE_OK) {
//        NSLog(@"create table failed.b");
//    }

    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];

    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];

    NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:[self getDBPath]] options:nil error:nil];

    if(store == nil){
        NSLog(@">>>>>>>>>>...fail");
    }

    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    context.persistentStoreCoordinator = psc;

//    NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
//    [person setValue:@"MJ" forKey:@"name"];
//    [person setValue:[NSNumber numberWithInt:27] forKey:@"age"];
//
//    NSManagedObject *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:context];
//    [card setValue:@"4414241933432" forKey:@"no"];
//
//
//    [person setValue:card forKey:@"card"];
//
//    BOOL success = [context save:nil];
//    NSLog(@">>>>>>>>>>success %d", success);

    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Person"];

    NSArray *arr = [context executeFetchRequest:request error:nil];
    NSLog(@"arr %@", arr);
    for(Person *p in arr){
        NSLog(@">>>>>>>>>>name %@ age %d", p.name, p.age.intValue);
    }
}

- (NSString *)getDBPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *database_path = [documents stringByAppendingPathComponent:@"test_db.data"];
    return database_path;
}

@end


text:
// Copyright (c) 2014-2018 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef PRIVATESENDSERVER_H
#define PRIVATESENDSERVER_H

#include "net.h"
#include "privatesend.h"

class CPrivateSendServer;

// The main object for accessing mixing
extern CPrivateSendServer privateSendServer;

/** Used to keep track of current status of mixing pool
 */
class CPrivateSendServer : public CPrivateSendBaseSession, public CPrivateSendBaseManager
{
private:
    // Mixing uses collateral transactions to trust parties entering the pool
    // to behave honestly. If they don't it takes their money.
    std::vector<CTransactionRef> vecSessionCollaterals;

    bool fUnitTest;

    /// Add a clients entry to the pool
    bool AddEntry(const CPrivateSendEntry& entryNew, PoolMessage& nMessageIDRet);
    /// Add signature to a txin
    bool AddScriptSig(const CTxIn& txin);

    /// Charge fees to bad actors (Charge clients a fee if they're abusive)
    void ChargeFees(CConnman& connman);
    /// Rarely charge fees to pay miners
    void ChargeRandomFees(CConnman& connman);

    /// Check for process
    void CheckPool(CConnman& connman);

    void CreateFinalTransaction(CConnman& connman);
    void CommitFinalTransaction(CConnman& connman);

    /// Is this nDenom and txCollateral acceptable?
    bool IsAcceptableDSA(const CPrivateSendAccept& dsa, PoolMessage& nMessageIDRet);
    bool CreateNewSession(const CPrivateSendAccept& dsa, PoolMessage& nMessageIDRet, CConnman& connman);
    bool AddUserToExistingSession(const CPrivateSendAccept& dsa, PoolMessage& nMessageIDRet);
    /// Do we have enough users to take entries?
    bool IsSessionReady() { return (int)vecSessionCollaterals.size() >= CPrivateSend::GetMaxPoolTransactions(); }

    /// Check that all inputs are signed. (Are all inputs signed?)
    bool IsSignaturesComplete();
    /// Check to make sure a given input matches an input in the pool and its scriptSig is valid
    bool IsInputScriptSigValid(const CTxIn& txin);
    /// Are these outputs compatible with other client in the pool?
    bool IsOutputsCompatibleWithSessionDenom(const std::vector<CTxOut>& vecTxOut);

    // Set the 'state' value, with some logging and capturing when the state changed
    void SetState(PoolState nStateNew);

    /// Relay mixing Messages
    void RelayFinalTransaction(const CTransaction& txFinal, CConnman& connman);
    void PushStatus(CNode* pnode, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, CConnman& connman);
    void RelayStatus(PoolStatusUpdate nStatusUpdate, CConnman& connman, PoolMessage nMessageID = MSG_NOERR);
    void RelayCompletedTransaction(PoolMessage nMessageID, CConnman& connman);

    void SetNull();

public:
    CPrivateSendServer() :
        vecSessionCollaterals(), fUnitTest(false) {}

    void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman);

    void CheckTimeout(CConnman& connman);
    void CheckForCompleteQueue(CConnman& connman);

    void DoMaintenance(CConnman& connman);
};

#endif


text:
/*INSERT INTO `posts` (`title`, `contents`) VALUES ('This is the first post', 'Yes it is.')

INSERT INTO `posts` SET
	`title` = 'The second post',
	`contents` = 'Once again, yes it is.'*/

/*SELECT `id`, `title`, `contents` FROM `posts`*/

/*UPDATE `posts` SET
	`title` = 'This is a post',
	`contents` = 'New content wooo'
WHERE `id` = 13*/

DELETE FROM `posts` WHERE `id` = 13


text:
{-# LANGUAGE OverloadedStrings #-}

-- Easy access to the phrase files

module Common.Phrases where

import qualified Data.Text as T
import qualified Data.Text.IO as T (readFile)

fileLines :: String -> IO [T.Text]
fileLines n = T.readFile n >>= return . T.splitOn "\n"

phraseFiles :: [String]
phraseFiles = [
    "./phrases/beatles-songs.txt",
    "./phrases/best-selling-books.txt",
    "./phrases/movie-quotes.txt",
    "./phrases/oscar-winning-movies.txt",
    "./phrases/wikipedia-idioms.txt"
    ]


text:
'use strict';

/**
* Find packages containing TypeScript declarations.
*
* @module @stdlib/_tools/pkgs/types
*
* @example
* var findTypes = require( '@stdlib/_tools/pkgs/types' );
*
* findTypes( clbk );
*
* function clbk( error, pkgs ) {
*     if ( error ) {
*         throw error;
*     }
*     console.dir( pkgs );
* }
*
* @example
* var findTypes = require( '@stdlib/_tools/pkgs/types' );
*
* var pkgs = findTypes.sync();
* // returns [...]
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var main = require( './main.js' );
var sync = require( './sync.js' );

// MAIN //

setReadOnly( main, 'sync', sync );

// EXPORTS //

module.exports = main;


text:
export interface RawGroup {
  name: string
  slug?: string
  groups?: RawGroup[]
  tags: string[]
}


text:
var atext = require('../lib/sharejs/atext');
var atext_test = require('./randomizer/atext');
var randomizer = require('ot-fuzzer');

describe('randomizer', function() {
  it('passes', function() {
    this.timeout(20000);
    randomizer(atext, atext.generateRandomOp);
  });
});


text:
package suspend_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"

	dataNormalizer "github.com/tidepool-org/platform/data/normalizer"
	"github.com/tidepool-org/platform/data/types/basal"
	dataTypesBasalAutomated "github.com/tidepool-org/platform/data/types/basal/automated"
	dataTypesBasalAutomatedTest "github.com/tidepool-org/platform/data/types/basal/automated/test"
	dataTypesBasalScheduled "github.com/tidepool-org/platform/data/types/basal/scheduled"
	dataTypesBasalScheduledTest "github.com/tidepool-org/platform/data/types/basal/scheduled/test"
	"github.com/tidepool-org/platform/data/types/basal/suspend"
	dataTypesBasalTemporary "github.com/tidepool-org/platform/data/types/basal/temporary"
	dataTypesBasalTemporaryTest "github.com/tidepool-org/platform/data/types/basal/temporary/test"
	dataTypesBasalTest "github.com/tidepool-org/platform/data/types/basal/test"
	dataTypesTest "github.com/tidepool-org/platform/data/types/test"
	errorsTest "github.com/tidepool-org/platform/errors/test"
	"github.com/tidepool-org/platform/pointer"
	"github.com/tidepool-org/platform/structure"
	structureValidator "github.com/tidepool-org/platform/structure/validator"
	"github.com/tidepool-org/platform/test"
)

func NewMeta() interface{} {
	return &basal.Meta{
		Type:         "basal",
		DeliveryType: "suspend",
	}
}

func NewSuspend() *suspend.Suspend {
	datum := suspend.New()
	datum.Basal = *dataTypesBasalTest.RandomBasal()
	datum.DeliveryType = "suspend"
	datum.Duration = pointer.FromInt(test.RandomIntFromRange(suspend.DurationMinimum, suspend.DurationMaximum))
	datum.DurationExpected = pointer.FromInt(test.RandomIntFromRange(*datum.Duration, suspend.DurationMaximum))
	datum.Suppressed = dataTypesBasalTemporaryTest.RandomSuppressedTemporary(dataTypesBasalScheduledTest.RandomSuppressedScheduled())
	return datum
}

func CloneSuspend(datum *suspend.Suspend) *suspend.Suspend {
	if datum == nil {
		return nil
	}
	clone := suspend.New()
	clone.Basal = *dataTypesBasalTest.CloneBasal(&datum.Basal)
	clone.Duration = pointer.CloneInt(datum.Duration)
	clone.DurationExpected = pointer.CloneInt(datum.DurationExpected)
	if datum.Suppressed != nil {
		switch suppressed := datum.Suppressed.(type) {
		case *dataTypesBasalAutomated.SuppressedAutomated:
			clone.Suppressed = dataTypesBasalAutomatedTest.CloneSuppressedAutomated(suppressed)
		case *dataTypesBasalScheduled.SuppressedScheduled:
			clone.Suppressed = dataTypesBasalScheduledTest.CloneSuppressedScheduled(suppressed)
		case *dataTypesBasalTemporary.SuppressedTemporary:
			clone.Suppressed = dataTypesBasalTemporaryTest.CloneSuppressedTemporary(suppressed)
		}
	}
	return clone
}

var _ = Describe("Suspend", func() {
	It("DeliveryType is expected", func() {
		Expect(suspend.DeliveryType).To(Equal("suspend"))
	})

	It("DurationMaximum is expected", func() {
		Expect(suspend.DurationMaximum).To(Equal(604800000))
	})

	It("DurationMinimum is expected", func() {
		Expect(suspend.DurationMinimum).To(Equal(0))
	})

	Context("New", func() {
		It("returns the expected datum with all values initialized", func() {
			datum := suspend.New()
			Expect(datum).ToNot(BeNil())
			Expect(datum.Type).To(Equal("basal"))
			Expect(datum.DeliveryType).To(Equal("suspend"))
			Expect(datum.Duration).To(BeNil())
			Expect(datum.DurationExpected).To(BeNil())
			Expect(datum.Suppressed).To(BeNil())
		})
	})

	Context("Suspend", func() {
		Context("Parse", func() {
			// TODO
		})

		Context("Validate", func() {
			DescribeTable("validates the datum",
				func(mutator func(datum *suspend.Suspend), expectedErrors ...error) {
					datum := NewSuspend()
					mutator(datum)
					dataTypesTest.ValidateWithExpectedOrigins(datum, structure.Origins(), expectedErrors...)
				},
				Entry("succeeds",
					func(datum *suspend.Suspend) {},
				),
				Entry("type missing",
					func(datum *suspend.Suspend) { datum.Type = "" },
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueEmpty(), "/type", &basal.Meta{DeliveryType: "suspend"}),
				),
				Entry("type invalid",
					func(datum *suspend.Suspend) { datum.Type = "invalidType" },
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotEqualTo("invalidType", "basal"), "/type", &basal.Meta{Type: "invalidType", DeliveryType: "suspend"}),
				),
				Entry("type basal",
					func(datum *suspend.Suspend) { datum.Type = "basal" },
				),
				Entry("delivery type missing",
					func(datum *suspend.Suspend) { datum.DeliveryType = "" },
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueEmpty(), "/deliveryType", &basal.Meta{Type: "basal"}),
				),
				Entry("delivery type invalid",
					func(datum *suspend.Suspend) { datum.DeliveryType = "invalidDeliveryType" },
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotEqualTo("invalidDeliveryType", "suspend"), "/deliveryType", &basal.Meta{Type: "basal", DeliveryType: "invalidDeliveryType"}),
				),
				Entry("delivery type suspend",
					func(datum *suspend.Suspend) { datum.DeliveryType = "suspend" },
				),
				Entry("duration missing; duration expected missing",
					func(datum *suspend.Suspend) {
						datum.Duration = nil
						datum.DurationExpected = nil
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotExists(), "/duration", NewMeta()),
				),
				Entry("duration missing; duration expected out of range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = nil
						datum.DurationExpected = pointer.FromInt(-1)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotExists(), "/duration", NewMeta()),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(-1, 0, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("duration missing; duration expected in range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = nil
						datum.DurationExpected = pointer.FromInt(0)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotExists(), "/duration", NewMeta()),
				),
				Entry("duration missing; duration expected in range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = nil
						datum.DurationExpected = pointer.FromInt(604800000)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotExists(), "/duration", NewMeta()),
				),
				Entry("duration missing; duration expected out of range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = nil
						datum.DurationExpected = pointer.FromInt(604800001)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotExists(), "/duration", NewMeta()),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("duration out of range (lower); duration expected missing",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(-1)
						datum.DurationExpected = nil
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(-1, 0, 604800000), "/duration", NewMeta()),
				),
				Entry("duration out of range (lower); duration expected out of range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(-1)
						datum.DurationExpected = pointer.FromInt(-1)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(-1, 0, 604800000), "/duration", NewMeta()),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(-1, 0, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("duration out of range (lower); duration expected in range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(-1)
						datum.DurationExpected = pointer.FromInt(0)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(-1, 0, 604800000), "/duration", NewMeta()),
				),
				Entry("duration out of range (lower); duration expected in range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(-1)
						datum.DurationExpected = pointer.FromInt(604800000)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(-1, 0, 604800000), "/duration", NewMeta()),
				),
				Entry("duration out of range (lower); duration expected out of range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(-1)
						datum.DurationExpected = pointer.FromInt(604800001)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(-1, 0, 604800000), "/duration", NewMeta()),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("duration in range (lower); duration expected missing",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(0)
						datum.DurationExpected = nil
					},
				),
				Entry("duration in range (lower); duration expected out of range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(0)
						datum.DurationExpected = pointer.FromInt(-1)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(-1, 0, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("duration in range (lower); duration expected in range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(0)
						datum.DurationExpected = pointer.FromInt(0)
					},
				),
				Entry("duration in range (lower); duration expected in range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(0)
						datum.DurationExpected = pointer.FromInt(604800000)
					},
				),
				Entry("duration in range (lower); duration expected out of range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(0)
						datum.DurationExpected = pointer.FromInt(604800001)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("duration in range (upper); duration expected missing",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800000)
						datum.DurationExpected = nil
					},
				),
				Entry("duration in range (upper); duration expected out of range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800000)
						datum.DurationExpected = pointer.FromInt(604799999)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604799999, 604800000, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("duration in range (upper); duration expected in range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800000)
						datum.DurationExpected = pointer.FromInt(604800000)
					},
				),
				Entry("duration in range (upper); duration expected in range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800000)
						datum.DurationExpected = pointer.FromInt(604800000)
					},
				),
				Entry("duration in range (upper); duration expected out of range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800000)
						datum.DurationExpected = pointer.FromInt(604800001)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 604800000, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("duration out of range (upper); duration expected missing",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800001)
						datum.DurationExpected = nil
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/duration", NewMeta()),
				),
				Entry("duration out of range (upper); duration expected out of range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800001)
						datum.DurationExpected = pointer.FromInt(-1)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/duration", NewMeta()),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(-1, 0, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("duration out of range (upper); duration expected in range (lower)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800001)
						datum.DurationExpected = pointer.FromInt(0)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/duration", NewMeta()),
				),
				Entry("duration out of range (upper); duration expected in range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800001)
						datum.DurationExpected = pointer.FromInt(604800000)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/duration", NewMeta()),
				),
				Entry("duration out of range (upper); duration expected out of range (upper)",
					func(datum *suspend.Suspend) {
						datum.Duration = pointer.FromInt(604800001)
						datum.DurationExpected = pointer.FromInt(604800001)
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/duration", NewMeta()),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/expectedDuration", NewMeta()),
				),
				Entry("suppressed missing",
					func(datum *suspend.Suspend) { datum.Suppressed = nil },
				),
				Entry("suppressed automated",
					func(datum *suspend.Suspend) {
						datum.Suppressed = dataTypesBasalAutomatedTest.RandomSuppressedAutomated()
					},
				),
				Entry("suppressed scheduled",
					func(datum *suspend.Suspend) {
						datum.Suppressed = dataTypesBasalScheduledTest.RandomSuppressedScheduled()
					},
				),
				Entry("suppressed temporary with suppressed missing",
					func(datum *suspend.Suspend) {
						datum.Suppressed = dataTypesBasalTemporaryTest.RandomSuppressedTemporary(nil)
					},
				),
				Entry("suppressed temporary with suppressed automated",
					func(datum *suspend.Suspend) {
						datum.Suppressed = dataTypesBasalTemporaryTest.RandomSuppressedTemporary(dataTypesBasalAutomatedTest.RandomSuppressedAutomated())
					},
				),
				Entry("suppressed temporary with suppressed scheduled",
					func(datum *suspend.Suspend) {
						datum.Suppressed = dataTypesBasalTemporaryTest.RandomSuppressedTemporary(dataTypesBasalScheduledTest.RandomSuppressedScheduled())
					},
				),
				Entry("suppressed temporary with suppressed temporary with suppressed missing",
					func(datum *suspend.Suspend) {
						datum.Suppressed = dataTypesBasalTemporaryTest.RandomSuppressedTemporary(dataTypesBasalTemporaryTest.RandomSuppressedTemporary(nil))
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotValid(), "/suppressed/suppressed", NewMeta()),
				),
				Entry("multiple errors",
					func(datum *suspend.Suspend) {
						datum.Type = "invalidType"
						datum.DeliveryType = "invalidDeliveryType"
						datum.Duration = nil
						datum.DurationExpected = pointer.FromInt(604800001)
						datum.Suppressed = dataTypesBasalTemporaryTest.RandomSuppressedTemporary(dataTypesBasalTemporaryTest.RandomSuppressedTemporary(nil))
					},
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotEqualTo("invalidType", "basal"), "/type", &basal.Meta{Type: "invalidType", DeliveryType: "invalidDeliveryType"}),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotEqualTo("invalidDeliveryType", "suspend"), "/deliveryType", &basal.Meta{Type: "invalidType", DeliveryType: "invalidDeliveryType"}),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotExists(), "/duration", &basal.Meta{Type: "invalidType", DeliveryType: "invalidDeliveryType"}),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotInRange(604800001, 0, 604800000), "/expectedDuration", &basal.Meta{Type: "invalidType", DeliveryType: "invalidDeliveryType"}),
					errorsTest.WithPointerSourceAndMeta(structureValidator.ErrorValueNotValid(), "/suppressed/suppressed", &basal.Meta{Type: "invalidType", DeliveryType: "invalidDeliveryType"}),
				),
			)
		})

		Context("Normalize", func() {
			DescribeTable("normalizes the datum",
				func(mutator func(datum *suspend.Suspend)) {
					for _, origin := range structure.Origins() {
						datum := NewSuspend()
						mutator(datum)
						expectedDatum := CloneSuspend(datum)
						normalizer := dataNormalizer.New()
						Expect(normalizer).ToNot(BeNil())
						datum.Normalize(normalizer.WithOrigin(origin))
						Expect(normalizer.Error()).To(BeNil())
						Expect(normalizer.Data()).To(BeEmpty())
						Expect(datum).To(Equal(expectedDatum))
					}
				},
				Entry("does not modify the datum",
					func(datum *suspend.Suspend) {},
				),
				Entry("does not modify the datum; type missing",
					func(datum *suspend.Suspend) { datum.Type = "" },
				),
				Entry("does not modify the datum; delivery type missing",
					func(datum *suspend.Suspend) { datum.DeliveryType = "" },
				),
				Entry("does not modify the datum; duration missing",
					func(datum *suspend.Suspend) { datum.Duration = nil },
				),
				Entry("does not modify the datum; duration expected missing",
					func(datum *suspend.Suspend) { datum.DurationExpected = nil },
				),
				Entry("does not modify the datum; suppressed missing",
					func(datum *suspend.Suspend) { datum.Suppressed = nil },
				),
			)
		})
	})
})


text:
'use strict';
var React = require('react');
var Reflux = require('reflux');

var VideoItem = require('../video-item/video-item.component');
var MusicActions = require('../../actions/music/music-actions');
var MusicStore = require('../../store/music/music-store');

var Music = React.createClass({

  mixins: [Reflux.connect(MusicStore)],

  getInitialState: function () {
    return {
      musicList: []
    }
  },

  componentWillMount: function () {
    MusicActions.getMusics();
    console.log('getMusics');
  },

  render: function () {

    var musicList = this.state.musicList.length === 0 ? '' : (<VideoItem videoItems={this.state.musicList}/>);

    return (

音乐

            更多>>

          {musicList}

    );
  }
});

module.exports = Music;


text:
<?php

namespace Org\Schema\Thing\Action\InteractAction\CommunicateAction;

/**
 * InformAction Class.
 * The act of notifying someone of information pertinent to them, with no expectation of a response.
 * @author      AppBels <app.bels@gmail.com>
 * @name        InformAction
 * @namespace   Org\Schema\Thing\Action\InteractAction\CommunicateAction
 * @package		Org\Schema
 * @see			https://schema.org/InformAction
 * Date         26/02/2017
 */
class InformAction extends \Org\Schema\Thing\Action\InteractAction\CommunicateAction
{

	/**
	 * Upcoming or past event associated with this place, organization, or action.
	 * Supersedes events.
	 * @access	public
	 * @var		\Org\Schema\Thing\Event
	 */
	public $event;

	/**
	 * InformAction constructor.
	 * @access	public
	 * @see		\Org\Schema\Thing\Action\InteractAction\CommunicateAction::__construct()
	 */
	public function __construct ()
	{
		parent::__construct();
	}

	/**
	 * InformAction toString.
	 * @access  public
	 * @see     \Org\Schema\Thing\Action\InteractAction\CommunicateAction::__toString()
	 *
	 * @return  string
	 */
	public function __toString ()
	{
		return parent::__toString();
	}

	/**
	 * InformAction destructor.
	 * @access	public
	 * @see		\Org\Schema\Thing\Action\InteractAction\CommunicateAction::__destruct()
	 */
	public function __destruct ()
	{
		parent::__destruct();
	}

}

?>


text:
import matplotlib.pyplot as plt
import numpy as np
import constants as const
from matplotlib.ticker import Formatter
from RgChart import RgChart
from RgVars import MRT, AT

class LineChart(RgChart):

    def __init__(self, *measurements):
        self._fig, self._ax = plt.subplots()
        self._lines = self._create_base_line(measurements)

    def with_defaults(self):
        self.with_title().with_ylabel().with_grids()
        return self

    def with_xticks_names(self, xt_names = None):
        if xt_names is not None:
            formatter = XAxFormatter(xt_names)
            self._ax.xaxis.set_major_formatter(formatter)
            #self.__fig.autofmt_xdate()
        return self

    def with_line(self, color = 'b', *measurements):
        self._lines.append(self._create_line(measurements, color)[0])
        return self

    def with_legend(self, *labels):
        for i in range(0,len(labels)):
            self._lines[i].set_label(labels[i])
        self._legend = plt.legend(loc='upper center', fancybox=True, shadow=True, ncol=5)
        return self

    def _create_line(self, measurements, color = 'b'):
        nm = len(measurements)
        ind = np.arange(nm)
        val, xax = [], []
        for i in range(0, len(measurements)):
            val.append(measurements[i]._mrt)
            xax.append(measurements[i]._title)

        #decide if plot MRT or AT
        if (issubclass(measurements[i]._rg_var, AT)):
            return None #TODO
        elif  (issubclass(measurements[i]._rg_var, MRT)):
            return plt.plot(ind, val, '%co-'%color)
        else:
            raise ValueError("Unknown variable")

    def _create_base_line(self, measurements):
        self._title = measurements[0]._title if measurements[0]._title is not None else ""
        self._ylabel = measurements[0]._rg_var.ylabel if measurements[0]._rg_var is None else ""
        return self._create_line(measurements)

    def _create_plot(self):
        baseline = self._lines[0]
        nm = len(baseline.get_data()[0]) # number of measurements on base line
        self._ax.set_xlim(-const.X_AX_OFFSET, nm - const.X_AX_OFFSET)
        plt.setp([self._lines])

class XAxFormatter(Formatter):
    def __init__(self, xvals):
        self._xvals = xvals

    def __call__(self, x, pos=0):
        'Return the label for time x at position pos'
        #ind = int(round(x))
        #if ind >= len(self._xvals) or ind < 0: return ''
        if(x.is_integer()):
            ind = int(x)
            return self._xvals[ind]
        else:
            return ''


text:
<?php

/**
 * Customer country attribute source
 *
 * @category    Mage
 * @package     Mage_Customer
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Customer_Model_Entity_Address_Attribute_Source_Country
    extends Mage_Customer_Model_Resource_Address_Attribute_Source_Country
{
}


text:
"""Tests for the Nest integration API glue library.

There are two interesting cases to exercise that have different strategies
for token refresh and for testing:
- API based requests, tested using aioclient_mock
- Pub/sub subcriber initialization, intercepted with patch()

The tests below exercise both cases during integration setup.
"""

import time
from unittest.mock import patch

import pytest

from homeassistant.components.nest import DOMAIN
from homeassistant.components.nest.const import API_URL, OAUTH2_TOKEN, SDM_SCOPES
from homeassistant.setup import async_setup_component
from homeassistant.util import dt

from .common import (
    CLIENT_ID,
    CLIENT_SECRET,
    CONFIG,
    FAKE_REFRESH_TOKEN,
    FAKE_TOKEN,
    PROJECT_ID,
    TEST_CONFIGFLOW_YAML_ONLY,
    create_config_entry,
)

FAKE_UPDATED_TOKEN = "fake-updated-token"

async def async_setup_sdm(hass):
    """Set up the integration."""
    assert await async_setup_component(hass, DOMAIN, CONFIG)
    await hass.async_block_till_done()

@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY])
async def test_auth(hass, aioclient_mock):
    """Exercise authentication library creates valid credentials."""

    expiration_time = time.time() + 86400
    create_config_entry(expiration_time).add_to_hass(hass)

    # Prepare to capture credentials in API request.  Empty payloads just mean
    # no devices or structures are loaded.
    aioclient_mock.get(f"{API_URL}/enterprises/{PROJECT_ID}/structures", json={})
    aioclient_mock.get(f"{API_URL}/enterprises/{PROJECT_ID}/devices", json={})

    # Prepare to capture credentials for Subscriber
    captured_creds = None

    async def async_new_subscriber(creds, subscription_name, loop, async_callback):
        """Capture credentials for tests."""
        nonlocal captured_creds
        captured_creds = creds
        return None  # GoogleNestSubscriber

    with patch(
        "google_nest_sdm.google_nest_subscriber.DefaultSubscriberFactory.async_new_subscriber",
        side_effect=async_new_subscriber,
    ) as new_subscriber_mock:
        await async_setup_sdm(hass)

    # Verify API requests are made with the correct credentials
    calls = aioclient_mock.mock_calls
    assert len(calls) == 2
    (method, url, data, headers) = calls[0]
    assert headers == {"Authorization": f"Bearer {FAKE_TOKEN}"}
    (method, url, data, headers) = calls[1]
    assert headers == {"Authorization": f"Bearer {FAKE_TOKEN}"}

    # Verify the susbcriber was created with the correct credentials
    assert len(new_subscriber_mock.mock_calls) == 1
    assert captured_creds
    creds = captured_creds
    assert creds.token == FAKE_TOKEN
    assert creds.refresh_token == FAKE_REFRESH_TOKEN
    assert int(dt.as_timestamp(creds.expiry)) == int(expiration_time)
    assert creds.valid
    assert not creds.expired
    assert creds.token_uri == OAUTH2_TOKEN
    assert creds.client_id == CLIENT_ID
    assert creds.client_secret == CLIENT_SECRET
    assert creds.scopes == SDM_SCOPES

@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY])
async def test_auth_expired_token(hass, aioclient_mock):
    """Verify behavior of an expired token."""

    expiration_time = time.time() - 86400
    create_config_entry(expiration_time).add_to_hass(hass)

    # Prepare a token refresh response
    aioclient_mock.post(
        OAUTH2_TOKEN,
        json={
            "access_token": FAKE_UPDATED_TOKEN,
            "expires_at": time.time() + 86400,
            "expires_in": 86400,
        },
    )
    # Prepare to capture credentials in API request.  Empty payloads just mean
    # no devices or structures are loaded.
    aioclient_mock.get(f"{API_URL}/enterprises/{PROJECT_ID}/structures", json={})
    aioclient_mock.get(f"{API_URL}/enterprises/{PROJECT_ID}/devices", json={})

    # Prepare to capture credentials for Subscriber
    captured_creds = None

    async def async_new_subscriber(creds, subscription_name, loop, async_callback):
        """Capture credentials for tests."""
        nonlocal captured_creds
        captured_creds = creds
        return None  # GoogleNestSubscriber

    with patch(
        "google_nest_sdm.google_nest_subscriber.DefaultSubscriberFactory.async_new_subscriber",
        side_effect=async_new_subscriber,
    ) as new_subscriber_mock:
        await async_setup_sdm(hass)

    calls = aioclient_mock.mock_calls
    assert len(calls) == 3
    # Verify refresh token call to get an updated token
    (method, url, data, headers) = calls[0]
    assert data == {
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "grant_type": "refresh_token",
        "refresh_token": FAKE_REFRESH_TOKEN,
    }
    # Verify API requests are made with the new token
    (method, url, data, headers) = calls[1]
    assert headers == {"Authorization": f"Bearer {FAKE_UPDATED_TOKEN}"}
    (method, url, data, headers) = calls[2]
    assert headers == {"Authorization": f"Bearer {FAKE_UPDATED_TOKEN}"}

    # The subscriber is created with a token that is expired.  Verify that the
    # credential is expired so the subscriber knows it needs to refresh it.
    assert len(new_subscriber_mock.mock_calls) == 1
    assert captured_creds
    creds = captured_creds
    assert creds.token == FAKE_TOKEN
    assert creds.refresh_token == FAKE_REFRESH_TOKEN
    assert int(dt.as_timestamp(creds.expiry)) == int(expiration_time)
    assert not creds.valid
    assert creds.expired
    assert creds.token_uri == OAUTH2_TOKEN
    assert creds.client_id == CLIENT_ID
    assert creds.client_secret == CLIENT_SECRET
    assert creds.scopes == SDM_SCOPES


text:
package org.hibernate.test.sql.hand;

/**
 * Used to mimic some tests from the JPA testsuite...
 *
 * @author Steve Ebersole
 */
public class Dimension {
	private Long id;
	private int length;
	private int width;

	public Dimension() {}

	public Dimension(int length, int width) {
		this.length = length;
		this.width = width;
	}

	public Long getId() {
		return id;
	}

	public int getLength() {
		return length;
	}

	public int getWidth() {
		return width;
	}
}


text:
package org.apache.geode.distributed.internal.locks;

import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Collection;
import java.util.LinkedList;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.ExpirationAction;
import org.apache.geode.cache.ExpirationAttributes;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.Scope;
import org.apache.geode.internal.cache.DistributedRegion;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.test.junit.rules.ExecutorServiceRule;

@Category(IntegrationTest.class)
public class DLockServiceLeakTest {

  private Cache cache;
  private DistributedRegion testRegion;

  @Rule
  public ExecutorServiceRule executorServiceRule =
      ExecutorServiceRule.builder().threadCount(5).build();

  @Before
  public void setUp() {
    Properties properties = new Properties();
    properties.setProperty(MCAST_PORT, "0");

    cache = new CacheFactory(properties).create();
    testRegion = (DistributedRegion) cache.createRegionFactory(RegionShortcut.REPLICATE)
        .setScope(Scope.GLOBAL)
        .setEntryTimeToLive(new ExpirationAttributes(1, ExpirationAction.DESTROY))
        .create("testRegion");
    testRegion.becomeLockGrantor();
  }

  @After
  public void tearDown() {
    cache.close();
  }

  @Test
  public void basicDLockUsage() throws InterruptedException, ExecutionException, TimeoutException {
    Lock lock = testRegion.getDistributedLock("testLockName");
    lock.lockInterruptibly();

    Future<Boolean> future = executorServiceRule.submit(() -> lock.tryLock());
    assertFalse("should not be able to get lock from another thread",
        future.get(5, TimeUnit.SECONDS));

    assertTrue("Lock is reentrant", lock.tryLock());
    // now locked twice.

    future = executorServiceRule.submit(() -> lock.tryLock());
    assertFalse("should not be able to get lock from another thread",
        future.get(5, TimeUnit.SECONDS));

    lock.unlock();

    future = executorServiceRule.submit(() -> lock.tryLock());
    assertFalse("should not be able to get lock from another thread", future.get());

    lock.unlock();

    future = executorServiceRule.submit(() -> {
      boolean locked = lock.tryLock();
      if (!locked) {
        return false;
      }
      lock.unlock();
      return true;
    });
    assertTrue("Another thread can now take out the lock", future.get(5, TimeUnit.SECONDS));

    DLockService lockService = (DLockService) testRegion.getLockService();
    Collection<DLockToken> tokens = lockService.getTokens();

    for (DLockToken token : tokens) {
      assertEquals(0, token.getUsageCount());
    }
  }

  @Test
  public void singleThreadWithCache() {
    putTestKey();

    DLockService lockService = (DLockService) testRegion.getLockService();
    Collection<DLockToken> tokens = lockService.getTokens();

    assertEquals(1, tokens.size());

    for (DLockToken token : tokens) {
      assertEquals(0, token.getUsageCount());
    }
  }

  @Test
  public void multipleThreadsWithCache() {
    LinkedList<Future> futures = new LinkedList<>();
    for (int i = 0; i < 5; i++) {
      futures.add(executorServiceRule.submit(this::putTestKey));
    }

    futures.forEach(future -> {
      try {
        future.get();
      } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
      }
    });

    DLockService lockService = (DLockService) testRegion.getLockService();
    Collection<DLockToken> tokens = lockService.getTokens();

    assertTrue(tokens.size() < 2);

    for (DLockToken token : tokens) {
      assertEquals(0, token.getUsageCount());
    }
  }

  private void putTestKey() {
    for (int i = 0; i < 1000; i++) {
      testRegion.put("testKey", "testValue");
    }
  }
}


text:
cask "the-archive-browser" do
  version "1.11.2,111:1504018288"
  sha256 "a9cffc4d7a4e9869c9b7542dff7b9614c487623fce6404ce779b0c4b654eb72b"

  url "https://dl.devmate.com/cx.c3.thearchivebrowser/#{version.after_comma.before_colon}/#{version.after_colon}/TheArchiveBrowser-#{version.after_comma.before_colon}.zip",
      verified: "dl.devmate.com/cx.c3.thearchivebrowser/"
  name "The Archive Browser"
  homepage "https://theunarchiver.com/archive-browser"

  livecheck do
    url "https://updates.devmate.com/cx.c3.thearchivebrowser.xml"
    strategy :sparkle do |item|
      "#{item.short_version},#{item.version}:#{item.url[%r{/(\d+)/TheArchiveBrowser-\d+\.zip}i, 1]}"
    end
  end

  auto_updates true

  app "The Archive Browser.app"

  zap trash: [
    "~/Library/Cookies/cx.c3.thearchivebrowser.binarycookies",
    "~/Library/Preferences/cx.c3.thearchivebrowser.plist",
  ],
      rmdir: [
        "~/Library/Application Support/The Archive Browser",
        "~/Library/Caches/cx.c3.thearchivebrowser",
      ]
end


text:
const init = (db) => {
  return {
    users: require('./users/')(db),
    comments: require('./comments/')(db),
    posts: require('./posts')(db),
  };
};

module.exports = { init };


text:
package org.nd4j.jita.allocator.tad;

import org.bytedeco.javacpp.LongPointer;
import org.nd4j.linalg.primitives.Pair;
import org.bytedeco.javacpp.IntPointer;
import org.bytedeco.javacpp.Pointer;
import org.nd4j.jita.allocator.impl.AtomicAllocator;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.cache.TADManager;
import org.nd4j.linalg.jcublas.buffer.AddressRetriever;
import org.nd4j.linalg.jcublas.buffer.CudaDoubleDataBuffer;
import org.nd4j.linalg.jcublas.buffer.CudaIntDataBuffer;
import org.nd4j.linalg.jcublas.buffer.CudaLongDataBuffer;
import org.nd4j.nativeblas.LongPointerWrapper;
import org.nd4j.nativeblas.NativeOps;
import org.nd4j.nativeblas.NativeOpsHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author raver119@gmail.com
 */
public class BasicTADManager implements TADManager {
    protected NativeOps nativeOps = NativeOpsHolder.getInstance().getDeviceNativeOps();
    private static Logger logger = LoggerFactory.getLogger(BasicTADManager.class);
    protected AtomicLong bytes = new AtomicLong(0);

    @Override
    public Pair<DataBuffer, DataBuffer> getTADOnlyShapeInfo(INDArray array, int[] dimension) {
        if (dimension != null && dimension.length > 1)
            Arrays.sort(dimension);

        if (dimension == null)
            dimension = new int[] {Integer.MAX_VALUE};

        boolean isScalar = dimension == null || (dimension.length == 1 && dimension[0] == Integer.MAX_VALUE);

        // FIXME: this is fast triage, remove it later
        int targetRank = isScalar ? 2 : array.rank(); //dimensionLength <= 1 ? 2 : dimensionLength;
        long offsetLength = 0;
        long tadLength = 1;

        if(!isScalar)
            for (int i = 0; i < dimension.length; i++) {
                tadLength *= array.shape()[dimension[i]];
            }

        if(!isScalar)
            offsetLength = array.lengthLong() / tadLength;
        else
            offsetLength = 1;
        //     logger.info("Original shape info before TAD: {}", array.shapeInfoDataBuffer());
        //    logger.info("dimension: {}, tadLength: {}, offsetLength for TAD: {}", Arrays.toString(dimension),tadLength, offsetLength);

        DataBuffer outputBuffer = new CudaLongDataBuffer(targetRank * 2 + 4);
        DataBuffer offsetsBuffer = new CudaLongDataBuffer(offsetLength);

        AtomicAllocator.getInstance().getAllocationPoint(outputBuffer).tickHostWrite();
        AtomicAllocator.getInstance().getAllocationPoint(offsetsBuffer).tickHostWrite();

        DataBuffer dimensionBuffer = AtomicAllocator.getInstance().getConstantBuffer(dimension);
        Pointer dimensionPointer = AtomicAllocator.getInstance().getHostPointer(dimensionBuffer);

        Pointer xShapeInfo = AddressRetriever.retrieveHostPointer(array.shapeInfoDataBuffer());
        Pointer targetPointer = AddressRetriever.retrieveHostPointer(outputBuffer);
        Pointer offsetsPointer = AddressRetriever.retrieveHostPointer(offsetsBuffer);
        if(!isScalar)
            nativeOps.tadOnlyShapeInfo((LongPointer) xShapeInfo, (IntPointer) dimensionPointer, dimension.length,
                    (LongPointer) targetPointer, new LongPointerWrapper(offsetsPointer));

        else  {
            outputBuffer.put(0,2);
            outputBuffer.put(1,1);
            outputBuffer.put(2,1);
            outputBuffer.put(3,1);
            outputBuffer.put(4,1);
            outputBuffer.put(5,0);
            outputBuffer.put(6,0);
            outputBuffer.put(7,99);

        }

        AtomicAllocator.getInstance().getAllocationPoint(outputBuffer).tickHostWrite();
        AtomicAllocator.getInstance().getAllocationPoint(offsetsBuffer).tickHostWrite();

        //   logger.info("TAD shapeInfo after construction: {}", Arrays.toString(TadDescriptor.dataBufferToArray(outputBuffer)));
        // now we need to copy this buffer to either device global memory or device cache

        return new Pair<>(outputBuffer, offsetsBuffer);

    }

    /**
     * This method removes all cached shape buffers
     */
    @Override
    public void purgeBuffers() {
        // no-op
    }

    @Override
    public long getCachedBytes() {
        return bytes.get();
    }
}


text:
require 'rails_helper'

RSpec.describe DashboardController, type: :controller do
  describe 'GET #show' do
    it 'returns http redirect when logged out' do
      get :show
      expect(response).to have_http_status(:redirect)
    end
    # it 'returns http success when logged in' do
    #   user = create(:user)
    #   login_as(user, scope: :user)
    #   get :show
    #   expect(response).to have_http_status(:success)
    # end
  end
end


text:
package org.test.filter;

import marvin.MarvinPluginCollection;
import marvin.image.MarvinImage;
import org.test.filter.core.BaseFilter;
import org.test.filter.core.ColorFilter;
import org.test.filter.core.FilterContext;

/**
 * Created by BORIS on 19.08.2017.
 */
public class CropFilter extends BaseFilter implements ColorFilter<MarvinImage, MarvinImage> {

    public CropFilter(FilterContext filterContext) {
        super(filterContext);
    }

    @Override
    public MarvinImage filter(MarvinImage image) {
        super.filter(image);
        int indentY = image.getHeight() / 5;
        int indentX = image.getWidth() / 5;
        int y1 = indentY;
        int x1 = indentX;
        int x2 = image.getWidth() - (indentX * 2);
        int y2 = image.getHeight() - (indentY * 2);
        MarvinPluginCollection.crop(image.clone(), image, x1, y1, x2, y2);
        return image;
    }

}


text:
ko.bindingHandlers.dnnDatePicker = {
    init: function (element, valueAccessor) {
        Sys.Application.add_load(function () {
            var picker = $find(element.id.replace('_wrapper', ''));
            if (!picker) {
                return;
            }
            var value = ko.utils.unwrapObservable(valueAccessor());
            picker.set_selectedDate(value);
            picker.add_dateSelected(function (sender, e) {
                var date = e.get_newDate();
                var observable = valueAccessor();
                if (observable().compare(date) !== 0) {
                    observable(date);
                }
            });
        });
    },
    update: function (element, valueAccessor) {
        var picker = $find(element.id.replace('_wrapper', ''));
        var value = ko.utils.unwrapObservable(valueAccessor());
        if (picker) {
            picker.set_selectedDate(value);
        }
    }
};