text:
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Links.UrlBuilders;
using Sitecore.Resources.Media;
using Sitecore.Web.UI.WebControls;
using System.Web;

namespace Constellation.Foundation.ModelMapping.FieldModels
{
	/// <summary>
	/// When used as a ViewModel property, allows for the retrieval of File field values on the View based
	/// on the needs of that specific view.
	/// </summary>
	public class FileModel
	{
		private readonly string _requestCacheKey;
		private readonly string _languageName;
		private readonly string _databaseName;
		private readonly ID _mediaID;

		internal FileModel(FileField field)
		{
			// record facts to reconstitute MediaItem as necessary
			_languageName = field.InnerField.Item.Language.Name;
			_databaseName = field.InnerField.Item.Database.Name;
			_mediaID = field.MediaItem?.ID;

			_requestCacheKey = GetRequestCacheKeyValue(field.InnerField);
			// park the MediaItem in the Request cache
			MediaItem = field.MediaItem;

			// populate the stock attributes
			this.Rendered = new HtmlString(FieldRenderer.Render(field.InnerField.Item, field.InnerField.Name));

			var file = field.MediaItem;
			this.Name = file.Name;
			this.DisplayName = file.DisplayName;

			if (file != null)
			{

				var options = new MediaUrlBuilderOptions()
				{
					Language = file.Language
				};

				var innerUrl = MediaManager.GetMediaUrl(file, options);
				Src = HashingUtils.ProtectAssetUrl(innerUrl);
			}
			else
			{
				Src = string.Empty;
			}
		}

		/// <summary>
		/// The MediaItem's Display Name
		/// </summary>
		public string DisplayName { get; }

		/// <summary>
		/// The MediaItem's Name
		/// </summary>
		public string Name { get; }

		/// <summary>
		/// The Url of the file using the current media context.
		/// </summary>
		public string Src { get; }

		/// <summary>
		/// The Url of the file using the current media context.
		/// </summary>
		public string Url
		{
			get
			{
				return Src;
			}
		}

		/// <summary>
		/// The result of calling FieldRenderer.Render() on the File Field.
		/// </summary>
		public HtmlString Rendered { get; }

		/// <summary>
		/// The MediaItem that is the Value of the Field that was mapped to this Object.
		/// </summary>
		protected MediaItem MediaItem
		{
			get
			{
				if (HttpContext.Current != null)
				{
					return (MediaItem)HttpContext.Current.Items[_requestCacheKey];
				}

				var database = Sitecore.Configuration.Factory.GetDatabase(_databaseName);
				var language = Sitecore.Globalization.Language.Parse(_languageName);

				return database.GetItem(_mediaID, language);
			}
			private set
			{
				if (HttpContext.Current != null && !HttpContext.Current.Items.Contains(_requestCacheKey))
				{
					HttpContext.Current.Items.Add(_requestCacheKey, value);
				}
			}
		}

		private static string GetRequestCacheKeyValue(Field field)
		{
			return $"fileUrlBuilder{field.Item.ID.ToShortID()}{field.ID.ToShortID()}";
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<Product xmlns="http://code.google.com/p/open-zwave/">

<!-- Polycontrol: Danalock Keypad -->

	<!-- COMMAND_CLASS_BASIC does not respond to requests -->
	<CommandClass id="32" setasreport="true"/>

	<!-- COMMAND_CLASS_DOOR_LOCK does not respond to requests -->
	<CommandClass id="98" getsupported="false"/>

	<!-- COMMAND_CLASS_ALARM does not respond to requests -->
	<CommandClass id="113" getsupported="false"/>

	<!-- COMMAND_CLASS_POWERLEVEL does not respond to requests -->
	<CommandClass id="115" action="remove"/>

	<!-- COMMAND_CLASS_ASSOCIATION. This class is in the list reported, but it does not respond to requests -->
	<CommandClass id="133">
		<Associations num_groups="1">
			<Group index="1" max_associations="1" label="Group 1" write_only="true"/>
		</Associations>
	</CommandClass>

</Product>

redpajama_set_name: RedPajamaGithub


text:
Distinguish intentional scroll and inertia scroll

Highly inspired by https://github.com/d4nyll/lethargy

My thanks to d4nyll. And sorry for copy some code.

This package is aiming at creating precise analysis of intentional scroll and inertia scroll.
Lethargy is a light weight npm package to help distinguishing between scroll events intiated by the user and those by inertia. It adopted a finited cache of scroll delta to determine the current state. In the information theory's term, it's a FIR filter which would cut the noise(inertia) and emphasize the signal(intentional). However, the FIR lethargy implemented is not a high pass filter, led to the result strong inertial scrolling will be recoginized as intentional. And that is what I want to solve in this package.


text:
package algo.leetcode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class WordBreakII {

    ArrayList<String> output;
    StringBuilder sb;
    public ArrayList<String> wordBreak(String s, Set<String> dict) {
        output = new ArrayList<String>();
        sb = new StringBuilder();
        if (s.length() == 0 || dict.size() == 0) {
            return output;
        }
        // to speed up, check if each character is in the dict
        boolean found = false;
        for (int i = 0; i < s.length(); i++) {
            for (String dictWord : dict) {
                if (dictWord.indexOf(s.charAt(i)) >= 0) {
                    found = true;
                    break;
                }
                found = false;
            }
            if (!found) return output;
        }

        findWords(s, dict);
        return output;
    }
    public void findWords(String s, Set<String> dict) {
        // base case: return when string is ""
        if (s.length() == 0) {
            output.add(sb.toString());
            return;
        }
        // check substring from 0 to i
        for (int i = 1; i <= s.length(); i++) {
            String toFind = s.substring(0, i);
            if (dict.contains(toFind)) {
                if (sb.length() > 0)
                    sb.append(" ");
                sb.append(toFind);
                findWords(s.substring(i), dict);
                int start = sb.lastIndexOf(toFind);
                if (start > 0) start = start - 1;
                int end = sb.length();
                sb.delete(start, end);
            }
        }
        return;
    }

    public List<String> wordBreak2(String s, List<String> wordDict) {
        List<String> result = new ArrayList<>();
        if(s.length() == 0 || wordDict.size() == 0) return result;
        Set<String> set = new HashSet<>();
        int maxLen = Integer.MIN_VALUE, minLen = Integer.MAX_VALUE;
        for(String str : wordDict){
            set.add(str);
            maxLen = Math.max(maxLen, str.length());
            minLen = Math.min(minLen, str.length());
        }
        wordBreakHelper(result, set, new boolean[s.length()], new StringBuilder(), s, maxLen, minLen, 0);
        return result;
    }

    public boolean wordBreakHelper(List<String> result, Set<String> set, boolean[] dead, StringBuilder sb,
                                   String s, int maxLen, int minLen, int start){
        if(start == s.length()){
            sb.setLength(sb.length() - 1);
            result.add(sb.toString());
            return true;
        }
        if(dead[start]) return false;
        boolean success = false;
        for(int i = start + minLen - 1; i < Math.min(start + maxLen, s.length()); i++){
            String sub = s.substring(start, i + 1);
            if(set.contains(sub)){
                int sbLen = sb.length();
                sb.append(sub).append(' ');
                if(wordBreakHelper(result, set, dead, sb, s, maxLen, minLen, i + 1)) success = true;
                sb.setLength(sbLen);
            }
        }
        dead[start] = !success;
        return success;
    }
}


text:
* Create an **"index.html"** file with title - **"Purple Spiders Agency"**
* Get the latest reset css
* Get the latest typography css
* Get the latest buttons css
* Get the latest forms css
* Create a section with a title "Need a website"
* Create a section with a title "Our Team"
* Create a section with a title "Sign-up to our Newsletter"
* Create a section with a title "Testimonials"
* Create footer
* Make the page responsive per the screenshots attached


text:
package com.sequenceiq.cloudbreak.converter.v4.stacks.cluster.gateway;

import java.util.stream.Collectors;

import javax.inject.Inject;

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.cluster.gateway.GatewayV4Response;
import com.sequenceiq.cloudbreak.converter.v4.stacks.cluster.gateway.topology.GatewayTopologyToGatewayTopologyV4ResponseConverter;
import com.sequenceiq.cloudbreak.view.GatewayView;

@Component
public class GatewayToGatewayV4ResponseConverter {

    @Inject
    private GatewayTopologyToGatewayTopologyV4ResponseConverter gatewayTopologyToGatewayTopologyV4ResponseConverter;

    public GatewayV4Response convert(GatewayView source) {
        GatewayV4Response response = new GatewayV4Response();
        response.setGatewayType(source.getGatewayType());
        response.setPath(source.getPath());
        response.setSsoProvider(source.getSsoProvider());
        response.setGatewaySigningPublicKey(source.getSignPub());
        response.setSsoType(source.getSsoType());
        response.setTokenCert(source.getTokenCert());
        response.setTopologies(source.getTopologies().stream()
                .map(t -> gatewayTopologyToGatewayTopologyV4ResponseConverter.convert(t))
                .collect(Collectors.toList()));
        return response;
    }
}


text:
namespace SleepyDiscord {
	User::User(const json::Value & json) :
		User(json::fromJSON<User>(json)) {
	}

	Connection::Connection(const json::Value & json) :
		Connection(json::fromJSON<Connection>(json)) {
	}
}


text:
#import "ResourceManager.h"
#import "CCBSpriteSheetParser.h"
#import "CCBAnimationParser.h"
#import "CCBGlobals.h"
#import "CocosBuilderAppDelegate.h"
#import "CCBDocument.h"

#pragma mark RMSpriteFrame

@implementation RMSpriteFrame

@synthesize spriteFrameName, spriteSheetFile;

- (void) dealloc
{
    self.spriteFrameName = NULL;
    self.spriteSheetFile = NULL;
    [super dealloc];
}

- (NSImage*) preview
{
    return [CCBSpriteSheetParser imageNamed:spriteFrameName fromSheet:spriteSheetFile];
}

@end

#pragma mark RMAnimation

@implementation RMAnimation

@synthesize animationFile, animationName;

- (void) dealloc
{
    self.animationFile = NULL;
    self.animationName = NULL;
    [super dealloc];
}

@end

#pragma mark RMResource

@implementation RMResource

@synthesize type, modifiedTime, touched, data, filePath;

- (void) loadData
{
    if (type == kCCBResTypeSpriteSheet)
    {
        NSArray* spriteFrameNames = [CCBSpriteSheetParser listFramesInSheet:filePath];
        NSMutableArray* spriteFrames = [NSMutableArray arrayWithCapacity:[spriteFrameNames count]];
        for (NSString* frameName in spriteFrameNames)
        {
            RMSpriteFrame* frame = [[[RMSpriteFrame alloc] init] autorelease];
            frame.spriteFrameName = frameName;
            frame.spriteSheetFile = self.filePath;

            [spriteFrames addObject:frame];
        }
        self.data = spriteFrames;
    }
    else if (type == kCCBResTypeAnimation)
    {
        NSArray* animationNames = [CCBAnimationParser listAnimationsInFile:filePath];
        NSMutableArray* animations = [NSMutableArray arrayWithCapacity:[animationNames count]];
        for (NSString* animationName in animationNames)
        {
            RMAnimation* anim = [[[RMAnimation alloc] init] autorelease];
            anim.animationName = animationName;
            anim.animationFile = self.filePath;

            [animations addObject:anim];
        }
        self.data = animations;
    }
    else if (type == kCCBResTypeDirectory)
    {
        // Ignore changed directories
    }
    else
    {
        self.data = NULL;
    }
}

- (NSImage*) preview
{
    if (type == kCCBResTypeImage)
    {
        NSImage* img = [[[NSImage alloc] initWithContentsOfFile:filePath] autorelease];
        return img;
    }

    return NULL;
}

- (NSComparisonResult) compare:(id) obj
{
    RMResource* res = obj;

    if (res.type < self.type)
    {
        return NSOrderedDescending;
    }
    else if (res.type > self.type)
    {
        return NSOrderedAscending;
    }
    else
    {
        return [[self.filePath lastPathComponent] compare:[res.filePath lastPathComponent] options:NSNumericSearch|NSForcedOrderingSearch|NSCaseInsensitiveSearch];
    }
}

- (void) dealloc
{
    self.data = NULL;
    self.modifiedTime = NULL;
    self.filePath = NULL;
    [super dealloc];
}

@end

#pragma mark RMDirectory

@implementation RMDirectory

@synthesize count, dirPath, resources, images, animations, bmFonts, ttfFonts, ccbFiles;

- (id) init
{
    self = [super init];
    if (!self) return NULL;

    resources = [[NSMutableDictionary alloc] init];
    images = [[NSMutableArray alloc] init];
    animations = [[NSMutableArray alloc] init];
    bmFonts = [[NSMutableArray alloc] init];
    ttfFonts = [[NSMutableArray alloc] init];
    ccbFiles = [[NSMutableArray alloc] init];

    return self;
}

- (NSArray*)resourcesForType:(int)type
{
    if (type == kCCBResTypeImage) return images;
    if (type == kCCBResTypeBMFont) return bmFonts;
    if (type == kCCBResTypeTTF) return ttfFonts;
    if (type == kCCBResTypeAnimation) return animations;
    if (type == kCCBResTypeCCBFile) return ccbFiles;
    return NULL;
}

- (void) dealloc
{
    [resources release];
    [images release];
    [animations release];
    [bmFonts release];
    [ttfFonts release];
    [ccbFiles release];
    self.dirPath = NULL;
    [super dealloc];
}

- (NSComparisonResult) compare:(RMDirectory*)dir
{
    return [dirPath compare:dir.dirPath];
}

@end

#pragma mark ResourceManager

@implementation ResourceManager

@synthesize directories, activeDirectories, systemFontList, tooManyDirectoriesAdded;

+ (ResourceManager*) sharedManager
{
    static ResourceManager* rm = NULL;
    if (!rm) rm = [[ResourceManager alloc] init];
    return rm;
}

- (void) loadFontListTTF
{
    NSMutableDictionary* fontInfo = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"FontListTTF" ofType:@"plist"]];
    systemFontList = [fontInfo objectForKey:@"supportedFonts"];
    [systemFontList retain];
}

- (id) init
{
    self = [super init];
    if (!self) return NULL;

    directories = [[NSMutableDictionary alloc] init];
    activeDirectories = [[NSMutableArray alloc] init];
    pathWatcher = [[SCEvents alloc] init];
    pathWatcher.ignoreEventsFromSubDirs = YES;
    pathWatcher.delegate = self;
    resourceObserver = [[NSMutableArray alloc] init];

    [self loadFontListTTF];

    return self;
}

- (void) dealloc
{
    [pathWatcher release];
    [directories release];
    [activeDirectories release];
    [resourceObserver release];
    [systemFontList release];
    self.activeDirectories = NULL;
    [super dealloc];
}

- (NSArray*) getAddedDirs
{
    NSMutableArray* arr = [NSMutableArray arrayWithCapacity:[directories count]];
    for (NSString* dirPath in directories)
    {
        [arr addObject:dirPath];
    }
    return arr;
}

- (void) updatedWatchedPaths
{
    if (pathWatcher.isWatchingPaths)
    {
        [pathWatcher stopWatchingPaths];
    }
    [pathWatcher startWatchingPaths:[self getAddedDirs]];
}

- (void) notifyResourceObserversResourceListUpdated
{
    for (id observer in resourceObserver)
    {
        if ([observer respondsToSelector:@selector(resourceListUpdated)])
        {
            [observer performSelector:@selector(resourceListUpdated)];
        }
    }
}

- (int) getResourceTypeForFile:(NSString*) file
{
    NSString* ext = [[file pathExtension] lowercaseString];
    NSFileManager* fm = [NSFileManager defaultManager];

    BOOL isDirectory;
    [fm fileExistsAtPath:file isDirectory:&isDirectory];

    if (isDirectory)
    {
        return kCCBResTypeDirectory;
    }
    else if ([[file stringByDeletingPathExtension] hasSuffix:@"-hd"]
             || [[file stringByDeletingPathExtension] hasSuffix:@"@2x"])
    {
        // Ignore -hd files
        return kCCBResTypeNone;
    }
    else if ([ext isEqualToString:@"png"]
        || [ext isEqualToString:@"jpg"]
        || [ext isEqualToString:@"jpeg"])
    {
        return kCCBResTypeImage;
    }
    else if ([ext isEqualToString:@"fnt"])
    {
        return kCCBResTypeBMFont;
    }
    else if ([ext isEqualToString:@"ttf"])
    {
        return kCCBResTypeTTF;
    }
    else if ([ext isEqualToString:@"plist"]
             && [CCBSpriteSheetParser isSpriteSheetFile:file])
    {
        return kCCBResTypeSpriteSheet;
    }
    else if ([ext isEqualToString:@"plist"]
             && [CCBAnimationParser isAnimationFile:file])
    {
        return kCCBResTypeAnimation;
    }
    else if ([ext isEqualToString:@"ccb"])
    {
        return kCCBResTypeCCBFile;
    }

    return kCCBResTypeNone;
}

- (void) clearTouchedForResInDir:(RMDirectory*)dir
{
    NSDictionary* resources = dir.resources;
    for (NSString* file in resources)
    {
        RMResource* res = [resources objectForKey:file];
        res.touched = NO;
    }
}

- (void) updateResourcesForPath:(NSString*) path
{
    NSFileManager* fm = [NSFileManager defaultManager];
    RMDirectory* dir = [directories objectForKey:path];
    NSArray* files = [fm contentsOfDirectoryAtPath:path error:NULL];
    NSMutableDictionary* resources = dir.resources;

    BOOL needsUpdate = NO; // Assets needs to be reloaded in editor
    BOOL resourcesChanged = NO;  // A resource file was modified, added or removed

    [self clearTouchedForResInDir:dir];

    for (NSString* fileShort in files)
    {
        NSString* file = [path stringByAppendingPathComponent:fileShort];

        RMResource* res = [resources objectForKey:file];
        NSDictionary* attr = [fm attributesOfItemAtPath:file error:NULL];
        NSDate* modifiedTime = [attr fileModificationDate];

        if (res)
        {
            if ([res.modifiedTime compare:modifiedTime] == NSOrderedSame)
            {
                // Skip files that are not modified
                res.touched = YES;
                continue;
            }
            else if ([[[CCBGlobals globals] appDelegate].currentDocument.fileName isEqualToString: file])
            {
                // Skip the current document
                res.touched = YES;
                continue;
            }
            else
            {
                // A resource has been modified, we need to reload assets
                res.modifiedTime = modifiedTime;
                res.type = [self getResourceTypeForFile:file];

                // Reload its data
                [res loadData];

                needsUpdate = YES;
                resourcesChanged = YES;
            }
        }
        else
        {
            // This is a new resource, add it!
            res = [[RMResource alloc] init];
            res.modifiedTime = modifiedTime;
            res.type = [self getResourceTypeForFile:file];
            res.filePath = file;

            // Load basic resource data if neccessary
            [res loadData];

            // Check if it is a directory
            if (res.type == kCCBResTypeDirectory)
            {
                [self addDirectory:file];
                res.data = [directories objectForKey:file];
            }

            [resources setObject:res forKey:file];

            if (res.type != kCCBResTypeNone) resourcesChanged = YES;
        }
        res.touched = YES;
    }

    // Check for deleted files
    NSMutableArray* removedFiles = [NSMutableArray array];

    for (NSString* file in resources)
    {
        RMResource* res = [resources objectForKey:file];
        if (!res.touched)
        {
            [removedFiles addObject:file];
            needsUpdate = YES;
            if (res.type != kCCBResTypeNone) resourcesChanged = YES;
        }
    }

    // Remove references to files marked for deletion
    for (NSString* file in removedFiles)
    {
        [resources removeObjectForKey:file];
    }

    // Update arrays for different resources
    if (resChanged)
    {
        [dir.images removeAllObjects];
        [dir.animations removeAllObjects];
        [dir.bmFonts removeAllObjects];
        [dir.ttfFonts removeAllObjects];
        [dir.ccbFiles removeAllObjects];

        for (NSString* file in resources)
        {
            RMResource* res = [resources objectForKey:file];
            if (res.type == kCCBResTypeImage
                || res.type == kCCBResTypeSpriteSheet
                || res.type == kCCBResTypeDirectory)
            {
                [dir.images addObject:res];
            }
            if (res.type == kCCBResTypeAnimation
                || res.type == kCCBResTypeDirectory)
            {
                [dir.animations addObject:res];
            }
            if (res.type == kCCBResTypeBMFont
                || res.type == kCCBResTypeDirectory)
            {
                [dir.bmFonts addObject:res];
            }
            if (res.type == kCCBResTypeTTF
                || res.type == kCCBResTypeDirectory)
            {
                [dir.ttfFonts addObject:res];
            }
            if (res.type == kCCBResTypeCCBFile)
            {
                [dir.ccbFiles addObject:res];
            }
        }

        [dir.images sortUsingSelector:@selector(compare:)];
        [dir.animations sortUsingSelector:@selector(compare:)];
        [dir.bmFonts sortUsingSelector:@selector(compare:)];
        [dir.ttfFonts sortUsingSelector:@selector(compare:)];
        [dir.ccbFiles sortUsingSelector:@selector(compare:)];
    }

    if (resourcesChanged) [self notifyResourceObserversResourceListUpdated];
    if (needsUpdate)
    {
        [[[CCBGlobals globals] appDelegate] reloadResources];
    }
}

- (void) addDirectory:(NSString *)dirPath
{
    NSLog(@"addDirectory: %@",dirPath);

    if ([directories count] > kCCBMaxTrackedDirectories)
    {
        tooManyDirectoriesAdded = YES;
        return;
    }

    // Check if directory is already added (then add to its count)
    RMDirectory* dir = [directories objectForKey:dirPath];
    if (dir)
    {
        dir.count++;
    }
    else
    {
        dir = [[[RMDirectory alloc] init] autorelease];
        dir.count = 1;
        dir.dirPath = dirPath;
        [directories setObject:dir forKey:dirPath];

        [self updatedWatchedPaths];
    }

    [self updateResourcesForPath:dirPath];
}

- (void) removeDirectory:(NSString *)dirPath
{
    RMDirectory* dir = [directories objectForKey:dirPath];
    if (dir)
    {
        // Remove sub directories
        NSDictionary* resources = dir.resources;
        for (NSString* file in resources)
        {
            RMResource* res = [resources objectForKey:file];
            if (res.type == kCCBResTypeDirectory)
            {
                [self removeDirectory:file];
            }
        }

        dir.count--;
        if (!dir.count)
        {
            [directories removeObjectForKey:dirPath];
            [self updatedWatchedPaths];
        }
    }
}

- (void) setActiveDirectories:(NSArray *)ad
{
    [activeDirectories removeAllObjects];

    for (NSString* dirPath in ad)
    {
        RMDirectory* dir = [directories objectForKey:dirPath];
        if (dir)
        {
            [activeDirectories addObject:dir];
        }
    }

    [self notifyResourceObserversResourceListUpdated];
}

- (void) setActiveDirectory:(NSString *)dir
{
    [self setActiveDirectories:[NSArray arrayWithObject:dir]];
}

- (void) addResourceObserver:(id)observer
{
    [resourceObserver addObject:observer];
}

- (void) removeResourceObserver:(id)observer
{
    [resourceObserver removeObject:observer];
}

- (void)pathWatcher:(SCEvents *)pathWatcher eventOccurred:(SCEvent *)event
{
    [[[CCDirector sharedDirector] view] lockOpenGLContext];
    [self updateResourcesForPath:event.eventPath];
    [[[CCDirector sharedDirector] view] unlockOpenGLContext];
}

- (NSString*) mainActiveDirectoryPath
{
    if ([activeDirectories count] == 0) return NULL;
    RMDirectory* dir = [activeDirectories objectAtIndex:0];
    return dir.dirPath;
}

- (NSString*) toAbsolutePath:(NSString*)path
{
    if ([activeDirectories count] == 0) return NULL;
    NSFileManager* fm = [NSFileManager defaultManager];

    for (RMDirectory* dir in activeDirectories)
    {
        NSString* p = [NSString stringWithFormat:@"%@/%@",dir.dirPath,path];
        if ([fm fileExistsAtPath:p]) return p;
    }
    return NULL;
}

- (void) debugPrintDirectories
{
    NSLog(@"directories: %@", directories);
    NSLog(@"activeDirectories: %@", activeDirectories);
}

@end


text:
FROM kalilinux/kali-linux-docker:latest

MAINTAINER Jason Chaffee <jason.chaffee+docker@gmail.com>

ENV DEBIAN_FRONTEND noninteractive
ENV TERM xterm-256color

RUN apt-get update -y && apt-get clean all
RUN apt-get install -y software-properties-common && apt-get update -y && apt-get clean all
RUN apt-get install -y git colordiff colortail unzip vim tmux xterm zsh curl && apt-get clean all
RUN apt-get install -y kali-linux-all && apt-get clean all

RUN git clone https://github.com/jasonchaffee/dotfiles.git /.dotfiles

RUN /.dotfiles/config install

RUN chsh -s $(which zsh)
RUN rm -f ${HOME}/.profile
RUN su -s /bin/zsh -c '. ~/.zshrc' root

CMD ["/bin/zsh"]


text:
package com.github.ldaniels528.trifecta

import java.util.Random
import java.util.concurrent.atomic.AtomicInteger

import com.github.ldaniels528.trifecta.JobManager._
import com.github.ldaniels528.trifecta.io.AsyncIO

import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}

/**
 * Background Job/Task Manager
 * @author lawrence.daniels@gmail.com
 */
class JobManager() {
  private val jobIdGen = new AtomicInteger(new Random().nextInt(1000) + 100)
  private val jobs = mutable.Map[Int, JobItem]()

  /**
   * Removes all jobs
   */
  def clear(): Unit = jobs.clear()

  /**
   * Creates a new asynchronous job
   * @param asyncIO the asynchronous I/O job
   * @param command the command that resulted in an asynchronous task
   * @return a new job
   */
  def createJob(asyncIO: AsyncIO, command: String)(implicit ec: ExecutionContext): JobItem = {
    registerJob(AsyncIOJob(jobId = nextJobID, asyncIO, command))
  }

  /**
   * Creates a new asynchronous job
   * @param startTime the start time of the job
   * @param task the asynchronous task
   * @param command the command that resulted in an asynchronous task
   * @return a new job
   */
  def createJob(startTime: Long, task: Future[_], command: String)(implicit ec: ExecutionContext): JobItem = {
    registerJob(AsyncJob(jobId = nextJobID, startTime, task, command))
  }

  /**
   * Retrieves a job by ID
   * @param jobId the given job ID
   * @return the option of a job
   */
  def getJobById(jobId: Int): Option[JobItem] = jobs.get(jobId)

  /**
   * Retrieves a job's task by ID
   * @param jobId the given job ID
   * @return the option of a job
   */
  def getJobTaskById(jobId: Int): Option[Future[_]] = jobs.get(jobId) map (_.task)

  /**
   * Retrieves the complete collection of jobs
   * @return the collection of jobs
   */
  def getJobs: Seq[JobItem] = jobs.values.toSeq

  /**
   * Kills a job by ID
   * @param jobId the given job ID
   */
  def killJobById(jobId: Int): Unit = {
    jobs -= jobId
    ()
  }

  /**
   * Returns the next unique job ID
   * @return the next job ID
   */
  private def nextJobID: Int = jobIdGen.incrementAndGet()

  /**
   * Registers a job for processing
   * @param job the given [[JobItem]]
   * @return the registered job
   */
  private def registerJob(job: JobItem)(implicit ec: ExecutionContext): JobItem = {
    // trigger the update for the end time
    job.task.onComplete {
      case Success(v) => job.endTime = System.currentTimeMillis()
      case Failure(_) => job.endTime = System.currentTimeMillis()
    }

    // add the job to the mapping
    jobs += (job.jobId -> job)
    job
  }

}

/**
 * Job Manager Companion Object
 * @author lawrence.daniels@gmail.com
 */
object JobManager {

  /**
   * Represents a job
   */
  trait JobItem {

    def jobId: Int

    def command: String

    def task: Future[_]

    def startTime: Long

    var endTime: Long = _

  }

  /**
   * Represents an asynchronous job
   */
  case class AsyncJob(jobId: Int, startTime: Long, task: Future[_], command: String) extends JobItem

  /**
   * Represents an asynchronous I/O job
   */
  case class AsyncIOJob(jobId: Int, asyncIO: AsyncIO, command: String) extends JobItem {

    def task: Future[_] = asyncIO.task

    def startTime: Long = asyncIO.startTime

  }

}


text:
package com.slack.api.app_backend.events.handler;

import com.slack.api.app_backend.events.EventHandler;
import com.slack.api.app_backend.events.payload.PinRemovedPayload;
import com.slack.api.model.event.PinRemovedEvent;

public abstract class PinRemovedHandler extends EventHandler<PinRemovedPayload> {

    @Override
    public String getEventType() {
        return PinRemovedEvent.TYPE_NAME;
    }
}


text:
<component name="libraryTable">
  <library name="ijkplayer-java-0.7.5">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/tv.danmaku.ijk.media/ijkplayer-java/0.7.5/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/tv.danmaku.ijk.media/ijkplayer-java/0.7.5/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
'use strict';

const metasync = require('..');
const fs = require('fs');
const assert = require('assert');
const ASYNC_TIMEOUT = 200;

// assert.deepStrictEqual polyfill for pre-io.js
if (!assert.deepStrictEqual) {
  assert.deepStrictEqual = (actual, expected, message) => {
    const actualKeys = Object.keys(actual);
    const expectedKeys = Object.keys(expected);
    assert.strictEqual(actualKeys.length, expectedKeys.length, message);
    let i, key;
    for (i = 0; i < actualKeys.length; i++) {
      key = actualKeys[i];
      assert.strictEqual(actual[key], expected[key], message);
    }
  };
}

// Functional Asyncronous Composition

function compositionTest(end) {

  metasync.composition(
    [f1, f2, f3, [[f4, f5, [f6, f7], f8]], [[f9, f10]], f11],
    (data) => console.dir(data)
  );

  function f1(callback) {
    console.log('f1');
    setTimeout(() => callback('result1'), ASYNC_TIMEOUT);
  }

  function f2(data, callback) {
    console.log('f2');
    setTimeout(() => callback('result2'), ASYNC_TIMEOUT);
  }

  function f3(data, callback) {
    console.log('f3');
    setTimeout(() => {
      data.third = 'result3';
      callback();
    }, ASYNC_TIMEOUT);
  }

  function f4(callback) {
    console.log('f4');
    setTimeout(() => callback(), ASYNC_TIMEOUT);
  }

  function f5(data, callback) {
    console.log('f5');
    setTimeout(() => callback(5), ASYNC_TIMEOUT);
  }

  function f6(data, callback) {
    console.log('f6');
    setTimeout(() => callback('result6'), ASYNC_TIMEOUT);
  }

  function f7(data, callback) {
    console.log('f7');
    setTimeout(() => callback('result7'), ASYNC_TIMEOUT);
  }

  function f8(data, callback) {
    console.log('f8');
    setTimeout(() => callback('result8'), ASYNC_TIMEOUT);
  }

  function f9(data, callback) {
    console.log('f9');
    setTimeout(() => callback('result9'), ASYNC_TIMEOUT);
  }

  function f10(data, callback) {
    console.log('f10');
    setTimeout(() => callback('result10'), ASYNC_TIMEOUT);
  }

  function f11(data, callback) {
    console.log('f11');
    setTimeout(() => {
      callback('result11');
      console.log('Composition test done');
      end();
    }, ASYNC_TIMEOUT);
  }

}

// Data Collector

function dataCollectorTest(end) {

  const dataCollector = new metasync.DataCollector(4);

  dataCollector.on('done', (errs, data) => {
    console.dir({
      dataKeys: Object.keys(data)
    });
    console.log('DataCollector test done');
    end();
  });

  dataCollector.collect('user', { name: 'Marcus Aurelius' });

  fs.readFile('HISTORY.md', (err, data) => {
    dataCollector.collect('history', data);
  });

  fs.readFile('README.md', (err, data) => {
    dataCollector.collect('readme', data);
  });

  setTimeout(() => {
    dataCollector.collect('timer', { date: new Date() });
  }, ASYNC_TIMEOUT);

}

function dataCollectorTimeoutTest(end) {

  const dataCollector = new metasync.DataCollector(4, 1000);

  dataCollector.on('timeout', (err, data) => {
    console.dir({
      err: err ? err.toString() : null,
      dataKeys: Object.keys(data)
    });
    console.log('Collector timeout test done');
    end();
  });

  dataCollector.collect('user', { name: 'Marcus Aurelius' });

}

function dataCollectorErrorTest(end) {

  const dataCollector = new metasync.DataCollector(4);

  dataCollector.on('error', (err, key) => {
    console.dir({
      err: err ? err.toString() : null,
      key
    });
  });

  dataCollector.on('done', (errs, data) => {
    console.dir({
      errorKeys: errs ? Object.keys(errs) : null,
      dataKeys: Object.keys(data)
    });
    console.log('Collector Error test done');
    end();
  });

  dataCollector.collect('user', new Error('User not found'));
  dataCollector.collect('file', 'file content');
  dataCollector.collect('score', 1000);
  dataCollector.collect('tcp', new Error('No socket'));

}

// Key Collector

function keyCollectorTest(end) {

  const keyCollector = new metasync.KeyCollector(['user', 'history'], 1000);

  keyCollector.on('done', (errs, data) => {
    console.dir({
      dataKeys: Object.keys(data)
    });
    console.log('KeyCollector test done');
    end();
  });

  keyCollector.collect('user', { name: 'Marcus Aurelius' });

  fs.readFile('HISTORY.md', (err, data) => {
    keyCollector.collect('history', data);
  });

}
// Parallel execution

function parallelTest(end) {

  metasync.parallel([pf1, pf2, pf3], () => {
    console.log('Parallel test done');
    end();
  });

  function pf1(data, callback) {
    console.log('pf1');
    setTimeout(() => callback('result1'), ASYNC_TIMEOUT);
  }

  function pf2(data, callback) {
    console.log('pf2');
    setTimeout(() => callback('result2'), ASYNC_TIMEOUT);
  }

  function pf3(data, callback) {
    console.log('pf3');
    setTimeout(() => callback('result3'), ASYNC_TIMEOUT);
  }

}

// Sequential execution

function sequentialTest(end) {

  metasync.sequential([sf1, sf2, sf3], () => {
    console.log('Sequential test done');
    end();
  });

  function sf1(data, callback) {
    console.log('sf1');
    setTimeout(() => callback('result1'), ASYNC_TIMEOUT);
  }

  function sf2(data, callback) {
    console.log('sf2');
    setTimeout(() => callback('result2'), ASYNC_TIMEOUT);
  }

  function sf3(data, callback) {
    console.log('sf3');
    setTimeout(() => callback('result3'), ASYNC_TIMEOUT);
  }

}

// Asynchrous filter

function filterTest(end) {

  const dataToFilter = [
    'Lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur',
    'adipiscing', 'elit', 'sed', 'do', 'eiusmod', 'tempor',
    'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua',
  ];

  function filterPredicate(item, callback) {
    // filter words which consists of unique letters only
    const letters = [];
    console.log('checking value: ' + item);
    let i;
    for (i = 0; i < item.length; ++i) {
      if (letters.includes(item[i].toLowerCase())) {
        break;
      }
      letters.push(item[i].toLowerCase());
    }

    setTimeout(() => callback(letters.length === item.length), ASYNC_TIMEOUT);
  }

  metasync.filter(dataToFilter, filterPredicate, (result) => {
    console.log('filtered array: ' + result);
    console.log('Filter test done');
    end();
  });

}

// Asynchrous find

function findTest(end) {

  metasync.find(
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
    (item, callback) => (
      callback(item % 3 === 0 && item % 5 === 0)
    ),
    (result) => {
      console.log('found value: ' + result);
      console.log('Find test done');
      end();
    }
  );

}

// Asyncronous each in parallel

function eachTest(end) {

  metasync.each(
    ['a', 'b', 'c'],
    (item, callback) => {
      console.dir({ each: item });
      callback();
    },
    (/*data*/) => {
      console.log('Each test done');
      end();
    }
  );

}

// Asyncronous series (sequential)

function seriesTest(end) {

  metasync.series(
    //['a', 'b', 'c'],
    new Array(5000),
    (item, callback) => {
      //console.dir({ series: item });
      callback();
    },
    (/*data*/) => {
      console.log('Series test done');
      end();
    }
  );

}

// Asyncronous reduce (sequential)

function reduceTest(end) {

  metasync.reduce(
    ['a', 'b', 'c'],
    (prev, curr, callback) => {
      console.dir({ reduce: { prev, curr } });
      callback(null, curr);
    },
    (/*err, data*/) => {
      console.log('Reduce test done');
      end();
    }
  );

}

function concurrentQueueTest(end) {

  const queue =  new metasync.ConcurrentQueue(3, 2000);

  queue.on('process', (item, callback) => {
    setTimeout(() => {
      console.dir({ item });
      callback();
    }, 100);
  });

  queue.on('timeout', () => {
    console.log('ConcurrentQueue timed out');
  });

  queue.on('empty', () => {
    console.log('ConcurrentQueue test done');
    end();
  });

  queue.add({ id: 1 });
  queue.add({ id: 2 });
  queue.add({ id: 3 });
  queue.add({ id: 4 });
  queue.add({ id: 5 });
  queue.add({ id: 6 });
  queue.add({ id: 8 });
  queue.add({ id: 9 });
}

function concurrentQueuePauseResumeStopTest(end) {
  const queue =  new metasync.ConcurrentQueue(3, 2000);
  queue.pause();
  queue.on('empty', end);
  if (!queue.events.empty) {
    console.log('ConcurrentQueue pause test done');
  }
  queue.resume();
  queue.on('empty', end);
  if (queue.events.empty) {
    console.log('ConcurrentQueue resume test done');
  }
  queue.stop();
  if (queue.count === 0) {
    console.log('ConcurrentQueue stop test done');
  }
}

function throttleTest(end) {

  let state;

  function fn(letter) {
    console.log('Throttled function, state: ' + state);
    if (state === letter) {
      console.log('Throttle test done');
      end();
    }
  }

  const f1 = metasync.throttle(500, fn, ['I']);

  // to be called 2 times (first and last: A and E)
  state = 'A';
  f1();
  state = 'B';
  f1();
  state = 'C';
  f1();
  state = 'D';
  f1();
  state = 'E';
  f1();

  // to be called 2 times (last will be I)
  setTimeout(() => {
    state = 'F';
    f1();
  }, 600);
  setTimeout(() => {
    state = 'G';
    f1();
  }, 700);
  setTimeout(() => {
    state = 'H';
    f1();
  }, 1000);
  setTimeout(() => {
    state = 'I';
    f1();
  }, 1100);

}

function mapTest() {
  metasync.map([1, 2, 3], (item, callback) => {
    setTimeout(() => {
      callback(null, item * item);
    }, item * 10);
  }, (error, result) => {
    assert.ifError(error);
    assert.deepStrictEqual(result, [1, 4, 9]);
    console.log('Map test #1 done');
  });

  metasync.map([1, 2, 3], (item, callback) => {
    setTimeout(() => {
      if (item === 2) {
        callback(new Error());
      } else {
        callback(null, item);
      }
    }, item * 10);
  }, (error, result) => {
    assert.ok(error);
    assert.ifError(result);
    console.log('Map test #2 done');
  });
}

function timeoutTest() {
  // Done function called by timer
  const start1 = new Date();
  metasync.timeout(200, (done) => {
    setTimeout(done, 300);
  }, () => {
    const timeDiff = new Date() - start1;
    assert(timeDiff < 250);
    console.log('Timout test #1 done');
  });

  // Done function called by async function
  const start2 = new Date();
  metasync.timeout(300, done => setTimeout(done, 200), () => {
    const timeDiff = new Date() - start2;
    assert(timeDiff < 250);
    console.log('Timout test #2 done');
  });
}

function chainTest() {
  // Just to make sure we don't forget to merge the tests. There's some bug in
  // metasync.composition so part of tests, including this one, are not run.
  // As a temporary workaround, you can run it via
  //   $ node chain-example
  require('./chain-example');
}

// Run tests

metasync.composition([
  compositionTest,
  dataCollectorTest,
  dataCollectorTimeoutTest,
  dataCollectorErrorTest,
  keyCollectorTest,
  parallelTest,
  sequentialTest,
  filterTest,
  findTest,
  eachTest,
  seriesTest,
  reduceTest,
  concurrentQueueTest,
  concurrentQueuePauseResumeStopTest,
  throttleTest,
  mapTest,
  timeoutTest,
  chainTest
], () => {
  console.log('All tests done');
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls Sci. Nat. , Bot. , sér. 2 16: (1841)

#### Original name
Calathiscus sepia Mont.

### Remarks
null


text:
@implementation CCSTimeData

@end


text: module.exports = require('./Navbar');


text:
package com.taobao.android.dexposed;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

/**
 *
Operates on classes without using reflection.

 *
 *
This class handles invalid {@code null} inputs as best it can.
 * Each method documents its behaviour in more detail.

 *
 *
The notion of a {@code canonical name} includes the human
 * readable name for the type, for example {@code int[]}. The
 * non-canonical method variants work with the JVM names, such as
 * {@code [I}.

 *
 * @since 2.0
 * @version $Id: ClassUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
 */
public class ClassUtils {

    /**
     *
The package separator character: '.' == {@value}.

     */
    public static final char PACKAGE_SEPARATOR_CHAR = '.';

    /**
     *
The package separator String: {@code "."}.

     */
    public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR);

    /**
     *
The inner class separator character: '$' == {@value}.

     */
    public static final char INNER_CLASS_SEPARATOR_CHAR = '$';

    /**
     *
The inner class separator String: {@code "$"}.

     */
    public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR);

    /**
     *
Empty string.

     */
    public static final String STRING_EMPTY = "";

    /**
     * Maps primitive {@code Class}es to their corresponding wrapper {@code Class}.
     */
    private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>();
    static {
         primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
         primitiveWrapperMap.put(Byte.TYPE, Byte.class);
         primitiveWrapperMap.put(Character.TYPE, Character.class);
         primitiveWrapperMap.put(Short.TYPE, Short.class);
         primitiveWrapperMap.put(Integer.TYPE, Integer.class);
         primitiveWrapperMap.put(Long.TYPE, Long.class);
         primitiveWrapperMap.put(Double.TYPE, Double.class);
         primitiveWrapperMap.put(Float.TYPE, Float.class);
         primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
    }

    /**
     * Maps wrapper {@code Class}es to their corresponding primitive types.
     */
    private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<Class<?>, Class<?>>();
    static {
        for (Class<?> primitiveClass : primitiveWrapperMap.keySet()) {
            Class<?> wrapperClass = primitiveWrapperMap.get(primitiveClass);
            if (!primitiveClass.equals(wrapperClass)) {
                wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
            }
        }
    }

    /**
     * Maps a primitive class name to its corresponding abbreviation used in array class names.
     */
    private static final Map<String, String> abbreviationMap = new HashMap<String, String>();

    /**
     * Maps an abbreviation used in array class names to corresponding primitive class name.
     */
    private static final Map<String, String> reverseAbbreviationMap = new HashMap<String, String>();

    /**
     * Add primitive type abbreviation to maps of abbreviations.
     *
     * @param primitive Canonical name of primitive type
     * @param abbreviation Corresponding abbreviation of primitive type
     */
    private static void addAbbreviation(String primitive, String abbreviation) {
        abbreviationMap.put(primitive, abbreviation);
        reverseAbbreviationMap.put(abbreviation, primitive);
    }

    /**
     * Feed abbreviation maps
     */
    static {
        addAbbreviation("int", "I");
        addAbbreviation("boolean", "Z");
        addAbbreviation("float", "F");
        addAbbreviation("long", "J");
        addAbbreviation("short", "S");
        addAbbreviation("byte", "B");
        addAbbreviation("double", "D");
        addAbbreviation("char", "C");
    }

    /**
     *
ClassUtils instances should NOT be constructed in standard programming.
     * Instead, the class should be used as
     * {@code ClassUtils.getShortClassName(cls)}.

     *
     *
This constructor is public to permit tools that require a JavaBean
     * instance to operate.

     */
    public ClassUtils() {
      super();
    }

    // Short class name
    // ----------------------------------------------------------------------
    /**
     *
Gets the class name minus the package name for an {@code Object}.

     *
     * @param object  the class to get the short name for, may be null
     * @param valueIfNull  the value to return if null
     * @return the class name of the object without the package name, or the null value
     */
    public static String getShortClassName(Object object, String valueIfNull) {
        if (object == null) {
            return valueIfNull;
        }
        return getShortClassName(object.getClass());
    }

    /**
     *
Gets the class name minus the package name from a {@code Class}.

     *
     *
Consider using the Java 5 API {@link Class#getSimpleName()} instead.
     * The one known difference is that this code will return {@code "Map.Entry"} while
     * the {@code java.lang.Class} variant will simply return {@code "Entry"}.

     *
     * @param cls  the class to get the short name for.
     * @return the class name without the package name or an empty string
     */
    public static String getShortClassName(Class<?> cls) {
        if (cls == null) {
            return "";
        }
        return getShortClassName(cls.getName());
    }

    /**
     *
Gets the class name minus the package name from a String.

     *
     *
The string passed in is assumed to be a class name - it is not checked.

     *
Note that this method differs from Class.getSimpleName() in that this will
     * return {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply
     * return {@code "Entry"}.

     *
     * @param className  the className to get the short name for
     * @return the class name of the class without the package name or an empty string
     */
    public static String getShortClassName(String className) {
        if (className == null) {
            return STRING_EMPTY;
        }
        if (className.length() == 0) {
            return STRING_EMPTY;
        }

        StringBuilder arrayPrefix = new StringBuilder();

        // Handle array encoding
        if (className.startsWith("[")) {
            while (className.charAt(0) == '[') {
                className = className.substring(1);
                arrayPrefix.append("[]");
            }
            // Strip Object type encoding
            if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
                className = className.substring(1, className.length() - 1);
            }
        }

        if (reverseAbbreviationMap.containsKey(className)) {
            className = reverseAbbreviationMap.get(className);
        }

        int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
        int innerIdx = className.indexOf(
                INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
        String out = className.substring(lastDotIdx + 1);
        if (innerIdx != -1) {
            out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
        }
        return out + arrayPrefix;
    }

    /**
     *
Null-safe version of aClass.getSimpleName()

     *
     * @param cls the class for which to get the simple name.
     * @return the simple class name.
     * @since 3.0
     * @see Class#getSimpleName()
     */
    public static String getSimpleName(Class<?> cls) {
        if (cls == null) {
            return STRING_EMPTY;
        }
        return cls.getSimpleName();
    }

    /**
     *
Null-safe version of aClass.getSimpleName()

     *
     * @param object the object for which to get the simple class name.
     * @param valueIfNull the value to return if object is null
     * @return the simple class name.
     * @since 3.0
     * @see Class#getSimpleName()
     */
    public static String getSimpleName(Object object, String valueIfNull) {
        if (object == null) {
            return valueIfNull;
        }
        return getSimpleName(object.getClass());
    }

    // Package name
    // ----------------------------------------------------------------------
    /**
     *
Gets the package name of an {@code Object}.

     *
     * @param object  the class to get the package name for, may be null
     * @param valueIfNull  the value to return if null
     * @return the package name of the object, or the null value
     */
    public static String getPackageName(Object object, String valueIfNull) {
        if (object == null) {
            return valueIfNull;
        }
        return getPackageName(object.getClass());
    }

    /**
     *
Gets the package name of a {@code Class}.

     *
     * @param cls  the class to get the package name for, may be {@code null}.
     * @return the package name or an empty string
     */
    public static String getPackageName(Class<?> cls) {
        if (cls == null) {
            return STRING_EMPTY;
        }
        return getPackageName(cls.getName());
    }

    /**
     *
Gets the package name from a {@code String}.

     *
     *
The string passed in is assumed to be a class name - it is not checked.

     *
If the class is unpackaged, return an empty string.

     *
     * @param className  the className to get the package name for, may be {@code null}
     * @return the package name or an empty string
     */
    public static String getPackageName(String className) {
        if (className == null || className.length() == 0) {
            return STRING_EMPTY;
        }

        // Strip array encoding
        while (className.charAt(0) == '[') {
            className = className.substring(1);
        }
        // Strip Object type encoding
        if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
            className = className.substring(1);
        }

        int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
        if (i == -1) {
            return STRING_EMPTY;
        }
        return className.substring(0, i);
    }

    // Superclasses/Superinterfaces
    // ----------------------------------------------------------------------
    /**
     *
Gets a {@code List} of superclasses for the given class.

     *
     * @param cls  the class to look up, may be {@code null}
     * @return the {@code List} of superclasses in order going up from this one
     *  {@code null} if null input
     */
    public static List<Class<?>> getAllSuperclasses(Class<?> cls) {
        if (cls == null) {
            return null;
        }
        List<Class<?>> classes = new ArrayList<Class<?>>();
        Class<?> superclass = cls.getSuperclass();
        while (superclass != null) {
            classes.add(superclass);
            superclass = superclass.getSuperclass();
        }
        return classes;
    }

    /**
     *
Gets a {@code List} of all interfaces implemented by the given
     * class and its superclasses.

     *
     *
The order is determined by looking through each interface in turn as
     * declared in the source file and following its hierarchy up. Then each
     * superclass is considered in the same way. Later duplicates are ignored,
     * so the order is maintained.

     *
     * @param cls  the class to look up, may be {@code null}
     * @return the {@code List} of interfaces in order,
     *  {@code null} if null input
     */
    public static List<Class<?>> getAllInterfaces(Class<?> cls) {
        if (cls == null) {
            return null;
        }

        LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<Class<?>>();
        getAllInterfaces(cls, interfacesFound);

        return new ArrayList<Class<?>>(interfacesFound);
    }

    /**
     * Get the interfaces for the specified class.
     *
     * @param cls  the class to look up, may be {@code null}
     * @param interfacesFound the {@code Set} of interfaces for the class
     */
    private static void getAllInterfaces(Class<?> cls, HashSet<Class<?>> interfacesFound) {
        while (cls != null) {
            Class<?>[] interfaces = cls.getInterfaces();

            for (Class<?> i : interfaces) {
                if (interfacesFound.add(i)) {
                    getAllInterfaces(i, interfacesFound);
                }
            }

            cls = cls.getSuperclass();
         }
     }

    // Convert list
    // ----------------------------------------------------------------------
    /**
     *
Given a {@code List} of class names, this method converts them into classes.

     *
     *
A new {@code List} is returned. If the class name cannot be found, {@code null}
     * is stored in the {@code List}. If the class name in the {@code List} is
     * {@code null}, {@code null} is stored in the output {@code List}.

     *
     * @param classNames  the classNames to change
     * @return a {@code List} of Class objects corresponding to the class names,
     *  {@code null} if null input
     * @throws ClassCastException if classNames contains a non String entry
     */
    public static List<Class<?>> convertClassNamesToClasses(List<String> classNames) {
        if (classNames == null) {
            return null;
        }
        List<Class<?>> classes = new ArrayList<Class<?>>(classNames.size());
        for (String className : classNames) {
            try {
                classes.add(Class.forName(className));
            } catch (Exception ex) {
                classes.add(null);
            }
        }
        return classes;
    }

    /**
     *
Given a {@code List} of {@code Class} objects, this method converts
     * them into class names.

     *
     *
A new {@code List} is returned. {@code null} objects will be copied into
     * the returned list as {@code null}.

     *
     * @param classes  the classes to change
     * @return a {@code List} of class names corresponding to the Class objects,
     *  {@code null} if null input
     * @throws ClassCastException if {@code classes} contains a non-{@code Class} entry
     */
    public static List<String> convertClassesToClassNames(List<Class<?>> classes) {
        if (classes == null) {
            return null;
        }
        List<String> classNames = new ArrayList<String>(classes.size());
        for (Class<?> cls : classes) {
            if (cls == null) {
                classNames.add(null);
            } else {
                classNames.add(cls.getName());
            }
        }
        return classNames;
    }

    // Class loading
    // ----------------------------------------------------------------------
    /**
     * Returns the class represented by {@code className} using the
     * {@code classLoader}.  This implementation supports the syntaxes
     * "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
     * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
     *
     * @param classLoader  the class loader to use to load the class
     * @param className  the class name
     * @param initialize  whether the class must be initialized
     * @return the class represented by {@code className} using the {@code classLoader}
     * @throws ClassNotFoundException if the class is not found
     */
    public static Class<?> getClass(
            ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException {
        try {
            Class<?> clazz;
            if (abbreviationMap.containsKey(className)) {
                String clsName = "[" + abbreviationMap.get(className);
                clazz = Class.forName(clsName, initialize, classLoader).getComponentType();
            } else {
                clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
            }
            return clazz;
        } catch (ClassNotFoundException ex) {
            // allow path separators (.) as inner class name separators
            int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);

            if (lastDotIndex != -1) {
                try {
                    return getClass(classLoader, className.substring(0, lastDotIndex) +
                            INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
                            initialize);
                } catch (ClassNotFoundException ex2) { // NOPMD
                    // ignore exception
                }
            }

            throw ex;
        }
    }

    /**
     * Returns the (initialized) class represented by {@code className}
     * using the {@code classLoader}.  This implementation supports
     * the syntaxes "{@code java.util.Map.Entry[]}",
     * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
     * and "{@code [Ljava.util.Map$Entry;}".
     *
     * @param classLoader  the class loader to use to load the class
     * @param className  the class name
     * @return the class represented by {@code className} using the {@code classLoader}
     * @throws ClassNotFoundException if the class is not found
     */
    public static Class<?> getClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
        return getClass(classLoader, className, true);
    }

    /**
     * Returns the (initialized) class represented by {@code className}
     * using the current thread's context class loader. This implementation
     * supports the syntaxes "{@code java.util.Map.Entry[]}",
     * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
     * and "{@code [Ljava.util.Map$Entry;}".
     *
     * @param className  the class name
     * @return the class represented by {@code className} using the current thread's context class loader
     * @throws ClassNotFoundException if the class is not found
     */
    public static Class<?> getClass(String className) throws ClassNotFoundException {
        return getClass(className, true);
    }

    /**
     * Returns the class represented by {@code className} using the
     * current thread's context class loader. This implementation supports the
     * syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
     * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
     *
     * @param className  the class name
     * @param initialize  whether the class must be initialized
     * @return the class represented by {@code className} using the current thread's context class loader
     * @throws ClassNotFoundException if the class is not found
     */
    public static Class<?> getClass(String className, boolean initialize) throws ClassNotFoundException {
        ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
        ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
        return getClass(loader, className, initialize);
    }

    // ----------------------------------------------------------------------
    /**
     * Converts a class name to a JLS style class name.
     *
     * @param className  the class name
     * @return the converted name
     */
    private static String toCanonicalName(String className) {
        className = deleteWhitespace(className);
        if (className == null) {
            throw new NullPointerException("className must not be null.");
        } else if (className.endsWith("[]")) {
            StringBuilder classNameBuffer = new StringBuilder();
            while (className.endsWith("[]")) {
                className = className.substring(0, className.length() - 2);
                classNameBuffer.append("[");
            }
            String abbreviation = abbreviationMap.get(className);
            if (abbreviation != null) {
                classNameBuffer.append(abbreviation);
            } else {
                classNameBuffer.append("L").append(className).append(";");
            }
            className = classNameBuffer.toString();
        }
        return className;
    }

    /**
     *
Converts an array of {@code Object} in to an array of {@code Class} objects.
     * If any of these objects is null, a null element will be inserted into the array.

     *
     *
This method returns {@code null} for a {@code null} input array.

     *
     * @param array an {@code Object} array
     * @return a {@code Class} array, {@code null} if null array input
     * @since 2.4
     */
    public static Class<?>[] toClass(Object... array) {
        if (array == null) {
            return null;
        } else if (array.length == 0) {
            return new Class[0];
        }
        Class<?>[] classes = new Class[array.length];
        for (int i = 0; i < array.length; i++) {
            classes[i] = array[i] == null ? null : array[i].getClass();
        }
        return classes;
    }

    // Delete
    //-----------------------------------------------------------------------
    /**
     *
Deletes all whitespaces from a String as defined by
     * {@link Character#isWhitespace(char)}.

     *
     *

     * StringUtils.deleteWhitespace(null)         = null
     * StringUtils.deleteWhitespace("")           = ""
     * StringUtils.deleteWhitespace("abc")        = "abc"
     * StringUtils.deleteWhitespace("   ab  c  ") = "abc"
     *

     *
     * @param str  the String to delete whitespace from, may be null
     * @return the String without whitespaces, {@code null} if null String input
     */
    public static String deleteWhitespace(String str) {
        if (isEmpty(str)) {
            return str;
        }
        int sz = str.length();
        char[] chs = new char[sz];
        int count = 0;
        for (int i = 0; i < sz; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                chs[count++] = str.charAt(i);
            }
        }
        if (count == sz) {
            return str;
        }
        return new String(chs, 0, count);
    }

    // Empty checks
    //-----------------------------------------------------------------------
    /**
     *
Checks if a CharSequence is empty ("") or null.

     *
     *

     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     *

     *
     *
NOTE: This method changed in Lang version 2.0.
     * It no longer trims the CharSequence.
     * That functionality is available in isBlank().

     *
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is empty or null
     * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
     */
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

}


text:
package org.sagebionetworks.repo.manager.file;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.dao.FileHandleDao;
import org.sagebionetworks.repo.model.file.FileHandleAssociateType;
import org.sagebionetworks.repo.model.file.FileHandleAssociationManager;
import org.sagebionetworks.repo.model.file.FileHandleAssociationProvider;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;

public class FileHandleAssociationManagerImpl implements FileHandleAssociationManager {

	Map<FileHandleAssociateType, FileHandleAssociationProvider> providerMap;

	private FileHandleDao fileHandleDao;

	@Autowired
	public FileHandleAssociationManagerImpl(FileHandleDao fileHandleDao) {
		this.fileHandleDao = fileHandleDao;
	}

	@Override
	public Set<String> getFileHandleIdsAssociatedWithObject(List<String> fileHandleIds, String objectId,
			FileHandleAssociateType associateType) {

		ValidateArgument.required(fileHandleIds, "fileHandleIds");
		ValidateArgument.required(associateType, "associateType");
		ValidateArgument.required(objectId, "objectId");

		if (fileHandleIds.isEmpty()) {
			return Collections.emptySet();
		}

		Set<String> allFileHandleIds = new HashSet<>(fileHandleIds);

		// Gather all the file handle ids that are previews (each entry is <FileHandlePreviewId, FileHandleId>)
		Map<String, String> fileHandlePreviewIds = fileHandleDao.getFileHandlePreviewIds(fileHandleIds);

		// Expand the initial set with the file handles ids that reference any preview
		allFileHandleIds.addAll(fileHandlePreviewIds.values());

		FileHandleAssociationProvider provider = getProvider(associateType);

		// Get the directly associated file handle ids
		Set<String> associatedFileHandleIds = provider.getFileHandleIdsDirectlyAssociatedWithObject(new ArrayList<>(allFileHandleIds), objectId);

		// Builds the result filtering the ids that are not associated
		Set<String> result = fileHandleIds.stream().filter(id -> {
			// Retain the given id or the id of the file handle mapped with the preview if it exist
			String mappedId = fileHandlePreviewIds.getOrDefault(id, id);
			return associatedFileHandleIds.contains(mappedId);
		}).collect(Collectors.toSet());

		return result;
	}

	@Override
	public ObjectType getAuthorizationObjectTypeForAssociatedObjectType(FileHandleAssociateType associateType) {
		ValidateArgument.required(associateType, "associateType");
		FileHandleAssociationProvider provider = getProvider(associateType);
		return provider.getAuthorizationObjectTypeForAssociatedObjectType();
	}

	/**
	 * Helper to get the correct provider for a given type.
	 *
	 * @param type
	 * @return
	 */
	private FileHandleAssociationProvider getProvider(FileHandleAssociateType type) {
		if (type == null) {
			throw new IllegalArgumentException("FileHandleAssociationType cannot be null");
		}
		FileHandleAssociationProvider provider = providerMap.get(type);
		if (provider == null) {
			throw new UnsupportedOperationException(
					"Currently do not support this operation for FileHandleAssociationType = " + type);
		}
		return provider;
	}

	/**
	 * Injected.
	 *
	 * @param providerMap
	 */
	public void setProviderMap(Map<FileHandleAssociateType, FileHandleAssociationProvider> providerMap) {
		this.providerMap = providerMap;
	}

}


text: define({name:"util"});


text:
var loader = require("../helpers/moduleLoader.js");
var nodeMocks = require("../mocks/nodeMocks.js");
var child_processMock = nodeMocks.getMockChildProcess();
var MockChildProcess = nodeMocks.MockChildProcess;
var PhantomBrowser = loader.loadModule("./js/browsers/PhantomBrowser.js", {"child_process" : child_processMock}).module.exports;

var BrowserStatus = require("../../js/browsers/BrowserStatus.js");

describe("PhantomBrowser", function(){

	var browser;

	beforeEach(function(){
		MockChildProcess.reset();
	});

	it("Can check that phantomjs is available", function(done){

		child_processMock.setstdout("1.7.0");
		PhantomBrowser.test()

		.then(function(){
			expect(child_processMock.exec).toHaveBeenCalledWith("phantomjs --version", jasmine.any(Object), jasmine.any(Function));
			done();
		});
	});

	it("Can will check that phantomjs is 1.7 or greater", function(done){
		debugger;
		var version = "1.4.0";
		child_processMock.setstdout(version);
		PhantomBrowser.test()

		.then(function(){
			done(false);
		}, function(v){
			expect(v).toEqual(version);
			done();
		});
	});

	it("Can execute phantomjs with a given script", function(){
		browser = new PhantomBrowser();

		var script = "script.js";

		browser.execute(script);

		expect(child_processMock.spawn).toHaveBeenCalledWith("phantomjs", [script]);
	});

	it("Will listen to the stdout of the process and fire the 'message' event when data is received", function(done){
		browser = new PhantomBrowser();
		var script = "script.js";
		var spy = jasmine.createSpy("messageCallback");
		var message = {title : "Stuff", data : "blah blah"};

		browser.execute(script);
		browser.on("message", spy);

		MockChildProcess.stdout.fire("data", null, JSON.stringify(message));

		waits(50);

		runs(function(){
			expect(spy).toHaveBeenCalledWith(message);
			done();
		});

	});

	it("Will fire the 'error' event and update it's status if the process errors", function(done){
		browser = new PhantomBrowser();
		var script = "script.js";
		var spy = jasmine.createSpy("errorCallback");
		var error = new Error("Some Error");

		browser.execute(script);
		browser.on("error", spy);

		MockChildProcess.fire("error", error, null);

		waits(50);

		runs(function(){
			expect(spy).toHaveBeenCalledWith(error, null);
			expect(browser.status).toBe(BrowserStatus.ERROR);
			done();
		});
	});

	it("Will fire the 'complete' event and update it's status when the process exits", function(done){
		browser = new PhantomBrowser();
		var script = "script.js";
		var spy = jasmine.createSpy("completeCallback");

		browser.execute(script);
		browser.on("complete", spy);

		MockChildProcess.fire("exit", 0);

		waits(50);

		runs(function(){
			expect(spy).toHaveBeenCalledWith(null, null);
			expect(browser.status).toBe(BrowserStatus.IDLE);
			done();
		});
	});

	it("Can close the process", function(){
		browser = new PhantomBrowser();
		var script = "script.js";

		browser.execute(script);
		browser.close();

		expect(MockChildProcess.disconnect).toHaveBeenCalled();

	});

});


text:
module Descraff
  module Model

    class FieldDescription
      attr_reader :name, :options

      def initialize(name, options=nil)
        @name = name
        @options ||= {}
        @options.merge!(options) if options
      end
    end

  end
end


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class SendEmail(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the SendEmail Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(SendEmail, self).__init__(temboo_session, '/Library/Google/Gmail/SendEmail')

    def new_input_set(self):
        return SendEmailInputSet()

    def _make_result_set(self, result, path):
        return SendEmailResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return SendEmailChoreographyExecution(session, exec_id, path)

class SendEmailInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the SendEmail
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_AttachmentName(self, value):
        """
        Set the value of the AttachmentName input for this Choreo. ((optional, string) The name of the file to attach to the email.)
        """
        super(SendEmailInputSet, self)._set_input('AttachmentName', value)
    def set_AttachmentURL(self, value):
        """
        Set the value of the AttachmentURL input for this Choreo. ((optional, string) URL of a hosted file that you wish to add as an attachment.  Use this instead of a normal Attachment.)
        """
        super(SendEmailInputSet, self)._set_input('AttachmentURL', value)
    def set_Attachment(self, value):
        """
        Set the value of the Attachment input for this Choreo. ((optional, string) The Base64 encoded contents of the file to attach to the email.  Use this instead of AttachmentURL.)
        """
        super(SendEmailInputSet, self)._set_input('Attachment', value)
    def set_BCC(self, value):
        """
        Set the value of the BCC input for this Choreo. ((optional, string) An email address to BCC on the email you're sending. Can be a comma separated list of email addresses.)
        """
        super(SendEmailInputSet, self)._set_input('BCC', value)
    def set_CC(self, value):
        """
        Set the value of the CC input for this Choreo. ((optional, string) An email address to CC on the email you're sending. Can be a comma separated list of email addresses.)
        """
        super(SendEmailInputSet, self)._set_input('CC', value)
    def set_FromAddress(self, value):
        """
        Set the value of the FromAddress input for this Choreo. ((conditional, string) The address and name (optional) that the email is being sent from e.g., "Dan" <dan@temboo.com>)
        """
        super(SendEmailInputSet, self)._set_input('FromAddress', value)
    def set_MessageBody(self, value):
        """
        Set the value of the MessageBody input for this Choreo. ((required, string) The message body for the email.)
        """
        super(SendEmailInputSet, self)._set_input('MessageBody', value)
    def set_Password(self, value):
        """
        Set the value of the Password input for this Choreo. ((required, password) A Google App-specific password that you've generated after enabling 2-Step Verification. See the Gmailv2 bundle for OAuth.)
        """
        super(SendEmailInputSet, self)._set_input('Password', value)
    def set_Subject(self, value):
        """
        Set the value of the Subject input for this Choreo. ((required, string) The subject line of the email.)
        """
        super(SendEmailInputSet, self)._set_input('Subject', value)
    def set_ToAddress(self, value):
        """
        Set the value of the ToAddress input for this Choreo. ((required, string) The email address that you want to send an email to. Can be a comma separated list of email addresses.)
        """
        super(SendEmailInputSet, self)._set_input('ToAddress', value)
    def set_Username(self, value):
        """
        Set the value of the Username input for this Choreo. ((required, string) Your full Google email address e.g., martha.temboo@gmail.com. See the Gmailv2 bundle for OAuth.)
        """
        super(SendEmailInputSet, self)._set_input('Username', value)

class SendEmailResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the SendEmail Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Success(self):
        """
        Retrieve the value for the "Success" output from this Choreo execution. ((boolean) Indicates the result of the SMTP operation. The value will be "true" for a successful request.)
        """
        return self._output.get('Success', None)

class SendEmailChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return SendEmailResultSet(response, path)


text:
Cancer Code
=============

Below is a skeleton of the code contained in the code.cancer.py file.  Below should be summaries of the contents, as well as links to the source itself.

CancerSim Class
-----------------

The main cancer simulation class

.. autoclass:: code.cancer.CancerSim
        :members:


text:
function setPathForLibDirectory(libFile) {
	if ( typeof Titanium == 'undefined') {
		lib = require("../../lib/" + libFile);
	} else {
		lib = require(libFile);
	}
	return lib;
};

function cameraService() {
	intentService = setPathForLibDirectory('customCalls/intentService');
	intentService = new intentService();
	loadingSpinner = setPathForLibDirectory('loadingSpinner/loadingSpinner');
	this.spinner = new loadingSpinner();
};

cameraService.prototype.takePicture = function(postTags, shareImageButton, anchor) {
	var imageFilePath;
	var dialog = Titanium.UI.createOptionDialog({
		title : 'Choose an image source...',
		options : ['Camera', 'Photo Gallery', 'Cancel'],
		cancel : 2
	});
	var self = this;
	dialog.addEventListener("click", function(e) {
		if (OS_IOS) {
			var selectedIndex = e.index;
		} else if (OS_ANDROID) {
			var selectedIndex = dialog.selectedIndex;
		}
		if (selectedIndex == 0) {
			Titanium.Media.showCamera({
				saveToPhotoGallery : true,
				allowImageEditing : true,
				saveToPhotoGallery : true,
				mediaTypes : Titanium.Media.MEDIA_TYPE_PHOTO,
				success : function(event) {
					self.spinner.addTo(anchor);
					self.spinner.show();
					var fileName = 'excl' + new Date().getTime() + '.jpg';
					var imageFile = Ti.Filesystem.getFile('file:///sdcard/').exists() ? Ti.Filesystem.getFile('file:///sdcard/', fileName) : Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, fileName);
					imageFile.write(event.media);
					if (event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) {
						imageFilePath = imageFile.nativePath;
						if (OS_ANDROID) {
							intentService.sendIntentImageAndroid(postTags, imageFilePath);
						} else if (OS_IOS) {
							intentService.sendIntentImageiOS(postTags, imageFilePath, anchor);
						}
					}
					self.spinner.hide();
				},
				cancel : function() {
				},
				error : function(error) {
					var errorMessage = Titanium.UI.createAlertDialog({
						title : 'Camera'
					});
					if (error.code == Titanium.Media.NO_CAMERA) {
						errorMessage.setMessage('Device does not have camera');
					} else {
						errorMessage.setMessage('Unexpected error: ' + error.code);
					}
					errorMessage.show();
				}
			});
		}

		if (selectedIndex == 1) {
			Titanium.Media.openPhotoGallery({
				success : function(event) {
					var imageFile = event.media;
					if (event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) {
						Ti.App.Properties.setString("image", imageFile.nativePath);
						imageFilePath = imageFile.nativePath;
						if (OS_ANDROID) {
							loadingSpinner.hide();
							intentService.sendIntentImageAndroid(postTags, imageFilePath);
						} else if (OS_IOS) {
							fileNameInstagram = "_temp.ig";
							imageFileInstagram = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory, fileNameInstagram);
							imageFileInstagram.write(event.media);
							intentService.sendIntentImageiOS(postTags, imageFilePath, imageFileInstagram.getNativePath(), instagramAnchor);
						}
					}
				},
				cancel : function() {
				},
				error : function() {
					var errorMessage = Titanium.UI.createAlertDialog({
						title : 'Photo Gallery'
					});
					errorMessage.setMessage('Unexpected error: ' + error.code);
					errorMessage.show();
				}
			});
		} else {
			//cancel was tapped
		}

	});
	dialog.show();
};

module.exports = cameraService;


text:
<?php

namespace Behat\Behat\Definition\Call;

use Behat\Behat\Definition\Definition;
use Behat\Testwork\Call\RuntimeCallee;

/**
 * Represents a step definition created and executed in the runtime.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
abstract class RuntimeDefinition extends RuntimeCallee implements Definition
{
    /**
     * @var string
     */
    private $type;
    /**
     * @var string
     */
    private $pattern;

    /**
     * Initializes definition.
     *
     * @param string      $type
     * @param string      $pattern
     * @param callable    $callable
     * @param null|string $description
     */
    public function __construct($type, $pattern, $callable, $description = null)
    {
        $this->type = $type;
        $this->pattern = $pattern;

        parent::__construct($callable, $description);
    }

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * {@inheritdoc}
     */
    public function getPattern()
    {
        return $this->pattern;
    }

    /**
     * {@inheritdoc}
     */
    public function __toString()
    {
        return $this->getType() . ' ' . $this->getPattern();
    }
}