text:
require_relative "ohai/version"
require_relative "ohai/config"
require_relative "ohai/system"
require_relative "ohai/exception"

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;

namespace Roro.Activities.Files
{
    public class FolderExists : DecisionNodeActivity
    {
        public Input<Text> FolderPath { get; set; }

        public override bool Execute(ActivityContext context)
        {
            var folderPath = context.Get(this.FolderPath);
            return Directory.Exists(folderPath);
        }
    }
}


text:
#ifndef CLLogger_H
#define CLLogger_H

#include "CLStatus.h"

/*
ÓÃÓÚÏòÎļþLOG_FILE_NAMEÖУ¬¼Ç¼ÈÕÖ¾ÐÅÏ¢
*/
class CLLogger
{
public:
	static CLLogger* GetInstance();
	static CLStatus WriteLogMsg(const char *pstrMsg, long lErrorCode);
	CLStatus WriteLog(const char *pstrMsg, long lErrorCode);
	CLStatus Flush();

private:
	CLLogger(const CLLogger&);
	CLLogger& operator=(const CLLogger&);

	CLLogger();
	~CLLogger();

	int m_Fd;
	static CLLogger *m_pLog;

private:
	char *m_pLogBuffer;
	unsigned int m_nUsedBytesForBuffer;
};

#endif


text:
Caffeine Bedtime Calculator. 2017 Seth L

Version: 0.0.3

---

Calculates the date/time when you can reasonably expect your sleep to no
longer be impaired by caffeine, based on a metabolic half-life of 5.7
hours.

Arguments:

    TARGET:         Natural number. Target caffeine amount (in milligrams) for
                        bedtime. Recommendation: 50 to 100
    TIME_AMOUNT:    Format is '24-hour-time:amount'. 'Amount' is milligrams of
                        caffeine. E.g, '1100:300'

Example:

    python cbc.py 75 '1100:300' '1500:5'

* `75` is how many milligrams of caffeine the user wants in their system at bedtime.
* `'1100:300'` means the user had 300mg of caffeine at 11:00 a.m.
* `'1500:5'` means the user had 5mg of caffeine at 3:00 p.m.

![./img/showme.png](./img/showme.png)

## Prerequisites

1. Python 3
2. pip (pip3, for Python 3)
3. virtualenv (`pip install virtualenv`)

## Installation

    # Clone repo
    git clone https://github.com/sethll/caffeine-bedtime-calculator.git
    cd caffeine-bedtime-calculator

    # Using a virtual environment is recommended, but not required. You may
    # skip these steps.
    virtualenv venv -p python3
    . venv/bin/activate

    # Install dependencies
    pip install -r requirements.txt


text:
package techreborn.blocks;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import prospector.shootingstar.ShootingStar;
import prospector.shootingstar.model.ModelCompound;
import reborncore.common.BaseBlock;
import techreborn.client.TechRebornCreativeTabMisc;
import techreborn.entities.EntityNukePrimed;
import techreborn.lib.ModInfo;

/**
 * Created by Mark on 13/03/2016.
 */
public class BlockNuke extends BaseBlock {
	public static final PropertyBool OVERLAY = PropertyBool.create("overlay");

	public BlockNuke() {
		super(Material.TNT);
		setUnlocalizedName("techreborn.nuke");
		setCreativeTab(TechRebornCreativeTabMisc.instance);
		this.setDefaultState(this.blockState.getBaseState().withProperty(OVERLAY, false));
		ShootingStar.registerModel(new ModelCompound(ModInfo.MOD_ID, this));
	}

	public void explode(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase igniter) {
		if (!worldIn.isRemote) {
			EntityNukePrimed entitynukeprimed = new EntityNukePrimed(worldIn, (double) ((float) pos.getX() + 0.5F),
				(double) pos.getY(), (double) ((float) pos.getZ() + 0.5F), igniter);
			worldIn.spawnEntity(entitynukeprimed);
			// worldIn.playSoundAtEntity(entitynukeprimed, "game.tnt.primed",
			// 1.0F, 1.0F);
		}
	}

	@Override
	public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn) {
		if (!worldIn.isRemote) {
			EntityNukePrimed entitynukeprimed = new EntityNukePrimed(worldIn, (double) ((float) pos.getX() + 0.5F),
				(double) pos.getY(), (double) ((float) pos.getZ() + 0.5F), explosionIn.getExplosivePlacedBy());
			entitynukeprimed.fuse = worldIn.rand.nextInt(entitynukeprimed.fuse / 4) + entitynukeprimed.fuse / 8;
			worldIn.spawnEntity(entitynukeprimed);
		}
	}

	@Override
	public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) {
		if (!worldIn.isRemote && entityIn instanceof EntityArrow) {
			EntityArrow entityarrow = (EntityArrow) entityIn;

			if (entityarrow.isBurning()) {
				this.explode(worldIn, pos, state, entityarrow.shootingEntity instanceof EntityLivingBase
				                                  ? (EntityLivingBase) entityarrow.shootingEntity : null);
				worldIn.setBlockToAir(pos);
			}
		}
	}

	@Override
	public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) {
		super.onBlockAdded(worldIn, pos, state);
		if (worldIn.isBlockPowered(pos)) {
			this.explode(worldIn, pos, state, null);
			worldIn.setBlockToAir(pos);
		}
	}

	/**
	 * Called when a neighboring block changes.
	 */
	@Override
	public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos p_189540_5_) {
		if (worldIn.isBlockPowered(pos)) {
			this.explode(worldIn, pos, state, null);
			worldIn.setBlockToAir(pos);
		}
	}

	@Override
	public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn,
	                                EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {
		return false;
	}

	@Override
	public int getMetaFromState(IBlockState state) {
		return state.getValue(OVERLAY) ? 1 : 0;
	}

	@Override
	public IBlockState getStateFromMeta(int meta) {
		return this.getDefaultState().withProperty(OVERLAY, (meta & 1) > 0);
	}

	@Override
	protected BlockStateContainer createBlockState() {
		return new BlockStateContainer(this, OVERLAY);
	}

}


text:
Simple Electron shell around Plex web app.

## Dev

```
$ npm install
```

### Run

```
$ npm start
```

### Build

```
$ npm run build
```

Builds the app for OS X, Linux, and Windows, using [electron-packager](https://github.com/maxogden/electron-packager).

## License

MIT © [Erik](http://gartner.io)


text:
package com.google.api.ads.adwords.jaxws.v201502.cm;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Job-handling statistics.
 *
 *
 *
Java class for JobStats complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="JobStats">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="progressPercent" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="pendingTimeMillis" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="processingTimeMillis" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="JobStats.Type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "JobStats", propOrder = {
    "progressPercent",
    "pendingTimeMillis",
    "processingTimeMillis",
    "jobStatsType"
})
public class JobStats {

    protected Integer progressPercent;
    protected Long pendingTimeMillis;
    protected Long processingTimeMillis;
    @XmlElement(name = "JobStats.Type")
    protected String jobStatsType;

    /**
     * Gets the value of the progressPercent property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getProgressPercent() {
        return progressPercent;
    }

    /**
     * Sets the value of the progressPercent property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setProgressPercent(Integer value) {
        this.progressPercent = value;
    }

    /**
     * Gets the value of the pendingTimeMillis property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getPendingTimeMillis() {
        return pendingTimeMillis;
    }

    /**
     * Sets the value of the pendingTimeMillis property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setPendingTimeMillis(Long value) {
        this.pendingTimeMillis = value;
    }

    /**
     * Gets the value of the processingTimeMillis property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getProcessingTimeMillis() {
        return processingTimeMillis;
    }

    /**
     * Sets the value of the processingTimeMillis property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setProcessingTimeMillis(Long value) {
        this.processingTimeMillis = value;
    }

    /**
     * Gets the value of the jobStatsType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getJobStatsType() {
        return jobStatsType;
    }

    /**
     * Sets the value of the jobStatsType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setJobStatsType(String value) {
        this.jobStatsType = value;
    }

}


text:
//  Copyright 2011年 Renren Inc. All rights reserved.
//  - Powered by Team Pegasus. -
//
#import <CommonCrypto/CommonDigest.h>
#import "ROConnect.h"
#import "JSONKit.h"
#import "ROCreateAlbumResponseItem.h"
#import "ROUserResponseItem.h"
#import "ROUtility.h"
#import "ROPublishPhotoRequestParam.h"
#import "RODialog.h"
#import "RORequest.h"
#import "Renren.h"

@interface Renren(Private)

- (void)setGeneralRequestArgs:(RORequestParam *)inRequestParam;

- (void)getLoggedInUserId;
// 新方法。
- (void)sendRequestWithUrl:(NSString *)url param:(RORequestParam *)param httpMethod:(NSString *)httpMethod delegate:(id<RORequestDelegate>)delegate;

// 旧方法。
- (RORequest*)openUrl:(NSString *)url params:(NSMutableDictionary *)params httpMethod:(NSString *)httpMethod delegate:(id<RORequestDelegate>)delegate;

- (NSString *)getSecretKeyByToken:(NSString *)token;
- (NSString *)getSessionKeyByToken:(NSString *)token;

/**
 * 删除当前用户登录状态
 */
- (void)delUserSessionInfo;

- (void)authorizeWithRRAppAuth:(BOOL)tryRRAppAuth safariAuth:(BOOL)trySafariAuth;

@end

@implementation Renren

@synthesize accessToken = _accessToken;
@synthesize expirationDate = _expirationDate;
@synthesize secret=_secret;
@synthesize sessionKey=_sessionKey;
@synthesize appKey = _appKey;
@synthesize appId = _appId;
@synthesize renrenDelegate = _renrenDelegate;
@synthesize permissions = _permissions;

#pragma mark - Construction & Destruction -

static Renren *sharedRenren = nil;

/**
 * Override NSObject : release the data members.
 */
- (void)dealloc {
	[_accessToken release];
	[_expirationDate release];
	[_request release];
	[_rrDialog release];
	[_appId release];
	self.appKey = nil;
	[_secret release];
	[_permissions release];
	[_sessionKey release];
	[super dealloc];
}

+ (Renren *)newRenRen{
    Renren *newRenrenObject = [[Renren alloc] init];
    [newRenrenObject isSessionValid];
    newRenrenObject.appKey = SHKCONFIG(renrenConsumerKey);
    newRenrenObject.appId = SHKCONFIG(renrenAppId);
    return [newRenrenObject autorelease];
}

+ (Renren *)sharedRenren {
    if (!sharedRenren) {
        sharedRenren = [[Renren alloc] init];
        [sharedRenren isSessionValid];
        sharedRenren.appKey = SHKCONFIG(renrenConsumerKey);
        sharedRenren.appId = SHKCONFIG(renrenAppId);
    }
    return sharedRenren;
}

#pragma mark - General Public Methods -

-(BOOL)isSessionValid{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	if (nil != defaults){
		self.accessToken = [defaults objectForKey:@"access_Token"];
		self.expirationDate = [defaults objectForKey:@"expiration_Date"];
		self.sessionKey = [defaults objectForKey:@"session_Key"];
		self.secret = [defaults objectForKey:@"secret_Key"];
	}
    return (self.accessToken != nil && self.expirationDate != nil && self.sessionKey != nil && NSOrderedDescending == [self.expirationDate compare:[NSDate date]]);
}

#pragma mark - Private Methods -

/**
 * 保存用户经oauth 2.0登录后的信息,到UserDefaults中。
 */
-(void)saveUserSessionInfo{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (self.accessToken) {
        [defaults setObject:self.accessToken forKey:@"access_Token"];
    }
	if (self.expirationDate) {
		[defaults setObject:self.expirationDate forKey:@"expiration_Date"];
	}
    if (self.sessionKey) {
        [defaults setObject:self.sessionKey forKey:@"session_Key"];
        [defaults setObject:self.secret forKey:@"secret_Key"];
    }

    [defaults synchronize];
}

/**
 * 删除UserDefaults中保存的用户oauth 2.0信息
 */
-(void)delUserSessionInfo{
	NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"access_Token"];
	[defaults removeObjectForKey:@"secret_Key"];
	[defaults removeObjectForKey:@"session_Key"];
	[defaults removeObjectForKey:@"expiration_Date"];
    [defaults removeObjectForKey:@"session_UserId"];
	NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
	NSArray* graphCookies = [cookies cookiesForURL:
                             [NSURL URLWithString:@"http://graph.renren.com"]];

	for (NSHTTPCookie* cookie in graphCookies) {
		[cookies deleteCookie:cookie];
	}
	NSArray* widgetCookies = [cookies cookiesForURL:[NSURL URLWithString:@"http://widget.renren.com"]];

	for (NSHTTPCookie* cookie in widgetCookies) {
		[cookies deleteCookie:cookie];
	}
	[defaults synchronize];
}

- (void)getLoggedInUserId{
  	NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"session_UserId"]) {
        return;
    }
    RORequestParam * param = [[[RORequestParam alloc] init] autorelease];
    param.method = @"users.getLoggedInUser";
	[self requestWithParam:param andDelegate:self];

}
// 新的接口。
- (void)sendRequestWithUrl:(NSString *)url param:(RORequestParam *)param httpMethod:(NSString *)httpMethod delegate:(id<RORequestDelegate>)delegate{
    [_request release];

    delegate = delegate?delegate:self;
    _request = [[RORequest getRequestWithParam:param httpMethod:httpMethod delegate:delegate requestURL:url] retain];
    [_request connect];
    return;
}

// 旧的接口
- (RORequest*)openUrl:(NSString *)url params:(NSMutableDictionary *)params httpMethod:(NSString *)httpMethod delegate:(id<RORequestDelegate>)delegate{
    [_request release];

    delegate = delegate?delegate:self;
    _request = [[RORequest getRequestWithParams:params httpMethod:httpMethod delegate:delegate requestURL:url] retain];
    [_request connect];
    return _request;
}

- (void)requestWithParam:(RORequestParam *)param andDelegate:(id <RORequestDelegate>)delegate {
    if (nil == param.method || [param.method length] <= 0) {
        NSLog(@"API Method must be specified");
        return;
    }

    if (![self isSessionValid]) {
        NSLog(@"Session is not valid! Request abort!!");
        return;
    }

    [self setGeneralRequestArgs:param];

    [self sendRequestWithUrl:kRestserverBaseURL param:param httpMethod:@"POST" delegate:delegate];

    return;
}

#pragma mark - RODialogDelegate Methods -

- (void)authDialog:(RODialog *)dialog withOperateType:(RODialogOperateType )operateType{
    if (dialog != _rrDialog) {
        return;
    }
    NSDictionary* authDictionary = nil;
    ROError* authError = nil;
    switch (operateType) {
        case RODialogOperateSuccess:
            authDictionary = (NSDictionary *)dialog.response.rootObject;
            NSString* token = [authDictionary objectForKey:@"token"];
            NSDate* expirationDate = [authDictionary objectForKey:@"expirationDate"];
            self.accessToken = token;
            self.expirationDate = expirationDate;
            self.secret=[self getSecretKeyByToken:token];
            self.sessionKey=[self getSessionKeyByToken:token];
            //用户信息保存到本地
            [self saveUserSessionInfo];
            [self getLoggedInUserId];
            if ([_renrenDelegate respondsToSelector:@selector(renrenDidLogin:)]) {
                [_renrenDelegate renrenDidLogin:self];
            }
            break;
        case RODialogOperateFailure:
            authError = dialog.response.error;
            if ([_renrenDelegate respondsToSelector:@selector(renren:loginFailWithError:)]) {
                 [_renrenDelegate renren:self loginFailWithError:authError];
            }
            break;
        default:
            if ([_renrenDelegate respondsToSelector:@selector(renrenDialogDidCancel:)]) {
                 [_renrenDelegate renrenDialogDidCancel:self];
            }
            break;
    }

}

- (void)widgetDialog:(RODialog *)dialog withOperateType:(RODialogOperateType )operateType{
    if (dialog != _rrDialog) {
        return;
    }
    switch (operateType) {
        case RODialogOperateSuccess:
            if ([_renrenDelegate respondsToSelector:@selector(renren:requestDidReturnResponse:)]) {
                [_renrenDelegate renren:self requestDidReturnResponse:dialog.response];
            }
            break;
        case RODialogOperateFailure:
            if([_renrenDelegate respondsToSelector:@selector(renren:requestFailWithError:)]){
                [_renrenDelegate renren:self requestFailWithError:dialog.response.error];
            }
            break;
        default:
            if ([_renrenDelegate respondsToSelector:@selector(renrenDialogDidCancel:)]) {
                [_renrenDelegate renrenDialogDidCancel:self];
            }
            break;
    }
}

#pragma mark - Util Methods -
/*
 * 用于设置通用的一些参数到param对象中。
 */
-(void)setGeneralRequestArgs: (RORequestParam *)inRequestParam{
    // 这里假设此前已经调用[self isSessionValid],并且返回Ture。
    inRequestParam.sessionKey = self.sessionKey;
    inRequestParam.apiKey = self.appKey;
    inRequestParam.callID = [ROUtility generateCallId];
    inRequestParam.xn_ss = @"1";
    inRequestParam.format = @"json";
    inRequestParam.apiVersion = kSDKversion;

    inRequestParam.sig = [ROUtility generateSig:[inRequestParam requestParamToDictionary] secretKey:self.secret];
}

/**
 * 用accesstoken 获取调用api 时用到的参数session_secret
 */
-(NSString *)getSecretKeyByToken:(NSString *)token{
	NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
								   token, @"oauth_token",
								   nil];
	NSString *getKeyUrl = [RORequest serializeURL:kRRSessionKeyURL params:params];
    id result = [RORequest getRequestSessionKeyWithParams:getKeyUrl];
	if ([result isKindOfClass:[NSDictionary class]]) {
		NSString* secretkey=[[result objectForKey:@"renren_token"] objectForKey:@"session_secret"];
		return secretkey;
	}
	return nil;
}

/**
 * 用accesstoken 获取调用api 时用到的参数session_key
 */
-(NSString *)getSessionKeyByToken:(NSString *)token{
	NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
								   token, @"oauth_token",
								   nil];
	NSString *getKeyUrl = [RORequest serializeURL:kRRSessionKeyURL params:params];
    id result = [RORequest getRequestSessionKeyWithParams:getKeyUrl];
	if ([result isKindOfClass:[NSDictionary class]]) {
		NSString* sessionkey=[[result objectForKey:@"renren_token"] objectForKey:@"session_key"];
		return sessionkey;
	}
	return nil;
}

#pragma mark - Authorize & Logout -

/*
 * 用户oauth2登录请求认证授权
 */
- (void)authorizationWithPermisson:(NSArray *)permissions andDelegate:(id<RenrenDelegate>)delegate {
    /*NSLog(@"正在通过OAuth 2.0请求认证授权......");
    self.permissions = permissions;
    self.renrenDelegate = delegate;
    if (![self isSessionValid]){
        [self authorizeWithRRAppAuth:YES safariAuth:YES];
    }*/
    NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
	NSArray* graphCookies = [cookies cookiesForURL:
                             [NSURL URLWithString:@"http://graph.renren.com"]];

	for (NSHTTPCookie* cookie in graphCookies) {
		[cookies deleteCookie:cookie];
	}
	NSArray* widgetCookies = [cookies cookiesForURL:[NSURL URLWithString:@"http://widget.renren.com"]];

	for (NSHTTPCookie* cookie in widgetCookies) {
		[cookies deleteCookie:cookie];
	}
    if (![self isSessionValid]) {
        self.renrenDelegate = [delegate retain];
        self.permissions = nil;
        self.permissions = permissions;
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setValue:_appKey forKey:@"client_id"];
        [parameters setValue:kRRSuccessURL forKey:@"redirect_uri"];
        [parameters setValue:@"token" forKey:@"response_type"];
        [parameters setValue:@"touch" forKey:@"display"];
        if (nil != self.permissions) {
            NSString *permissionScope = [self.permissions componentsJoinedByString:@","];
            [parameters setValue:permissionScope forKey:@"scope"];
        }

        [_rrDialog release];
        NSLog(@"正在通过OAuth 2.0请求认证授权......");
        _rrDialog = [[RODialog alloc] initWithURL:kAuthBaseURL params:parameters delegate:self];
        [_rrDialog show];
    }
}

- (void)passwordFlowAuthorizationWithParam:(ROPasswordFlowRequestParam *)param andDelegate:(id<RenrenDelegate>) delegate{
	self.renrenDelegate = delegate;

	param.apiKey = self.appKey;

	if (![self isSessionValid]){
		[self sendRequestWithUrl:kPasswordFlowBaseURL param:param httpMethod:@"POST" delegate:self];
	}
}

/**
 * 退出用户登录
 *
 * @param delegate
 *
 */

- (void)logout:(id<RenrenDelegate>)delegate {
    self.renrenDelegate = delegate;
    NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
    [params release];
    [_accessToken release];
    _accessToken = nil;
    [_expirationDate release];
    _expirationDate = nil;
    [_secret release];
    _secret=nil;
    [_sessionKey release];
    _sessionKey=nil;
    [self delUserSessionInfo];
    if ([self.renrenDelegate respondsToSelector:@selector(renrenDidLogout:)]) {
        [self.renrenDelegate renrenDidLogout:self];
    }
}

#pragma mark - Customlized API Request Methods -

- (RORequest *)requestWithParams:(NSMutableDictionary *)params andDelegate:(id <RenrenDelegate>)delegate{
    if (nil == [params objectForKey:@"method"]) {
        NSLog(@"API Method must be specified");
        return nil;
    }
	if ([self isSessionValid]) {
		[params setObject:self.sessionKey forKey:@"session_key"];
    }else {
		NSLog(@"Session is not valid! Request abort!!");
		return nil;
	}

	[params setObject:[ROUtility generateCallId] forKey:@"call_id"];//增加键与值
	[params setObject:_appKey forKey:@"api_key"];
	[params setObject:kSDKversion forKey:@"v"];
	[params setObject:@"json" forKey:@"format"];
	[params setObject:@"1" forKey:@"xn_ss"];

	NSString *sig = [ROUtility generateSig:params secretKey:self.secret];
	[params setObject:sig forKey:@"sig"];

    self.renrenDelegate = [delegate retain];

    return [self openUrl:kRestserverBaseURL params:params httpMethod:@"POST" delegate:self];
}

- (void)dialog:(NSString *)action andParams:(NSMutableDictionary *)params andDelegate:(id<RenrenDelegate>)delegate{
	NSString *dialogURL = [kDialogBaseURL stringByAppendingString:action];
	[params setObject:_appId forKey:@"app_id"];
	[params setObject:@"touch" forKey:@"display"];

	if ([params objectForKey:@"redirect_uri"] == nil) {
		[params setObject:kRRSuccessURL forKey:@"redirect_uri"];
    }

	if ([self isSessionValid]) {
        [params setValue:[self.accessToken stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"access_token"];
    }

	_renrenDelegate = delegate;
	[_rrDialog release];
	_rrDialog = [[RODialog alloc] initWithURL:dialogURL params:params delegate:self];
	[_rrDialog show];
}

#pragma mark - RORequestDelegate -

/**
 * Handle the auth.ExpireSession api call failure
 */
- (void)request:(RORequest *)request didFailWithError:(NSError*)error{
    NSLog(@"Failed to expire the session");
}

- (void)request:(RORequest *)request didFailWithROError:(ROError *)error{

	//password flow授权错误的处理
	if([request.requestParamObject isKindOfClass:[ROPasswordFlowRequestParam class]])
	{
		if ([self.renrenDelegate respondsToSelector:@selector(renren:loginFailWithError:)]) {
			[self.renrenDelegate renren:self loginFailWithError:error];
		}else{
			// 默认错误处理。
			NSString *title = [NSString stringWithFormat:@"Error code:%d", [error code]];
			NSString *description = [NSString stringWithFormat:@"%@", [error localizedDescription]];
			UIAlertView *alertView =[[[UIAlertView alloc] initWithTitle:title message:description delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil] autorelease];
			[alertView show];
		}
		return;
	}

	if (self.renrenDelegate && [self.renrenDelegate respondsToSelector:@selector(renren:requestFailWithError:)]) {
        [self.renrenDelegate renren:self requestFailWithError:error];
    }else{
        // 默认错误处理。
        NSString *title = [NSString stringWithFormat:@"Error code:%d", [error code]];
        NSString *description = [NSString stringWithFormat:@"%@", [error localizedDescription]];
        UIAlertView *alertView =[[[UIAlertView alloc] initWithTitle:title message:description delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil] autorelease];
        [alertView show];
    }

    return;
}

- (void)request:(RORequest *)request didLoad:(id)result{

	//password flow授权请求的处理
	if([request.requestParamObject isKindOfClass:[ROPasswordFlowRequestParam class]])
	{
		NSString *token = [request.responseObject.rootObject objectForKey:@"access_token"];
		NSString *date = [request.responseObject.rootObject objectForKey:@"expires_in"];

		self.accessToken = [request.responseObject.rootObject objectForKey:@"access_token"];;
		self.expirationDate = [ROUtility getDateFromString:date];
		self.secret=[self getSecretKeyByToken:token];
		self.sessionKey=[self getSessionKeyByToken:token];
		//用户信息保存到本地
		[self saveUserSessionInfo];
        [self getLoggedInUserId];
		if ([self.renrenDelegate respondsToSelector:@selector(renrenDidLogin:)]) {
			[self.renrenDelegate renrenDidLogin:self];
		}
		return;
	}
    if ([request.requestParamObject.method isEqualToString:@"users.getLoggedInUser"]) {
        NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
        NSNumber *uid = [(NSDictionary*)result objectForKey:@"uid"];
        if (uid) {
            [defaults setObject:[uid stringValue] forKey:@"session_UserId"];
            [defaults synchronize];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kNotificationDidGetLoggedInUserId" object:nil];
        }

        return;
    }
    if(self.renrenDelegate && [self.renrenDelegate respondsToSelector:@selector(renren:requestDidReturnResponse:)]){
        [self.renrenDelegate renren:self requestDidReturnResponse:request.responseObject];
    }else{
        // 默认请求成功时的处理。

    }

    return;
}

#pragma mark - Packaged API Function Methods -

-(void)createAlbum:(ROCreateAlbumRequestParam *)param andDelegate:(id<RenrenDelegate>)delegate{
	if (![param.method isEqualToString:@"photos.createAlbum"]) {
		NSLog(@"API Method Error!");
		return;
    }

	self.renrenDelegate = delegate;

	[self requestWithParam:param andDelegate:self];

    return;
}

-(void)getAlbums:(ROAlbumsInfoRequestParam *)param andDelegate:(id<RenrenDelegate>)delegate{
	if (![param.method isEqualToString:@"photos.getAlbums"]) {
		NSLog(@"API Method Error!");
		return;
    }

	self.renrenDelegate = delegate;

	[self requestWithParam:param andDelegate:self];

    return;
}

-(void)getUsersInfo:(ROUserInfoRequestParam *)param andDelegate:(id<RenrenDelegate>)delegate{
	if (![param.method isEqualToString:@"users.getInfo"]) {
		NSLog(@"API Method Error!");
		return;
    }

	self.renrenDelegate = delegate;

	[self requestWithParam:param andDelegate:self];

    return;
}

-(void)publishPhoto:(ROPublishPhotoRequestParam *)param andDelegate:(id<RenrenDelegate>)delegate{
    if (![param.method isEqualToString:@"photos.upload"]) {
		NSLog(@"API Method Error!");
		return;
    }

	self.renrenDelegate = delegate;

	[self requestWithParam:param andDelegate:self];

    return;
}

-(void)getFriends:(ROGetFriendsRequestParam *)param andDelegate:(id<RenrenDelegate>)delegate
{
	if (![param.method isEqualToString:@"friends.get"]) {
		NSLog(@"API Method Error!");
		return;
    }

	self.renrenDelegate = delegate;

	[self requestWithParam:param andDelegate:self];
}

-(void)getFriendsInfo:(ROGetFriendsInfoRequestParam *)param andDelegate:(id<RenrenDelegate>)delegate
{
	if (![param.method isEqualToString:@"friends.getFriends"]) {
		NSLog(@"API Method Error!");
		return;
    }

	if (![self isSessionValid]) {
		//[self delUserSessionInfo];
		NSLog(@"Session not valid!! Request abort!");
		return;
	}

	self.renrenDelegate = delegate;

	[self requestWithParam:param andDelegate:self];
}

#pragma mark - One-Click API Function Methods -
/**
 *一键发布照片流程方法
 *@param image 准备上传图片对象
 *@param caption 上传图片的附加文本,会成为照片的描述
 */
-(void)publishPhotoSimplyWithImage:(UIImage *)image caption:(NSString *)caption
{

    ROPublishPhotoDialogModel *dialogModel = [ROPublishPhotoDialogModel modelWithRenren:self];
    dialogModel.photo = image;
    dialogModel.caption = caption;
    RODialogView *dialogView = [RODialogView dialogViewWithModel:dialogModel];
    //判断用户是否已通过授权认证
    if (![self isSessionValid]) {
        [dialogView waitForRenrenAuthorize];
        NSArray *permissions = [NSArray arrayWithObjects:@"photo_upload",nil];
        [self authorizationWithPermisson:permissions andDelegate:dialogModel];
    }else {
        [dialogView show:YES];
    }
}

#pragma mark - discarded Methods should removed in near future -

/**
 * A private function for opening the authorization dialog.
 * User-Agent Flow
 */
- (void)authorizeWithRRAppAuth:(BOOL)tryRRAppAuth safariAuth:(BOOL)trySafariAuth {
    NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   _appKey, @"client_id",
                                   @"token", @"response_type",
                                   kRRSuccessURL, @"redirect_uri",
                                   @"touch", @"display",
                                   nil];
    if (_permissions != nil){
        NSString* scope = [_permissions componentsJoinedByString:@","];
        [params setValue:scope forKey:@"scope"];
    }

	[_rrDialog release];
	_rrDialog = [[RODialog alloc] initWithURL:kAuthBaseURL params:params delegate:self];
	[_rrDialog show];

}

@end


text:
<?php

namespace Cola\Api\Json;

use Cola\Json;
use Cola\Api\Response as ApiResponse;

/**
 * Response
 *
 * @version 1.0.0
 * @since version 3.0.0
 * @author dazarobbo <dazarobbo@live.com>
 */
class Response extends ApiResponse {

	/**
	 * Formats the current object to a JSON-formatted string
	 * IMPORTANT! This will serialise all public properties
	 * @return string
	 */
	public function toJsonString(){
		return Json::serialise($this);
	}

	/**
	 * Formats the current object to a JSONP formatted string
	 * @param string $functionName Name of the Javascript function to be appended
	 * @return string
	 */
	public function toJsonPString($functionName = 'Response'){
		return \sprintf('%s(%s);', $functionName, $this->toJsonString());
	}

	/**
	 * Invokes the toJsonString method and returns the result
	 * @return string
	 */
	public function __toString() {
		return $this->toJsonString();
	}

}


text:
<?php

namespace Oro\Bundle\FilterBundle\Form\Type\Filter;

interface NumberFilterTypeInterface
{
    const TYPE_GREATER_EQUAL = 1;
    const TYPE_GREATER_THAN  = 2;
    const TYPE_EQUAL         = 3;
    const TYPE_NOT_EQUAL     = 4;
    const TYPE_LESS_EQUAL    = 5;
    const TYPE_LESS_THAN     = 6;

    const DATA_INTEGER = 'data_integer';
    const DATA_DECIMAL = 'data_decimal';
    const PERCENT      = 'percent';
}


text:
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Verno.Filters
{
    public class DeleteFileAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.OnCompleted(() => Task.Run(() =>
            {
                var filePathResult = filterContext.Result as PhysicalFileResult;
                if (filePathResult != null)
                {
                    File.Delete(filePathResult.FileName);
                }
            }));
        }
    }
}


text:
Munich is small.

## Navigation

Subway system is split into two parts: S Bahn and U Bahn, just
like in [Frankfurt](frankfurt.md). Family ticket for 24 hours
would cost about €23 and allows up to 5 persons, each child
counting as 1/2 person. Subway is modern, safe and easy to
navigate.

City center (subway station Marienplatz) is old and nice, but
crowded during light hours. Areas just a mile away are way more
scenic and quiet.

To the south of Munich, there are lakes. Locals love them.
Totally worth visiting.

## B&B

Next to the airport, there's a couple of hotels, B&B Hotel and
Novotel among others. These two are most reliable. At B&B hotel,
breakfast is light, no protein except chicken eggs, and almost no
fat except butter.


text:
package com.syncano.library.callbacks;

import com.syncano.library.api.Response;
import com.syncano.library.api.ResponseGetList;

import java.util.List;

public abstract class SyncanoListCallback<T> implements SyncanoCallback<List<T>> {
    @Override
    public void success(Response<List<T>> response, List<T> result) {
        success((ResponseGetList<T>) response, result);
    }

    @Override
    public void failure(Response<List<T>> response) {
        failure((ResponseGetList<T>) response);
    }

    public abstract void success(ResponseGetList<T> response, List<T> result);

    public abstract void failure(ResponseGetList<T> response);
}


text:
using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal static partial class OpenSsl
    {
        private static Version s_opensslVersion;

        [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SSLEayVersion")]
        private static extern string OpenSslVersionDescription();

        internal static Version OpenSslVersion
        {
            get
            {
                if (s_opensslVersion == null)
                {
                    const string OpenSSL = "OpenSSL ";

                    // Skip OpenSSL part, and get the version string of format x.y.z
                    if (!Version.TryParse(OpenSslVersionDescription().AsReadOnlySpan().Slice(OpenSSL.Length, 5), out s_opensslVersion))
                    {
                        s_opensslVersion = new Version(0, 0, 0);
                    }
                }

                return s_opensslVersion;
            }
        }
    }
}


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

public class SchoolClass
{
    public SchoolClass(List<Course> courses = null)
    {
        this.Courses = new List<Course>();
    }

    public List<Course> Courses { get; set; }

    public void AddCourse(Course course)
    {
        this.Courses.Add(course);
    }

    public void RemoveCourse(Course course)
    {
        bool courseFound = false;
        for (int i = 0; i < this.Courses.Count; i++)
        {
            if (this.Courses[i].Name == course.Name)
            {
                courseFound = true;
                this.Courses.Remove(course);
            }
        }

        if (!courseFound)
        {
            throw new ArgumentException("There is not any course with this name.");
        }
    }
}


text:
<?php
namespace Ttree\JobButler\Domain\Model;

use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Utility\Arrays;

/**
 * Job Configuration Options
 */
class JobConfigurationOptions
{
    /**
     * @var array
     */
    protected $options;

    /**
     * JobConfigurationOptions constructor.
     * @param array $options
     */
    public function __construct(array $options)
    {
        $this->options = $options;
    }

    /**
     * @param string $path
     * @return mixed
     */
    public function getValueByPath($path)
    {
        return Arrays::getValueByPath($this->options, $path);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('time_based', '0028_auto_20201112_1509'),
    ]

    operations = [
        migrations.RenameField(
            model_name='onadateapplication',
            old_name='contribution_ptr',
            new_name='contributor_ptr',
        ),
        migrations.RenameField(
            model_name='periodapplication',
            old_name='contribution_ptr',
            new_name='contributor_ptr',
        ),
    ]


text:
package com.marcos.trabajo_grado;

import android.os.Bundle;
import org.apache.cordova.*;

public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
    }
}


text:
<?php
header( 'Location: ../index.php/Admin/inicio' );
?>


text:
@interface Repository : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *repo_description;
@property (nonatomic, strong) NSURL *url;
@property (nonatomic, strong) NSString *language;
@property (nonatomic, strong) NSNumber *watchersCount;

@end


text:
<!--

    Copyright © 2016-2017 The Thingsboard Authors

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<md-select ng-show="vm.displayStateSelection()" aria-label="{{ 'dashboard.state' | translate }}" ng-model="vm.stateObject[0].id">
    <md-option ng-repeat="(stateId, state) in vm.states" ng-value="stateId">
        {{vm.getStateName(stateId, state)}}
    </md-option>
</md-select>


text:
@interface YCShareController : UIViewController

@end


text:
using Restaurant.Domain.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Restaurant.Application.ViewModels
{
    public class OrderViewModel
    {
        public OrderViewModel()
        {
            this.Id = Guid.NewGuid();
        }

        [Key]
        public Guid Id { get; set; }

        [DisplayName("Home Processing:")]
        [DataType(DataType.Date)]
        public DateTime HomeProcessing { get; set; }

        [DisplayName("End Processing:")]
        [DataType(DataType.Date)]
        public DateTime EndProcessing { get; set; }

        [Required]
        [DisplayName("Table:")]
        public Guid TableServiceId { get; set; }
        public virtual TableServiceViewModel TableService { get; set; }

        [Required]
        [DisplayName("Dish:")]
        public Guid DishId { get; set; }
        public virtual DishViewModel Dish { get; set; }

        [Required]
        [DisplayName("Option:")]
        public Guid OptionId { get; set; }
        public virtual OptionViewModel Option { get; set; }
    }
}


text:
var app = app || {}

$(function (){

	var storage = null
	var jqCanvas = $('#canvas')
	var viewport = $(window)
	var jqBody = $('body')
	var lineNumbers = $('#linenumbers')
	var lineMarker = $('#linemarker')
	var storageStatusElement = $('#storage-status')
	var tooltip = $('#tooltip')[0]
	var errorTooltip = $('#error-tooltip')[0]
	var textarea = document.getElementById('textarea')
	var imgLink = document.getElementById('savebutton')
	var fileLink = document.getElementById('saveTextbutton')
	var linkLink = document.getElementById('linkbutton')
	var canvasElement = document.getElementById('canvas')
	var canvasPanner = document.getElementById('canvas-panner')
	var canvasTools = document.getElementById('canvas-tools')
	var defaultSource = document.getElementById('defaultGraph').innerHTML
	var fileName;
	var zoomLevel = 0
	var offset = {x:0, y:0}
	var mouseDownPoint = false
	var vm = skanaar.vector

	var editor = CodeMirror.fromTextArea(textarea, {
		lineNumbers: true,
		mode: 'vag',
		matchBrackets: true,
		autoCloseBrackets: true,
		theme: 'solarized dark',
		keyMap: 'sublime',
		extraKeys: {
			"Ctrl-Space": "autocomplete"
	   }
	});

	$(document).bind('keydown', function(e) {
		if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
			e.preventDefault()
			fileLink.click()
			return false
		}
	});

	var editorElement = editor.getWrapperElement()

	window.addEventListener('hashchange', reloadStorage);
	window.addEventListener('resize', _.throttle(sourceChanged, 750, {leading: true}))
	editor.on('changes', _.debounce(sourceChanged, 300))
	canvasPanner.addEventListener('mouseenter', classToggler(jqBody, 'canvas-mode', true))
	canvasPanner.addEventListener('mouseleave', classToggler(jqBody, 'canvas-mode', false))
	canvasTools.addEventListener('mouseenter', classToggler(jqBody, 'canvas-mode', true))
	canvasTools.addEventListener('mouseleave', classToggler(jqBody, 'canvas-mode', false))
	canvasPanner.addEventListener('mousedown', mouseDown)
	window.addEventListener('mousemove', _.throttle(mouseMove,50))
	canvasPanner.addEventListener('mouseup', mouseUp)
	canvasPanner.addEventListener('mouseleave', mouseUp)
	canvasPanner.addEventListener('wheel', _.throttle(magnify, 50))
	initImageDownloadLink(imgLink, canvasElement)
	initFileDownloadLink(fileLink)
	initToolbarTooltips()
	initDialog('.upload-dialog')
	reloadStorage()

	function initDialog(className) {

		$(className).magnificPopup({
			type: 'inline',
			fixedContentPos: false,
			fixedBgPos: true,
			overflowY: 'auto',
			closeBtnInside: true,
			preloader: false,
			removalDelay: 300,
			mainClass: 'my-mfp-slide-bottom'
		});
	}
	function classToggler(element, className, state){
		var jqElement = $(element)
		return _.bind(jqElement.toggleClass, jqElement, className, state)
	}

	function mouseDown(e){
		$(canvasPanner).css({width: '100%'})
		mouseDownPoint = vm.diff({ x: e.pageX, y: e.pageY }, offset)
	}

	function mouseMove(e){
		if (mouseDownPoint){
			offset = vm.diff({ x: e.pageX, y: e.pageY }, mouseDownPoint)
			sourceChanged()
		}
	}

	function mouseUp(){
		mouseDownPoint = false
		$(canvasPanner).css({width: '45%'})
	}

	function magnify(e){
		zoomLevel = Math.min(10, zoomLevel - (e.deltaY < 0 ? -1 : 1))
		sourceChanged()
	}

	app.magnifyViewport = function (diff){
		zoomLevel = Math.min(10, zoomLevel + diff)
		sourceChanged()
	}

	app.resetViewport = function (){
		zoomLevel = 0
		offset = {x: 0, y: 0}
		sourceChanged()
	}

	app.toggleSidebar = function (id){
		var sidebars = ['reference', 'about']
		_.each(sidebars, function (key){
			if (id !== key) $(document.getElementById(key)).toggleClass('visible', false)
		})
		$(document.getElementById(id)).toggleClass('visible')
	}

	app.confirmDiscardCurrentGraph = function (){
		$.magnificPopup.open({
			items: {
				src: '#discard-dialog'
			},
			type: 'inline',
			fixedContentPos: false,
			fixedBgPos: true,
			overflowY: 'auto',
			closeBtnInside: true,
			preloader: false,
			removalDelay: 300,
			mainClass: 'my-mfp-slide-bottom'
		});
	}
	app.dismissDialog = function (){
		$.magnificPopup.close();
	}

	app.discardCurrentGraph = function (){
		app.dismissDialog()
		setCurrentText(defaultSource)
		sourceChanged()
	}

	app.saveViewModeToStorage = function (){
		var question =
		'Do you want to overwrite the diagram in ' +
		'localStorage with the currently viewed diagram?'
		if (confirm(question)){
			storage.moveToLocalStorage()
			window.location = './'
		}
	}

	app.exitViewMode = function (){
		window.location = './'
	}

	app.importJDL = function() {
		app.dismissDialog()
		//Retrieve the first (and only!) File from the FileList object
		var f = document.getElementById('jdlFileInput').files[0]

		if(!f) {
			alert("Failed to load file")
		} else if (!f.type.match('text.*') && !f.name.endsWith('.vag') && !f.name.endsWith('.vg')) {
			alert(f.name + " is not a valid VAG or text file.")
		} else {
			var r = new FileReader()
			r.onload = function(e) {
				var contents = e.target.result;
				console.log( "Got the file\n"
					+"name: " + f.name + "\n"
					+"type: " + f.type + "\n"
					+"size: " + f.size + " bytes\n"
					+ "starts with: " + contents.substr(0, contents.indexOf("\n"))
				)
				setCurrentText(contents)
			}
			r.readAsText(f)
		}
		ga('send', 'event', 'VAG File', 'upload', 'VAG File upload');
		ga('jdlTracker.send', 'event', 'VAG File', 'upload', 'VAG File upload');
	}

	// Adapted from http://meyerweb.com/eric/tools/dencoder/
	function urlEncode(unencoded) {
		return encodeURIComponent(unencoded).replace(/'/g,'%27').replace(/"/g,'%22')
	}

	function urlDecode(encoded) {
		return decodeURIComponent(encoded.replace(/\+/g, ' '))
	}

	function setShareableLink(str){
		var base = '#view/'
		linkLink.href = base + urlEncode(str)
	}

	function buildStorage(locationHash){
		var key = 'vagstudio.lastSource'
		if (locationHash.substring(0,6) === '#view/')
		return {
			read: function (){ return urlDecode(locationHash.substring(6)) },
			save: function (){ setShareableLink(currentText()) },
			moveToLocalStorage: function (){ localStorage[key] = currentText() },
			isReadonly: true
		}
		return {
			read: function (){ return localStorage[key] || defaultSource },
			save: function (source){
				setShareableLink(currentText())
				localStorage[key] = source
			},
			moveToLocalStorage: function (){},
			isReadonly: false
		}
	}

	function initImageDownloadLink(link, canvasElement){
		link.addEventListener('click', downloadImage, false);
		function downloadImage(){
			var url = canvasElement.toDataURL('image/png')
			link.href = url;
			ga('send', 'event', 'VAG Image', 'download', 'VAG Image download');
			ga('jdlTracker.send', 'event', 'VAG Image', 'download', 'VAG Image download');
		}
	}

	function initFileDownloadLink(link){
		link.addEventListener('click', downloadFile, false);
		function downloadFile(){
			var textToWrite = currentText()
			var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'})
			var URL = window.URL || window.webkitURL
			if (URL != null) {
				link.href = window.URL.createObjectURL(textFileAsBlob)
			}
			ga('send', 'event', 'VAG File', 'download', 'VAG File download');
			ga('jdlTracker.send', 'event', 'VAG File', 'download', 'VAG File download');
		}
	}

	function initToolbarTooltips(){
		$('.tools a').each(function (i, link){
			link.onmouseover = function (){ tooltip.textContent  = $(link).attr('title') }
			link.onmouseout = function (){ tooltip.textContent  = '' }
		})
	}

	function positionCanvas(rect, superSampling, offset){
		var w = rect.width / superSampling
		var h = (rect.height / superSampling) - 60
		jqCanvas.css({
			top: (300 * (1 - h/viewport.height()) + offset.y) + 50,
			left: 150 + (viewport.width() - w)/2 + offset.x,
			width: w,
			height: h
		})
	}

	function setFilename(filename){
		fileLink.download = filename + '.vag'
		imgLink.download = filename + '.png'
	}

	function reloadStorage(){
		storage = buildStorage(location.hash)
		editor.setValue(storage.read())
		sourceChanged()
		if (storage.isReadonly) storageStatusElement.show()
		else storageStatusElement.hide()
	}

	function currentText(){
		return editor.getValue()
	}

	function setCurrentText(value){
		return editor.setValue(value)
	}

	function handleError(e){
		lineNumbers.toggleClass('error', true)
		if (e.location){
			var lineHeight = parseFloat($(editorElement).css('line-height'))
			lineMarker.css('top', 35 + lineHeight*e.location.start.line)
			errorTooltip.textContent = e.message + ' -> line: ' + e.location.start.line
		} else {
			throw e
		}
	}

	function sourceChanged(){
		try {
			lineMarker.css('top', -35)
			lineNumbers.toggleClass('error', false)
			errorTooltip.textContent = ''
			var superSampling = window.devicePixelRatio || 1
			var scale = superSampling * Math.exp(zoomLevel/10)

			var model = nomnoml.draw(canvasElement, currentText(), scale)
			positionCanvas(canvasElement, superSampling, offset)
			setFilename(model.config.title)
			storage.save(currentText())
		} catch (e){
			handleError(e)
		}
	}
})


text:
[cmdletbinding()]
param(
    [parameter(mandatory = $true)]
    [string]$domain,
    [parameter(mandatory = $true)]
    [string]$username,
    [parameter(mandatory = $true)]
    [string]$password,

    [parameter(mandatory = $true)]
    [string]$collection,
    [parameter(mandatory = $true)]
    [string]$iteration,
    [parameter(mandatory = $true)]
    [int]$nServers,

    [parameter(mandatory = $true)]
    [int]$nTimeoutMinutes,

    [Parameter(ValueFromRemainingArguments = $true)]
    $extraParameters
    )

    $title = "System Maintenance"
    $message = "Please save your work. You will be logged off in $nTimeoutInMinutes minute(s)."

    function log
    {
        param([string]$message)

        "`n`n$(get-date -f o)  $message"
    }

    function add-server
    {
        param(
            [parameter(mandatory=$true)]
            [string]$server
            )

            $cs = gwmi win32_computersystem;  $broker = "$($cs.dnshostname).$($cs.domain)"

            log "adding server $server to the deployment..."
            add-rdserver $server -role rds-rd-server -ev e

            if ($e -like '*deployment*not present*')
            {
                log "trying to create rds deployment..."
                new-rdsessiondeployment -connectionbroker $broker -sessionhost $_ -ev e

                if ($e -like "*$server*has reboots pending*")
                {
                    log "attempting to reboot $server..."
                    restart-computer $server -force -wait

                    log "attempting to create deployment with $server one more time..."
                    new-rdsessiondeployment -connectionbroker $broker -sessionhost $_ -ea stop
                }

                elseif ($e)
                {
                    throw
                }

                log "create deployment - success."
            }

            elseif ($e -like "*$server*has reboots pending*")
            {
                log "attempting to reboot $server..."
                restart-computer $server -force -wait

                log "attempting to add $server to deployment again after reboot..."
                add-rdserver $server -role rds-rd-server -ea stop
            }

            elseif ($e)
            {
                throw
            }

            log "successfully added '$server' to the deployment."
    }

    log "script running..."

	whoami

  # $PSBoundParameters

    if ($extraParameters)
    {
        log "any extra parameters:"
        $extraParameters
    }

	log "attempting impersonate as $domain\$username..."
	.\New-ImpersonateUser.ps1 -Username $username -Domain $domain -Password $password

	try
	{

		ipmo remotedesktop -DisableNameChecking    # 4>$null

	  # $domain = (gwmi win32_computersystem).Domain

		$newServers = 0..$($nServers - 1) | % { "rdsh-$_$iteration.$domain" }
		log "list of new servers:"
		$newServers | % { "    $($_.tolower())" }

		#  1. add new servers to the deployment
		#
		log "current list of servers in the rds deployment:"
		$existingServers = (get-rdserver).Server
		$existingServers |  % { "    $($_.tolower())" }

		$newServers | ? { -not ($_ -in $existingServers) } | % { add-server $_ }

		#  2. add new  servers to the rdsh collection
		#
		log "current list of rdsh servers in collection '$($collection)':"
		$existingServers = (get-rdsessionhost -CollectionName $collection).SessionHost
		if ($existingServers)
		{
			$existingServers | % { "    $($_.tolower())" }
		}
		else
		{
			"    --- no servers in the collection yet ----"
		}

		$serversToAdd = $newServers | ? { -not ($_ -in $existingServers) }

		if ($serversToAdd)
		{
			log "adding new servers $($serversToAdd -join '; ') to session host collection '$collection'..."
			add-rdsessionhost -collectionname $collection -sessionhost $serversToAdd -ea stop
		}

		#  3. put old servers in drain mode
		#
		$serversToRemove = $existingServers | ? { -not ($_ -in $newServers) }

		if ($serversToRemove)
		{
			$serversToRemove  | % `
			{
				log "putting server $_ in drain mode..."
				set-rdsessionhost -sessionhost $_ -newconnectionallowed No
			}
		}

		#  4. notify users they are going to be logged off in next <n> minutes
		#
		log "querying for user sessions in collection '$collection'..."
		$sessions =	get-rdusersession -CollectionName $collection
		log "found total $($sessions.count) user sessions,"

		$sessionsToLogoff = $sessions | ? { -not( $_.HostServer -in $newServers ) }
		log "out of those $($sessionsToLogoff.count) sessions on the servers that are to be removed..."

		if ($sessionsToLogoff)
		{
			$sessionsToLogoff| % `
			{
				log "sending message to user $($_.UserName) at host $($_.HostServer)..."
				send-rdusermessage -hostserver $_.HostServer -unifiedsessionid $_.UnifiedSessionId -messagetitle $title -messagebody $message
			}
		}

		#  5. log users off
		#
		if ($sessionsToLogoff)
		{
			log "waiting $nTimeoutMinutes munites before logging users off..."
			start-sleep -s ($nTimeoutMinutes * 60)

			log "querying for user sessions again..."
			$sessions =	get-rdusersession -CollectionName $collection
			log "found total $($sessions.count) user sessions at this time,"

			$sessionsToLogoff = $sessions | ? { -not( $_.HostServer -in $newServers ) }
			log "out of those, $($sessionsToLogoff.count) sessions to be logged off..."
			if ($sessionsToLogoff)
			{
				$sessionsToLogoff | % `
				{
					log "logging off user $($_.UserName) from host $($_.HostServer)..."
					invoke-rduserlogoff -hostserver $_.HostServer -unifiedsessionid $_.SessionId -force
				}
			}
		}

		#  6. remove old servers from deployment
		#
		if ($serversToRemove)
		{
			log "removing servers $($serversToRemove -join '; ') from session host collection '$collection'..."
			remove-rdsessionhost -sessionhost $serversToRemove -force

			$serversToRemove  | % `
			{
				log "removing server $_ from the deployment..."
				remove-rdserver $_ -role rds-rd-server -force
			}

			log "shutting down servers $($serversToRemove -join '; ')..."
			$creds = new-object System.Management.Automation.PSCredential ("$domain\$username", (convertto-securestring $password -asplaintext -force))
			stop-computer -computer $serversToRemove -credential $creds -force
		}
		else
		{
			log "nothing to do."
		}

	}
    catch
    {
        log "ERROR: caught exception"
        throw
    }
	finally
	{
		log "remove impersonation..."
		Remove-ImpersonateUser
	}

    log "done. success."


text:
class CleanupUsersLdapEmailRename < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  disable_ddl_transaction!

  def up
    cleanup_concurrent_column_rename :users, :ldap_email, :external_email
  end

  def down
    rename_column_concurrently :users, :external_email, :ldap_email
  end
end


text:
<?php

declare(strict_types=1);

namespace UliCMS\Security;

use Settings;

class Encryption
{

    // use this to encrypt user passwords
    public static function hashPassword(string $password): string
    {
        $salt = Settings::get("password_salt");

        // if no salt is set, generate it
        if (!$salt) {
            $newSalt = uniqid();
            Settings::set("password_salt", $newSalt);
            $salt = $newSalt;
        }
        return hash("sha512", $salt . $password);
    }
}


text:
import logging
from blox.modules.module import module
from blox.exceptions import *
from xml.dom.minidom import parseString
logger = logging.getLogger( 'blox' )

class xmlparse(module):
  def output(self, input, params):
    logger.debug('processing xml')
    if not input:
      raise ParseException( 'Invalid input' )
    xml = parseString( input )
    if not xml:
      raise ParseException( 'Invalid xml' )
    return xml


text:
var composer = require('./index'),
    prompt = require('prompt'),
    spawn = require('child_process').spawn,
    fs = require('fs'),
    url = require('url'),
    d = require('simply-deferred');

var cleanse = function(val) {
    return val;
};

module.exports = function(pax, args, opts) {
    var deferred = d.Deferred();

    var checkArgs = function() {
        var deferred = d.Deferred();
        if (args.length > 0) {
            deferred.resolve();
        } else {
            deferred.reject(new Error('No package to add'));
        }
        return deferred.promise();
    };

    var checkComposer = function() {
        var deferred = d.Deferred();

        if (!composer.manifest) {
            var schema = {
                properties: {
                    name: {
                        name: 'Name',
                        default: process.env['USER'] + '/' + pax.pkg.manifest.name,
                        required: true
                    },
                    description: {
                        name: 'Description',
                        default: pax.pkg.manifest.description,
                        required: true
                    },
                    version: {
                        name: 'Version',
                        default: pax.pkg.manifest.version,
                        required: true
                    }
                }
            };

            prompt.message = 'composer';
            prompt.colors = false;
            prompt.start();
            prompt.get(schema, function(err, json) {
                if (!err) {
                    json.autoload = {
                        "psr-0": {
                            "App": "src/"
                        }
                    };

                    fs.writeFileSync('./composer.json', JSON.stringify(json, null, 2));
                    composer.init();

                    deferred.resolve();
                } else {
                    deferred.reject(err);
                }
            });
        } else {
            deferred.resolve();
        }

        return deferred.promise();
    };

    var add = function() {

        var deferred = d.Deferred();

        var arg0 = args[0];
        var parsedURL = url.parse(arg0),
            pkg, name, version, repository;

        if (parsedURL.protocol) {
            //vcs
            if (parsedURL.protocol == 'git+ssh:') {
                repository = arg0.substr(10);
            } else {
                repository = arg0;
            }

            name = parsedURL.path.trim();
            if (name.match(/\/\.git$/)) {
                name = name.substr(0, name.length - 5);
            } else if (name.match(/\.git$/)) {
                name = name.substr(0, name.length - 4);
            }
            name = name.split(/[\/:]+/);
            name = name.splice(-2).join('/');

            // FIXME it shouldnt be always dev-master
            version = version || 'dev-master';
        } else {
            pkg = arg0.split('@');
            name = cleanse(pkg[0]);
            version = cleanse(pkg[1]);
        }

        if (name && version) {
            if (composer.manifest && composer.manifest.require && composer.manifest.require[name]) {
                deferred.reject(new Error('Package "' + name + '" conflict or already exist.'));
            } else {

                if (opts.dev) {
                    pax.log.out('Adding composer dev package ' + name + '@' + version + ' ...');
                } else {
                    pax.log.out('Adding composer package ' + name + '@' + version + ' ...');
                }

                if (repository) {
                    pax.log.out('From ' + repository + '...');

                    if (opts.dev) {
                        composer.manifest['require-dev'] = composer.manifest['require-dev'] || {};
                        composer.manifest['require-dev'][name] = version;
                    } else {
                        composer.manifest.require = composer.manifest.require || {};
                        composer.manifest.require[name] = version;
                    }

                    composer.manifest.repositories = composer.manifest.repositories || [];
                    composer.manifest.repositories.push({
                        type: 'vcs',
                        url: repository
                    });

                    fs.writeFileSync('./composer.json', JSON.stringify(composer.manifest, null, 2));
                    composer.init();

                    var c = spawn('composer', ['update'], {stdio:'inherit'});
                    c.on('close', function(code) {
                        deferred.resolve();
                    });
                } else {
                    var cOptions;
                    if (opts.dev) {
                        cOptions = ['require', '--dev', name + ':' + version];
                    } else {
                        cOptions = ['require', name + ':' + version];
                    }
                    var cRequire = spawn('composer', cOptions, {stdio:'inherit'});
                    cRequire.on('close', function(code) {
                        composer.init();
                        deferred.resolve();
                    });

                }

            }

        } else {
            deferred.reject(new Error('Parsing error.'));
        }

        return deferred.promise();
    };

    d.when(checkArgs())
        .then(checkComposer)
        .then(add)
        .then(deferred.resolve, deferred.reject);

    return deferred.promise();
};


text:
[![Build Status](https://secure.travis-ci.org/iVantage/angular-ivh-elide-filter.png?branch=master)](https://travis-ci.org/iVantage/angular-ivh-elide-filter)

> Smart cropping for text in AngularJS apps.

## Installation

Install with bower:

```
bower install --save angular-ivh-elide-filter
```

## Usage

Add this module as a dependency to your app:

```
angular.module('myApp', ['ivh.elideFilter']);
```

Use it in your views:

```
{{'super super super long text' | ivhElide}}
```

Inject it for profit:

```javascript
inject(function(ivhElideFilter) {
  var longText = 'super super super long text'
    , shorText = ivhElideFilter(longText);
});
```

### Filter Signature

#### `ivhElideFilter(str[, lim=25][, hard=false])`

Returns a version of `str` limited to `lim` characters, if the `str` is elided
three dots will be appended to it: `...`. By default, this filter will look for
a convenient word break *near* `lim` characters to break on if possible. If you
prefer a hard break pass `true` as the last parameter.

## Testing

Use `npm test` to run the full suite of linting, style checks, and unit tests.

Or, run each individually:

- Use `grunt jshint` for linting
- Use `grunt jscs` for coding style checks
- Use `grunt jasmine` to unit tests

For ease of development the `grunt watch` task will run each of the above as
needed when you make changes to source files.

## Changelog

- 2015-06-16 v0.0.1 Initial release

## License

MIT


text:
module Juli
  module Macro
    class Base
      include Juli::Util

      # called on 'juli init' to generate config sample template.
      def self.conf_template
        ''
      end

      # called when juli(1) starts.
      def initialize
      end

      # called on setting up conf to set default key=val
      def set_conf_default(conf)
      end

      # called on each parsed document
      def on_root(file, root, visitor = nil)
      end

      # called on each macro as "\{macro_name args...}" in text.
      # String should be returned.
      def run(*args)
        ''
      end

      # called at final on each parsed document
      def after_root(file, root)
      end

    end

    Dir.glob(File.join(File.dirname(__FILE__), 'macro/*.rb')){|m|
      require File.join('juli/macro', File.basename(m))
    }
  end
end


text:
class VARSHARED_EXPORT VarLib
{

public:
    VarLib(void);
};

#endif // VAR_H


text:
package com.facebook.buck.apple.xcode;

import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeTrue;

import com.facebook.buck.apple.AppleNativeIntegrationTestUtils;
import com.facebook.buck.apple.toolchain.ApplePlatform;
import com.facebook.buck.testutil.integration.BuckBuildLog;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TemporaryPaths;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.environment.Platform;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class ProjectIntegrationTest {

  @Rule public ExpectedException thrown = ExpectedException.none();

  @Rule public TemporaryPaths temporaryFolder = new TemporaryPaths();

  @Before
  public void setUp() {
    assumeTrue(Platform.detect() == Platform.MACOS || Platform.detect() == Platform.LINUX);
  }

  @Test
  public void testBuckProjectGeneratedSchemeOnlyIncludesDependenciesWithoutTests()
      throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_generated_scheme_only_includes_dependencies", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("project", "--without-tests", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testBuckProjectGeneratedSchemeIncludesTestsAndDependencies() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_generated_scheme_includes_tests_and_dependencies", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testBuckProjectGeneratedSchemeIncludesTestsAndDependenciesInADifferentBuckFile()
      throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this,
            "project_generated_scheme_includes_tests_and_dependencies_in_a_different_buck_file",
            temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testBuckProjectGeneratedSchemesDoNotIncludeOtherTests() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_generated_schemes_do_not_include_other_tests", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void generatingAllWorkspacesWillNotIncludeAllProjectsInEachOfThem() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this,
            "generating_all_workspaces_will_not_include_all_projects_in_each_of_them",
            temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void schemeWithActionConfigNames() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "scheme_with_action_config_names", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void schemeWithExtraTests() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "scheme_with_extra_tests", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void schemeWithExtraTestsWithoutSrcTarget() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "scheme_with_extra_tests_without_src_target", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void generatingCombinedProject() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "generating_combined_project", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand(
            "project", "--combined-project", "--without-tests", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void generatingRootDirectoryProject() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "generating_root_directory_project", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project", "//:bundle");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void generatingCombinedProjectWithTests() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "generating_combined_project_with_tests", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("project", "--combined-project", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testGeneratesWorkspaceFromBundle() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_implicit_workspace_generation", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project", "//bin:app");
    result.assertSuccess();
    Files.exists(workspace.resolve("bin/app.xcworkspace/contents.xcworkspacedata"));
    Files.exists(workspace.resolve("bin/bin.xcodeproj/project.pbxproj"));
  }

  @Test
  public void testGeneratesWorkspaceFromLibrary() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_implicit_workspace_generation", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project", "//lib:lib");
    result.assertSuccess();
    Files.exists(workspace.resolve("lib/lib.xcworkspace/contents.xcworkspacedata"));
    Files.exists(workspace.resolve("lib/lib.xcodeproj/project.pbxproj"));
  }

  @Test
  public void testGeneratesWorkspaceFromBinary() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_implicit_workspace_generation", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project", "//bin:bin");
    result.assertSuccess();
    Files.exists(workspace.resolve("bin/bin.xcworkspace/contents.xcworkspacedata"));
    Files.exists(workspace.resolve("bin/bin.xcodeproj/project.pbxproj"));
  }

  @Test
  public void testAttemptingToGenerateWorkspaceFromResourceTargetIsABuildError()
      throws IOException {
    thrown.expect(HumanReadableException.class);
    thrown.expectMessage(
        "//res:res must be a xcode_workspace_config, apple_binary, apple_bundle, or apple_library");

    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_implicit_workspace_generation", temporaryFolder);
    workspace.setUp();

    workspace.runBuckCommand("project", "//res:res");
  }

  @Test
  public void testGeneratingProjectWithTargetUsingGenruleSourceBuildsGenrule() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "target_using_genrule_source", temporaryFolder);
    workspace.setUp();

    workspace.runBuckCommand("project", "//lib:lib");

    BuckBuildLog buildLog = workspace.getBuildLog();
    buildLog.assertTargetBuiltLocally("//lib:gen");
    buildLog.assertTargetBuiltLocally("other_cell//:gen");
  }

  @Test
  public void testGeneratingProjectWithGenruleResourceBuildsGenrule() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "target_using_genrule_resource", temporaryFolder);
    workspace.setUp();

    workspace.runBuckCommand("project", "//app:TestApp");

    BuckBuildLog buildLog = workspace.getBuildLog();
    buildLog.assertTargetBuiltLocally("//app:GenResource");
  }

  @Test
  public void testBuckProjectBuckConfigWithoutTestsGenerate() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_buckconfig_without_tests_generate", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("project", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testBuckProjectBuckConfigWithoutTestsGenerateWithTests() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_buckconfig_without_tests_generate_with_tests", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("project", "--with-tests", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testBuckProjectFocus() throws IOException {
    assumeTrue(Platform.detect() == Platform.MACOS);
    assumeTrue(
        AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.IPHONESIMULATOR));
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "project_focus", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand(
            "project",
            "--focus",
            "//Libraries/Dep1:Dep1_1#iphonesimulator-x86_64 //Libraries/Dep2:Dep2",
            "//Apps:TestApp#iphonesimulator-x86_64");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testBuckProjectFocusPattern() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_focus_pattern", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("project", "--focus", "//Libraries/Dep1:", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testBuckProjectFocusPatternCell() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_focus_pattern_cell", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("project", "--focus", "bar//Dep2:", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testBuckProjectFocusWithTests() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_focus_with_tests", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand(
            "project",
            "--config",
            "project.ide=xcode",
            "--with-tests",
            "--focus",
            "//Tests:",
            "//Apps:TestApp");
    result.assertSuccess();
  }

  @Test
  public void testGeneratingProjectMetadataWithGenrule() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "target_using_genrule_source", temporaryFolder);
    workspace.setUp();

    workspace.runBuckCommand("project", "//lib:lib");
    workspace.verify();
  }

  @Test
  public void testBuckProjectWithUniqueLibraryNames() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "project_with_unique_library_names", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand(
            "project", "-c", "cxx.unique_library_name_enabled=true", "//Apps:workspace");
    result.assertSuccess();

    workspace.verify();
  }

  @Test
  public void testBuckProjectShowsFullOutput() throws Exception {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "target_using_genrule_source", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("project", "--show-full-output", "//lib:lib");
    workspace.verify();

    assertEquals(
        "//lib:lib#default,static "
            + workspace.getDestPath().resolve("lib").resolve("lib.xcworkspace")
            + System.lineSeparator(),
        result.getStdout());
  }

  @Test
  public void testBuckProjectShowsOutput() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "target_using_genrule_source", temporaryFolder);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("project", "--show-output", "//lib:lib");
    workspace.verify();

    assertEquals(
        "//lib:lib#default,static " + Paths.get("lib", "lib.xcworkspace") + System.lineSeparator(),
        result.getStdout());
  }
}


text:
layout          : blocks/page-participant
title           : Robert Grace
type            : participant
role            : Summit Content Manager
job-title       : Summit Content Manager
company         : OWASP
expenses        : owasp
funded          : yes
funded-who      : Summit Budget
flight-cost     : 250
ticket-cost     : 1500
funded-amount   : 1500
required-funds  : 1500
travel-from     : Germany
image           : https://media.licdn.com/mpr/mpr/shrinknp_400_400/AAEAAQAAAAAAAAknAAAAJGRjYjM4YTAwLWI0OTAtNDg3Ny1iMGMxLWQwOTZmNTNlNzRkYg.jpg
linkedin        : r-grace
twitter          : robertgracesa1
facebook        :
website         :
email           : robert.grace.sa@gmail.com
project-leader  :
chapter-leader  :
ticket          : 5x24h
regonline       : No
status          : add details
pre-summit      : Sat,Sun
working-sessions:
# add above a comma delimited list of the Working Sessions you would like to attend (use the session's title)
---

<!-- put more details about participant here -->


text:
<!DOCTYPE html>
<html>
<head>
<script>
function performTest(api)
{
    var node = document.body;
    api.DOM.deleteAllChildren(node);
    api.Selection.set(node,0,node,0);
    var properties = api.Formatting.getFormatting();
    delete properties["-corinthia-shift"];
    api.Selection.clearSelection();

    var lines = new Array();
    var names = Object.getOwnPropertyNames(properties).sort();
    for (var i = 0; i < names.length; i++)
        lines.push(names[i]+" = "+properties[names[i]]+"\n");
    return lines.join("");
}
</script>
</head>
<body>
</body>
</html>


text:
title:  "personal blog site sample post"
date:   2014-12-10 10:18:00
description: to do
---

how to use markdown language
2. how to insert images in posts
3. implement tag system
4. change from disqus to formspree


text:
package ru.shestakov.start;

import java.util.*;

/**
 * Init ConsoleInput class
 */
public class ConsoleInput implements Input, InputRange {
    private Scanner scanner = new Scanner(System.in);

    /**
     * Reads input user`s value
     * @param question
     * @return
     */
    public String ask(String question) {
        System.out.print(question);
        return scanner.nextLine();
    }

    /**
     * Reads input user`s value
     * @param question
     * @return
     */
    public long ask(String question, boolean check) {
        System.out.print(question);
        return Long.parseLong(scanner.nextLine());
    }

    /**
     * Validate value with exception
     * @param question
     * @param range
     * @return
     */
    public int ask(String question, int[] range) {
        int key = Integer.valueOf(this.ask(question));
        boolean exist = false;
        for(int value : range) {
            if(value == key) {
                exist = true;
                break;
            }
        }
        if (exist) { return key; } else { throw new MenuOutException("Out of menu range."); }
    }

}


text:
const { Command } = require('discord.js-commando')
const logger = new (require('../util/logger'))()

module.exports = class BaseCmd extends Command {
  log (info) {
    return logger.log(info)
  }

  warn (warning) {
    return logger.warn(warning)
  }

  error (err) {
    return logger.error(err)
  }

  getUsernames (userIds) {
    let usernames = []
    userIds.forEach(id => usernames.push(this.client.users.get(id).username))
    return usernames
  }

  getMentionedUsernames (msg) {
    let usernames = []

    msg.mentions.users.forEach(user => usernames.push(user.username))

    return `**${usernames.join('**, **')}**`
  }

  /**
   * Cleans each argument within the array by converting it to lowercase and
   * trimming any whitespace then adding it to a new array of the cleaned values
   * to be returned.
   *
   * @param {string[]} args
   *
   * @returns {string[]}
   */
  cleanArgs (args) {
    let newArgs = []
    args.forEach(val => newArgs.push(val.trim().toLowerCase()))
    return newArgs
  }
}


text:
Trabalho elaborado para o curso de Redes de Computadores I.

Seen here: http://www.gta.ufrj.br/ensino/eel878/redes1-2015-1/15_1/ccn/


text:
import logging
import sys

def get_caller_logger():
    import sys
    module = None
    mod_name = sys._getframe(2).f_globals['__name__']
    return logging.getLogger(mod_name)

def setup_root_logger(log_name):
    L = logging.getLogger(log_name)
    L.setLevel(logging.DEBUG)
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        # "[%(asctime)s:%(levelname)8s:%(name)35s] %(message)s",
        # "[%(asctime)s:%(levelname)s:%(name)s]\n    %(message)s",
        "[%(relativeCreated)d:%(levelname)s:%(name)s]\n    %(message)s",
        datefmt='%j:%H:%M:%S'
    )
    ch.setFormatter(formatter)
    L.addHandler(ch)
    return L


text:
package org.coc.tools;

import org.coc.tools.shared.misc.StringUtil;

public class TestStaff {

	public static void main(String[] args) {
		/**
		 * e.g. cutFolatString("123.45678",2) => "123.45"
		 * e.g. cutFolatString("123.45",3) => "123.45"
		 * e.g. cutFolatString("123.456.78",2) => "123.456.78"
		 * e.g. cutFolatString("123.45.678",2) => "123.45.67"
		 * @param floatString
		 * @param maxCharAfterDot
		 * @return
		 */

		String test="";
		int maxCharAfterDot=0;
		String result="";

		test="123.45678";
		maxCharAfterDot=2;
		result=StringUtil.cutDotString(test, maxCharAfterDot);
		System.out.println("test StringUtil.cutDotString:"+test+",maxCharAfterDot="+maxCharAfterDot+",result=" +result);

		test="123.45";
		maxCharAfterDot=3;
		result=StringUtil.cutDotString(test, maxCharAfterDot);
		System.out.println("test StringUtil.cutDotString:"+test+",maxCharAfterDot="+maxCharAfterDot+",result=" +result);

		test="123.456.78";
		maxCharAfterDot=2;
		result=StringUtil.cutDotString(test, maxCharAfterDot);
		System.out.println("test StringUtil.cutDotString:"+test+",maxCharAfterDot="+maxCharAfterDot+",result=" +result);

		test="123.45.678";
		maxCharAfterDot=2;
		result=StringUtil.cutDotString(test, maxCharAfterDot);
		System.out.println("test StringUtil.cutDotString:"+test+",maxCharAfterDot="+maxCharAfterDot+",result=" +result);

	}

}


text:
require 'active_support/concern'

module ActiveAssets
  module ActiveSprites
    module Configurable
      extend ActiveSupport::Concern

      included do
        config_accessor :sprite_backend
      end
    end
  end
end


text:
<?php

require_once('../config.php');

require_once(PATH_SDK_ROOT . 'Core/ServiceContext.php');
require_once(PATH_SDK_ROOT . 'DataService/DataService.php');
require_once(PATH_SDK_ROOT . 'PlatformService/PlatformService.php');
require_once(PATH_SDK_ROOT . 'Utility/Configuration/ConfigurationManager.php');

//Specify QBO or QBD
$serviceType = IntuitServicesType::QBO;

// Get App Config
$realmId = ConfigurationManager::AppSettings('RealmID');
if (!$realmId)
    exit("Please add realm to App.Config before running this sample.\n");

// Prep Service Context
$requestValidator = new OAuthRequestValidator(ConfigurationManager::AppSettings('AccessToken'),
    ConfigurationManager::AppSettings('AccessTokenSecret'),
    ConfigurationManager::AppSettings('ConsumerKey'),
    ConfigurationManager::AppSettings('ConsumerSecret'));
$serviceContext = new ServiceContext($realmId, $serviceType, $requestValidator);
if (!$serviceContext)
    exit("Problem while initializing ServiceContext.\n");

// Prep Data Services
$dataService = new DataService($serviceContext);
if (!$dataService)
    exit("Problem while initializing DataService.\n");

// Run a query
$entities = $dataService->Query("SELECT * FROM TaxRate");

// Echo some formatted output
if (count($entities) > 0) {
    $i = 0;
    foreach ($entities as $oneTaxRate) {
        echo "TaxRate[$i] Name: {$oneTaxRate->Name}	Rate {$oneTaxRate->RateValue} AgencyRef {$oneTaxRate->AgencyRef} (SpecialTaxType {$oneTaxRate->SpecialTaxType})\n";
        $i++;
    }
}

/*
Example output:

TaxRate[0] Name: NOTAXP	Rate 0 AgencyRef 1 (SpecialTaxType NO_TAX)
TaxRate[1] Name: NOTAXS	Rate 0 AgencyRef 1 (SpecialTaxType NO_TAX)
TaxRate[2] Name: Purchase EC 2%	Rate 2 AgencyRef 3 (SpecialTaxType NONE)
TaxRate[3] Name: Purchase HEC 1%	Rate 1 AgencyRef 3 (SpecialTaxType NONE)
*/

?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
BuildDb
</TITLE>

<META NAME="keywords" CONTENT="BuildDb class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Class BuildDb

java.lang.Object
  se.gu.ling.trindikit.oaa.common.OAASolver
      BuildDb

public class BuildDb
extends se.gu.ling.trindikit.oaa.common.OAASolver

This class builds an IclDb from an *.ics file (vCalendar format)

Constructor Summary

BuildDb()

Method Summary

 boolean
solve(com.sri.oaa2.icl.IclTerm goal,
      com.sri.oaa2.icl.IclList params,
      com.sri.oaa2.icl.IclList answers)

Methods inherited from class se.gu.ling.trindikit.oaa.common.OAASolver

getSolvable, getSolvableString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BuildDb

public BuildDb()

Method Detail

solve

public boolean solve(com.sri.oaa2.icl.IclTerm goal,
                     com.sri.oaa2.icl.IclList params,
                     com.sri.oaa2.icl.IclList answers)

Specified by:
solve in class se.gu.ling.trindikit.oaa.common.OAASolver

      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
import { Credential } from '@openid/openyolo';

export type Identity = Account &
  {
    isAuthenticated: boolean,
    email: string,
    roles: string[]
  };

export type OAuthIdentity = Identity &
  {
    accessToken: string,
    clientId: string,
  };

export type OpenIDConnectIdentity = OAuthIdentity &
  {
    idToken: string,
  };

export type OpenYoloIdentity = Credential;


text:
from schematizer.exceptions import SimpleValidationError

class BaseSchema:
    def to_native(self, obj):
        raise NotImplementedError

    def to_primitive(self, obj):
        raise NotImplementedError

class BaseCoercibleSchema(BaseSchema):
    def coerce_primitive(self, obj):
        raise NotImplementedError

    def coerce_native(self, obj):
        raise NotImplementedError

    def to_native(self, obj):
        try:
            return self.coerce_primitive(obj)
        except (TypeError, ValueError, ArithmeticError) as exc:
            raise SimpleValidationError('INVALID', extra={'message': str(exc)}) from exc

    def to_primitive(self, obj):
        return self.coerce_native(obj)


text:
Changes in **fasta-36.3.8d** released 13-April-2016:

1. Various bug fixes to `pssm_asn_subs.c` that avoid coredumps when
   reading NCBI PSSM ASN.1 binary files.  `pssm_asn_subs.c` can now read
   IUPACAA sequences.

2. default gap penalties for VT40 (from -14/-2 to -13/-1), VT80 (from
   -14/-2 to -11/-1), and VT120 (from -10/-1 to 11/-1) have changed
   slightly.

3. Introduction of `scripts/m9B_btop_msa.pl` and
   `scripts/m8_btop_msa.pl`, which uses the BTOP (`-m 9B` or `-m 8CB`)
   encoded alignment strings to produce a query driving multiple
   sequence alignment (MSA) in ClustalW format.  This MSA can be used
   as input to `psiblast` to produce an ASN.1 PSSM.

4. The `scripts/annot_blast_btop2.pl` script replaces
   `scripts/annot_blast_btop.pl` and allows annotation of both the query
   and subject sequences.

5. Various domain annotation scripts have been renamed for clarity.
   For example, `ann_feats_up_sql.pl` uses an SQL implementation of
   Uniprot features tables to annotate domains.  Likewise,
   `ann_pfam_www.pl` gets domain information from the Pfam web site,
   while `ann_pfam27.pl` gets the information from the downloaded
   Pfam27 mySQL tables, and `ann_pfam28.pl` uses the Pfam28 mySQL
   tables.

6. percent identity in sub-alignment scores is calculated like a BLAST
   percent identity -- gaps are not included in the denominator.

For more detailed information, see `doc/readme.v36`.


text:
title: Uploading data to Ambiata
version: 1.0
---

You can use the `ambiata-daemon upload` command to transfer data securely to
Ambiata via an upload to Amazon S3.

# Requirements

## Required variables

 - `UPLOAD_DIR`. This is the directory which will contain the files
   to be uploaded. It must be an absolute path (starts with a `/`).
   It is recommended that it is owned by same the user that
   `ambiata-daemon upload` process will run as. The process will require
   read, write and execute permission for the directory.

## Optional variables

The default values for these variables should serve most users, but
they can be set if required.

 - `ARCHIVE_RETENTION` (default: 7). This is the number of days to wait before
   deleting files which have been successfully uploaded. Setting this
   to "0" will cause uploaded files to never be deleted.

### NTLM authentication

NTLM is not currently supported directly. The upload command can be
configured to use an NTLM-authenticating proxy via an NTLM middleware
proxy such as [Cntlm](http://cntlm.sourceforge.net/).

# Uploading data

Once the upload process is configured and running, the final step is
to add some files to the directory specified in `UPLOAD_DIR`. The
process will only upload regular files in `UPLOAD_DIR`; it won't
upload directories or symbolic links.

The process will monitor `UPLOAD_DIR` for new files, but it won't
start uploading them until they have been present in the directory for
at least 2 minutes without changing; this is to avoid uploading
partial files.


text:
/** @module objects/nav */
/* globals $ */
'use strict';

$(function() {
	$('.site-header__menu').each(function() {
		var menu = $(this),
			content = menu.find('.site-header__menu__content'),
			toggle = menu.find('.site-header__menu__toggle'),
			body = $(document.body),
			scrollTop = 0,
			isOpen,
			close = function() {
				menu.removeClass('menu--state-open');
				body.removeClass('body--menu-open');
				if (isOpen) {
					body.scrollTop(scrollTop);
				}
				isOpen = false;
			};

		// Close on clicks outside menu
		$(document).on('click', close);

		// Avoid close on clicks within menu
		menu.on('click', function (event) {
			event.stopPropagation();
		});

		// Toggle on burger click
		toggle.on('click', function (event) {
			event.preventDefault();

			isOpen = menu.hasClass('menu--state-open');

			if (!isOpen) {
				scrollTop = body.scrollTop();
				menu.addClass('menu--state-open');

				window.setTimeout(function() {
					body.addClass('body--menu-open');
				}, 400);
			} else {
				close();
			}
		});

	});

});