text:
package ch.tuason.djbattlescore.lib.components;

import ch.tuason.djbattlescore.lib.MainController;
import ch.tuason.djbattlescore.lib.components.comps.BattleBarChart;
import ch.tuason.djbattlescore.lib.components.comps.Footer;
import ch.tuason.djbattlescore.lib.components.comps.Header;
import ch.tuason.djbattlescore.lib.components.comps.MainLayoutPane;
import ch.tuason.djbattlescore.lib.components.comps.NowPlayingImageRotator;
import ch.tuason.djbattlescore.lib.components.comps.ResultGridPane;
import ch.tuason.djbattlescore.lib.components.comps.ResultNowPlayingBoxRight;
import ch.tuason.djbattlescore.lib.data.entities.DjEntity;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.FileChooser;

/**
 * the ui components handler...
 *
 * @author maesi
 */
public class ComponentHandler {

    private final MainController mMainController;
    private MainLayoutPane mMainLayout;

    private ResultGridPane resultLayout;
    private NowPlayingImageRotator imageRotator;
    // private Button sayHiButton;
    private Header header;
    private BattleBarChart scoreBoardChart;
    private ResultNowPlayingBoxRight resultAndNowPlayingBox;
    private Footer footer;

    /**
     * constructor
     *
     * @param controller
     */
    public ComponentHandler(MainController controller) {
        this.mMainController = controller;
    }

    /**
     * returns the main layout...
     * @return
     */
    public MainLayoutPane getMainLayout() {
        if (mMainLayout == null) {
            mMainLayout = new MainLayoutPane(this);
        }
        return mMainLayout;
    }

    /**
     * method to null the bar chart instance...
     */
    public void nullBarchartComponent() {
        this.scoreBoardChart = null;
    }

    /**
     * returns the bar chart component...
     *
     * @return
     */
    public BattleBarChart getScoreBoardChart() {
        if (scoreBoardChart == null) {
            scoreBoardChart = new BattleBarChart(getController());
        }
        return scoreBoardChart;
    }

    /**
     * returns the whole right side (result and play now panels)...
     *
     * @return
     */
    public ResultNowPlayingBoxRight getResultAndPlayNowLayout() {
        if (resultAndNowPlayingBox == null) {
            resultAndNowPlayingBox = new ResultNowPlayingBoxRight(this);
        }
        return resultAndNowPlayingBox;
    }

    /**
     * returns the layout with the current results / standings...
     *
     * @return
     */
    public ResultGridPane getResultLayout() {
        if (resultLayout == null) {
            resultLayout = new ResultGridPane(this);
        }
        return resultLayout;
    }

    /**
     * returns an image rotator with the currently playing dj...
     *
     * @return a NowPlayingImageRotator instance...
     */
    public NowPlayingImageRotator getImageRotator() {
        if (imageRotator == null) {
            imageRotator = new NowPlayingImageRotator(this);
        }
        return imageRotator;
    }

    /**
     * returns the footer component...
     *
     * @return a Footer instance...
     */
    public Footer getFooter() {
        if (footer == null) {
            footer = new Footer(new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent t) {
                    Platform.exit();
                }

            }, new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent t) {
                    getController().getComponentHandler().getScoreBoardChart().resetChartAndAllData();
                }
            });
        }
        return footer;
    }

    /**
     * returns the title box with logo and label...
     * @return
     */
    public Header getHeader() {
        if (header == null) {
            header = new Header();
        }
        return header;
    }

    /**
     * opens a Import Dialog to import a CSV file...
     */
    public void showCSVImportDialog() {
        FileChooser fileChooser = new FileChooser();

        //Set extension filter
        FileChooser.ExtensionFilter extFilterCVS = new FileChooser.ExtensionFilter("CSV files (*.csv)", "*.CSV");
        fileChooser.getExtensionFilters().addAll(extFilterCVS);

        //Show open file dialog
        File file = fileChooser.showOpenDialog(null);

        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(file.getAbsolutePath()));
            if (getController().getDataHandler().readCSVFileFromBufferedReader(br, true)) {
                System.out.println("CSV data successfully imported... updating the app layout!");
                getMainLayout().reloadBarChartWithNewData();
                updateDjRanking();
            } else {
                System.out.println("Something with importing the CSV data went absolutely wrong!");
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Could not find the file to load...");
            Logger.getLogger(ComponentHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * method to update the dj ranking...
     */
    public void updateDjRanking() {
        List<DjEntity> results = getController().getDataHandler().getSortedAfterRankDjList();
        getResultLayout().removeCurrentDJRanking();
        if (!results.isEmpty()) {
            getResultLayout().addCurrentDJRanking(results);
            if (areAllVotesEqual(results)) {
                getImageRotator().addStandardImage();
            } else {
                getImageRotator().updateCurrentlyPlayingImage(results.get(0));
            }
        }
    }

    /**
     * checks whether all votes of the dj's are equal or not...
     * @param listOfDjs
     * @return boolean true or false whether the votes of the dj's are equal or
     * not...
     */
    private boolean areAllVotesEqual(List<DjEntity> listOfDjs) {
        int lastVote = -1;
        for (DjEntity dj : listOfDjs) {
            if (lastVote == -1) {
                lastVote = dj.getVotes();
            } else {
                if (lastVote != dj.getVotes()) {
                    return false;
                }
            }
        }
        return true;
    }

    public void checkIfNeededAndUpdateDjRanking() {
        if (getResultLayout().isDjRankingUpdateNeeded())
            updateDjRanking();
    }

    public MainController getController() {
        return this.mMainController;
    }
}


text:
var tinyevt = require('tinyevt');

function domEvtOff(e, evt, fn) {
	if (e.removeEventListener) {
		e.removeEventListener(evt, fn);
	} else if (e.detachEvent) {
		e.detachEvent('on' + evt, fn);
	}
}
function domEvtOn(elem, event, fn) {
	function listenHandler(e) {
		var ret = fn.apply(this, arguments);
		if (ret === false) {
			e.stopPropagation();
			e.preventDefault();
		}
		return (ret);
	}

	function attachHandler() {
		var ret = fn.call(elem, window.event);
		if (ret === false) {
			window.event.returnValue = false;
			window.event.cancelBubble = true;
		}
		return (ret);
	}
	if (elem.addEventListener) {
		elem.addEventListener(event, listenHandler, false);
		return listenHandler;
	} else {
		elem.attachEvent("on" + event, attachHandler);
		return attachHandler;
	}
}

var evt = (function(){
	var dom = function(el,evt,fn){
		var evtFn = domEvtOn(el,evt,fn);
		return function(){
			domEvtOff(el,evt,evtFn);
		};
	};
	var fn = function(el,evt,fn){
		return dom(el,evt,fn);
	};
	tinyevt(fn);
	return fn;
})();

module.exports = evt;

redpajama_set_name: RedPajamaGithub


text:
#import "ADSharedMacros.h"
#import "CredentialHelper.h"
#import "DataAccessHelper.h"
#import "FavoritesHelper.h"
#import "ListViewController.h"
#import "PresenceAppDelegate.h"
#import "PresenceConstants.h"
#import "StatusViewController.h"
#import "User.h"

#define kCustomRowHeight 48  /* height of each row */
#define kThreadBatchCount 5 /* number of rows to create before re-drawing the table view */

@interface ListViewController ()

- (void)startIconDownload:(User *)aUser forIndexPath:(NSIndexPath *)indexPath;
- (void)synchronousLoadTwitterData;

@end

@implementation ListViewController

@synthesize engine, composeBarButton, userIdArray, users;
@synthesize imageDownloadsInProgress, finishedThreads, dataAccessHelper;

#pragma mark -
#pragma mark custom init method

- (id)initWithUserIdArray:(NSMutableArray *)userIds
{
	if(self = [super initWithStyle:UITableViewStylePlain])
	{
		/* set the list of users to load */
		self.userIdArray = userIds;

		/* allocate the memory for the NSMutableArray of people on this ViewController */
		self.users = [[NSMutableArray alloc] init];

		/* create a UIBarButtonItem for the right side using the Compose style, this will
		 * present the ComposeStatusViewController modally */
		UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose
		                                                                              target:self
		                                                                              action:@selector(presentUpdateStatusController)];
		[self.navigationItem setRightBarButtonItem:rightBarButton animated:NO];
		[rightBarButton release];
	}
	return self;
}

- (void)setUserIdArray:(NSMutableArray *)newIdArray
{
	[userIdArray autorelease];
	userIdArray = [newIdArray retain];
	[self.users removeAllObjects];
	[self synchronousLoadTwitterData];
}

#pragma mark -
#pragma mark dealloc

- (void)dealloc
{
	[engine release];
	[composeBarButton release];
	[userIdArray release];
	[users release];
	[imageDownloadsInProgress release];
	[dataAccessHelper release];
	[super dealloc];
}

#pragma mark -
#pragma mark UIViewController methods
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
	/* return YES for all interface orientations */
	return YES;
}

- (void)viewDidLoad
{
	self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
	self.navigationItem.rightBarButtonItem.enabled = YES;
}

/* override viewWillAppear to begin the data load */
- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	if(![self.engine isAuthorized])
	{
		PresenceAppDelegate *appDelegate = (PresenceAppDelegate *)[UIApplication sharedApplication].delegate;
		self.engine = [appDelegate getEngineForDelegate:self];
	}
	if([self.engine isAuthorized])
	{
		[self authSucceededForEngine];
	}
}

- (void)viewDidAppear:(BOOL)animated
{
	[super viewDidAppear:animated];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning
{
	/* Releases the view if it doesn't have a superview. */
	[super didReceiveMemoryWarning];

	/* terminate all pending download connections */
	NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
	[allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];

	NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
	/* for each user, determine if the user is visible
	 * if not, set the user's statusUpdate and image properties to nil
	 */
	for(int i = 0; i < [users count]; i++)
	{
		BOOL visible = NO;
		for(NSIndexPath *path in visiblePaths)
		{
			if(path.row == i)
			{
				visible = YES;
				break;
			}
		}
		if(!visible)
		{
			User *user = [users objectAtIndex:i];
			if(user)
			{
				user.statusUpdates = nil;
				user.image = nil;
			}
		}
	}
}

- (void)viewDidUnload
{
	/* Release any retained subviews of the main view.
	 * e.g. self.myOutlet = nil;
	 */
}

#pragma mark -
#pragma mark Data loading

/* synchronously get the usernames and call beginLoadUser for each username */
- (void)synchronousLoadTwitterData
{
	if( !IsEmpty(self.userIdArray) )
	{
		/* start the device's network activity indicator */
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		for(NSString *user_id in self.userIdArray)
		{
			[self synchronousLoadUser:user_id];
		}
	}
}

/* synchronously fetch data, initialize a user object, and add it to the list of people
 * call the main thread when finished
 */
- (void)synchronousLoadUser:(NSString *)user_id
{
	User *user = [dataAccessHelper initUserByUserId:user_id];
	if(![user isValid])
	{
		[user release];
		user = nil;

		/* get the user's information from Twitter */
		[self.engine getUserInformationFor:user_id];
	}
	else
	{
		[self.users addObject:user];
		[user release];
		[self didFinishLoadingUser];
	}
}

- (BOOL)dataLoadComplete
{
	return [self.userIdArray count] == [self.users count];
}

/* called by synchronousLoadUser when the load has finished */
- (void)didFinishLoadingUser
{
	/* in order to save redrawing the UI after every load, redraw after ever kThreadBatchCount
	 * loads or redraw in the case that the queue is on it's last operation
	 */
	self.finishedThreads++;
	if(self.finishedThreads == kThreadBatchCount || [self dataLoadComplete])
	{
		self.finishedThreads = 0;

		/* reload the table's data */
		[self.tableView reloadData];
		if([self dataLoadComplete])
		{
			/* stop the network indicator */
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

			/* flash the scroll indicators to show give the user an idea of how long the
			 * list is */
			[self.tableView flashScrollIndicators];
		}
	}
}

#pragma mark -
#pragma mark Modal ComposeStatusViewController

/* show a modal view controller that will allow a user to compose a twitter status */
- (void)presentUpdateStatusController
{
	ComposeStatusViewController *statusViewController = [[ComposeStatusViewController alloc] initWithNibName:ComposeStatusViewControllerNibName
	                                                                               bundle:[NSBundle mainBundle]];
	statusViewController.delegate = self;
	[self.navigationController presentModalViewController:statusViewController animated:YES];
	[statusViewController release];
}

/* ComposeStatusViewControllerDelegate protocol */
- (void)didFinishComposing:(ComposeStatusViewController *)viewController
{
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark Table view methods

/* Customize the number of rows per section */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [self.users count];
	return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return kCustomRowHeight;
}

- (UITableViewCell *)placeHolderCellForTableView:(UITableView *)tableView
{
	static NSString *PlaceHolderIdentifier = @"PlaceHolder";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceHolderIdentifier];
	if(cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceHolderIdentifier] autorelease];
		cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	cell.detailTextLabel.text = NSLocalizedString(LoadingKey, @"");
	return cell;
}

/* Customize the appearance of table view cells. */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"ListCell";

	int peopleCount = [self.users count];
	int idCount = [self.userIdArray count];
	/* if this is the first row and there are no people to display yet
	 * but there should be, display a cell that indicates data is loading
	 */
	if(peopleCount == 0 && indexPath.row == 0 && idCount > 0)
	{
		return [self placeHolderCellForTableView:tableView];
	}

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if(cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleBlue;
	}
	/* Leave cells empty if there's no data yet */
	if(peopleCount > 0 && indexPath.row < peopleCount)
	{
		/* Set up the cell... */
		User *user = [self.users objectAtIndex:indexPath.row];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		cell.textLabel.text = user.screen_name;
		/* Only load cached images; defer new downloads until scrolling ends */
		if(!user.image)
		{
			/* first check the database */
			UIImage *anImage = [dataAccessHelper initImageForUserId:user.user_id];
			if(!anImage)
			{
				if(self.tableView.dragging == NO && self.tableView.decelerating == NO)
				{
					/* if there was no image in the database
					 * and the tableview is not dragging or decelerating
					 * start to download the image
					 */
					[self startIconDownload:user forIndexPath:indexPath];
				}

				/* if a download is deferred or in progress, return a placeholder
				 * image */
				cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];
			}
			else
			{
				user.image = anImage;
				[anImage release];
				cell.imageView.image = user.image;
			}
		}
		else
		{
			cell.imageView.image = user.image;
		}
	}
	return cell;
}

/* override didSelectRowAtIndexPath to push a StatusViewController onto the navigation stack when a
 * row is selected */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(!IsEmpty(self.users) > 0)
	{
		/* get the correct user out of the people array and initialize the status view
		 * controller for that user */
		User *user = [users objectAtIndex:indexPath.row];
		StatusViewController *statusViewController = [[StatusViewController alloc] initWithUser:user dataAccessHelper:dataAccessHelper];

		/* push the new view controller onto the navigation stack */
		[self.navigationController pushViewController:statusViewController animated:YES];
		[statusViewController release];
	}
}

#pragma mark -
#pragma mark Table cell image support

- (void)startIconDownload:(User *)aUser forIndexPath:(NSIndexPath *)indexPath
{
	/* check for a download in progress for the indexPath
	 * if there isn't one, create one and start the download
	 */
	IconDownloader *iconDownloader = [imageDownloadsInProgress objectForKey:indexPath];
	if(iconDownloader == nil)
	{
		iconDownloader = [[IconDownloader alloc] init];
		iconDownloader.user = aUser;
		iconDownloader.indexPathInTableView = indexPath;
		iconDownloader.delegate = self;
		[imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];
		[iconDownloader startDownload];
		[iconDownloader release];
	}
}

/* this method is used in case the user scrolled into a set of cells that don't have their app icons
 * yet */
- (void)loadImagesForOnscreenRows
{
	if(!IsEmpty(self.userIdArray) > 0)
	{
		NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
		for(NSIndexPath *indexPath in visiblePaths)
		{
			User *user = [self.users objectAtIndex:indexPath.row];
			if(!user.image)
			{
				/* avoid the app icon download if the app already has an icon */
				[self startIconDownload:user forIndexPath:indexPath];
			}
		}
	}
}

/* called by our ImageDownloader when an icon is ready to be displayed */
- (void)imageDidLoad:(NSIndexPath *)indexPath
{
	IconDownloader *iconDownloader = [imageDownloadsInProgress objectForKey:indexPath];
	if(iconDownloader != nil)
	{
		UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:iconDownloader.indexPathInTableView];

		/* Display the newly loaded image */
		User *user = iconDownloader.user;
		[dataAccessHelper saveOrUpdateUser:user];
		cell.imageView.image = user.image;
	}
	[imageDownloadsInProgress removeObjectForKey:indexPath];
}

#pragma mark -
#pragma mark Deferred image loading (UIScrollViewDelegate)

/* Load images for all onscreen rows when scrolling is finished */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	if(!decelerate)
	{
		[self loadImagesForOnscreenRows];
	}
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
	[self loadImagesForOnscreenRows];
}

#pragma mark -
#pragma mark SA_OAuthTwitterEngineDelegate
- (void)storeCachedTwitterOAuthData:(NSString *)data forUsername:(NSString *)username
{
	[CredentialHelper saveAuthData:data];
	[CredentialHelper saveUsername:username];
}

- (NSString *)cachedTwitterOAuthDataForUsername:(NSString *)username
{
	return [CredentialHelper retrieveAuthData];
}

- (void)authSucceededForEngine
{
	if( IsEmpty(users) )
	{
		[self synchronousLoadTwitterData];
	}
}

- (void)deauthorizeEngine
{
	[self.engine clearAccessToken];
}

#pragma mark -
#pragma mark EngineDelegate

/* These delegate methods are called after a connection has been established */
- (void)requestSucceeded:(NSString *)connectionIdentifier
{
	NSLog(@"Request succeeded %@, response pending.", connectionIdentifier);
}

- (void)requestFailed:(NSString *)connectionIdentifier withError:(NSError *)error
{
	NSLog(@"Request failed %@, with error %@.", connectionIdentifier, [error localizedDescription]);
}

- (void)infoRecievedForUser:(User *)user
{
	[dataAccessHelper saveOrUpdateUser:user];
	[self.users addObject:user];
}

- (void)userInfoReceived:(NSDictionary *)userInfo forRequest:(NSString *)connectionIdentifier
{
	User *user = [[User alloc] initWithInfo:userInfo];
	/* this user is not yet in the database */
	if([user isValid])
	{
		[self infoRecievedForUser:user];
	}
	[self didFinishLoadingUser];
	[user release];
}

@end


text:
<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Common\Paginator;
use AppBundle\Common\ArrayToolkit;
use Biz\Role\Util\PermissionBuilder;
use Symfony\Component\HttpFoundation\Request;
use Topxia\Service\Common\ServiceKernel;

class RoleController extends BaseController
{
    public function indexAction(Request $request)
    {
        $fields = $request->query->all();
        $fields = ArrayToolkit::filter($fields, array(
            'keyword' => '',
            'keywordType' => '',
        ));
        $conditons = array();

        if (isset($fields['keywordType']) && !empty($fields['keywordType'])) {
            $conditons[$fields['keywordType']] = $fields['keyword'];
        }
        $paginator = new Paginator(
            $this->get('request'),
            $this->getRoleService()->searchRolesCount($conditons),
            30
        );

        $roles = $this->getRoleService()->searchRoles(
            $conditons,
            'created',
            $paginator->getOffsetCount(),
            $paginator->getPerPageCount()
        );

        $userIds = ArrayToolkit::column($roles, 'createdUserId');
        $users = $this->getUserService()->findUsersByIds($userIds);
        $users = ArrayToolkit::index($users, 'id');

        return $this->render('admin/role/index.html.twig', array(
            'roles' => $roles,
            'users' => $users,
            'paginator' => $paginator,
        ));
    }

    public function createAction(Request $request)
    {
        if ('POST' == $request->getMethod()) {
            $params = $request->request->all();
            $params['data'] = json_decode($params['data'], true);
            $this->getRoleService()->createRole($params);

            return $this->createJsonResponse(true);
        }

        $tree = PermissionBuilder::instance()->getOriginPermissionTree();
        $res = $tree->toArray();

        return $this->render('admin/role/role-modal.html.twig', array(
            'menus' => json_encode($res['children']),
            'model' => 'create',
        ));
    }

    public function editAction(Request $request, $id)
    {
        $role = $this->getRoleService()->getRole($id);

        if ('POST' == $request->getMethod()) {
            $params = $request->request->all();
            $params['data'] = json_decode($params['data'], true);
            $role = $this->getRoleService()->updateRole($id, $params);

            return $this->createJsonResponse(true);
        }

        $tree = PermissionBuilder::instance()->getOriginPermissionTree();

        if (!empty($role['data'])) {
            $tree->each(function (&$tree) use ($role) {
                if (in_array($tree->data['code'], $role['data'])) {
                    $tree->data['checked'] = true;
                }
            });
        }

        $originPermissions = $tree->toArray();

        return $this->render('admin/role/role-modal.html.twig', array(
            'menus' => json_encode($originPermissions['children']),
            'model' => 'edit',
            'role' => $role,
        ));
    }

    public function deleteAction(Request $request, $id)
    {
        $this->getRoleService()->deleteRole($id);

        return $this->createJsonResponse(array('result' => true));
    }

    public function showAction(Request $request, $id)
    {
        $role = $this->getRoleService()->getRole($id);
        $tree = PermissionBuilder::instance()->getOriginPermissionTree();

        $tree->each(function (&$tree) use ($role) {
            if (in_array($tree->data['code'], $role['data'])) {
                $tree->data['checked'] = true;
            }

            $tree->data['chkDisabled'] = 'true';
        });

        $treeArray = $tree->toArray();

        return $this->render('admin/role/role-modal.html.twig', array(
            'menus' => json_encode($treeArray['children']),
            'model' => 'show',
            'role' => $role,
        ));
    }

    public function checkNameAction(Request $request)
    {
        $name = $request->query->get('value');
        $exclude = $request->query->get('exclude');

        $avaliable = $this->getRoleService()->isRoleNameAvalieable($name, $exclude);

        if ($avaliable) {
            $response = array('success' => true, 'message' => '');
        } else {
            $response = array('success' => false, 'message' => '角色名称已存在');
        }

        return $this->createJsonResponse($response);
    }

    public function checkCodeAction(Request $request)
    {
        $code = $request->query->get('value');
        $exclude = $request->query->get('exclude');

        $avaliable = $this->getRoleService()->isRoleCodeAvalieable($code, $exclude);

        if ($avaliable) {
            $response = array('success' => true, 'message' => '');
        } else {
            $response = array('success' => false, 'message' => '编码已存在');
        }

        return $this->createJsonResponse($response);
    }

    protected function getRoleService()
    {
        return $this->createService('Role:RoleService');
    }

    protected function getAppService()
    {
        return $this->createService('CloudPlatform:AppService');
    }

    protected function getUserService()
    {
        return ServiceKernel::instance()->createService('User:UserService');
    }
}


text:
import ExtendableError from 'es6-error';

export class LoginError extends ExtendableError {
  constructor(endpointName = '', detail = '') {
    const message = `ANALYST-0000
    ${endpointName} to login failed
    should check whether your username or password wrong, or login API failed
    ${detail}`;
    super(message);
    this.detail = detail;
  }
}

export class RemoteAPIError extends ExtendableError {
  constructor(endpointName = '', detail = '') {
    const message = `ANALYST-0001
    ${endpointName} returning unexpected response
    should check the usage of api or whether api server was down
    ${detail}`;
    super(message);
    this.detail = detail;
  }
}

export class NotaJSONError extends ExtendableError {
  constructor(endpointName = '', responce = '') {
    const message = `ANALYST-0002
    ${endpointName} returning unexpected response: ${responce}
    maybe there are some cros or proxy problem, so it return a HTML or so?  `;
    super(message);
    this.detail = responce;
  }
}

export class NoTokenError extends ExtendableError {
  constructor(endpointName = '') {
    const message = `ANALYST-0003
    ${endpointName} that had some req send to, should have token but it don't have
    should check client-side query, weather it's carrying its token  `;
    super(message);
  }
}

export class NoIDError extends ExtendableError {
  constructor(idName = '') {
    const message = `ANALYST-0004
    ${idName} that had some req send to, should have been provided,
    or data you query can't be fetched from database  `;
    super(message);
  }
}


text:
package softuni.services.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import softuni.dto.binding.UserDto;
import softuni.dto.binding.Add.UserAddDto;
import softuni.dto.view.Query2.UserSoldProductsDto;
import softuni.dto.view.Query4.ProductListDto;
import softuni.dto.view.Query4.ProductsNameAndPriceDto;
import softuni.dto.view.Query4.UsersListDto;
import softuni.dto.view.Query4.UsersProductsDto;
import softuni.entities.Product;
import softuni.entities.User;
import softuni.io.ModelParser;
import softuni.repositories.ProductRepository;
import softuni.repositories.UserRepository;
import softuni.services.api.UserService;

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

@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final ProductRepository productRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository, ProductRepository productRepository) {
        this.userRepository = userRepository;
        this.productRepository = productRepository;
    }

    @Override
    public void save(UserAddDto userAddDto) {
        User user = ModelParser.getInstance().map(userAddDto, User.class);
        this.userRepository.saveAndFlush(user);
    }

    @Override
    public List<UserDto> findAll() {
        List<User> users = this.userRepository.findAll();
        List<UserDto> userDtos = new ArrayList<>();
        for (User user : users) {
            UserDto userDto = ModelParser.getInstance().map(user, UserDto.class);
            userDtos.add(userDto);
        }
        return userDtos;
    }

    @Override
    public List<UserSoldProductsDto> getUserSoldProducts() {
        List<User> users = this.userRepository.findBySoldProducts();
        List<UserSoldProductsDto> userSoldProductsDtos = new ArrayList<>();

        for (User user : users) {
            List<Product> delete = new ArrayList<>();
            for (Product product : user.getSoldProducts()) {
                if(product.getBuyer() == null){
                    delete.add(product);
                }
            }
            user.getSoldProducts().removeAll(delete);
            UserSoldProductsDto userSoldProductsDto = ModelParser.getInstance().map(user, UserSoldProductsDto.class);
            userSoldProductsDtos.add(userSoldProductsDto);
        }

        return userSoldProductsDtos;
    }

    @Override
    public UsersListDto getUsersBySoldProductsCount() {
        List<User> users = this.userRepository.findBySoldProductsCount();
        UsersListDto usersListDto = new UsersListDto();
        usersListDto.setUsersCount(users.size());
        List<UsersProductsDto> usersProductsDtos = new ArrayList<>();
        for (User user : users) {
            UsersProductsDto usersProductsDto = ModelParser.getInstance().map(user, UsersProductsDto.class);
            ProductListDto productListDto = usersProductsDto.getSoldProducts();
            List<Product> products = this.productRepository.findSoldProductsByUserId(user.getId());
            productListDto.setCount(products.size());
            List<ProductsNameAndPriceDto> productsNameAndPriceDtos = new ArrayList<>();
            for (Product product : products) {
                ProductsNameAndPriceDto productsNameAndPriceDto = ModelParser.getInstance().map(product, ProductsNameAndPriceDto.class);
                productsNameAndPriceDtos.add(productsNameAndPriceDto);
            }

            productListDto.setProducts(productsNameAndPriceDtos);
            usersProductsDtos.add(usersProductsDto);
        }

        usersListDto.setUsers(usersProductsDtos);
        return usersListDto;
    }
}


text:
// ======================================================================== //
// Copyright 2009-2013 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

#ifndef __EMBREE_IMAGE_H__
#define __EMBREE_IMAGE_H__

#include <vector>
#include <string>

#include "sys/platform.h"
#include "sys/ref.h"
#include "sys/filename.h"
#include "math/color.h"

namespace embree
{
  /* virtual interface to image */
  class Image : public RefCount {
  public:
    Image (size_t width, size_t height, const std::string& name) : width(width), height(height), name(name) {}
    virtual ~Image() {}
    virtual Color4 get(size_t x, size_t y) const = 0;
    virtual void   set(size_t x, size_t y, const Color4& c) = 0;
    void set(size_t x, size_t y, const Color& c) { set(x,y,Color4(c.r,c.g,c.b,1.0f)); }
  public:
    size_t width,height;
    std::string name;
  };

  /* main image class templated over element type */
  template<typename T>
    class ImageT : public Image {
  public:

    /*! create empty image */
    ImageT (size_t width = 0, size_t height = 0, const std::string& name = "")
      : Image(width,height,name)
    {
      data = (T*) malloc(width*height*sizeof(T));
      memset(data,0,width*height*sizeof(T));
    }

    /*! create image of constant color */
    ImageT (size_t width, size_t height, const T& color, const std::string& name = "")
      : Image(width,height,name)
    {
      data = (T*) malloc(width*height*sizeof(T));
      for (size_t i=0; i<width*height; i++) data[i] = color;
    }

    /*! initialize image from color data */
    ImageT (size_t width, size_t height, T* color, const bool copy = true, const std::string& name = "")
      : Image(width,height,name)
    {
      if (copy) {
        data = (T*) malloc(width*height*sizeof(T));
        for (size_t i=0; i<width*height; i++) data[i] = color[i];
      }
      else {
        data = color;
      }
    }

    /*! image destruction */
    virtual ~ImageT() {
      if (data) free(data); data = NULL;
    }

    /*! returns pixel color */
    __forceinline Color4 get(size_t x, size_t y) const {
      return Color4(data[y*width+x]);
    }

    /*! sets pixel */
    __forceinline void set(size_t x, size_t y, const Color4& c) {
      c.set(data[y*width+x]);
    }

    /*! returns data pointer of image */
    __forceinline void* ptr() {
      return (void*)data;
    }

    /*! returns and forgets about data pointer of image */
    __forceinline void* steal_ptr() {
      T* ptr = data;
      data = NULL;
      return (void*)ptr;
    }

  protected:
    T* data;
  };

  /*! Shortcuts for common image types. */
  typedef ImageT<Col3c> Image3c;
  typedef ImageT<Col3f> Image3f;
  typedef ImageT<Col4c> Image4c;
  typedef ImageT<Col4f> Image4f;

  /*! Loads image from PPM file. */
  Ref<Image> loadPPM(const FileName& fileName);

  /*! Loads image from PFM file. */
  Ref<Image> loadPFM(const FileName& fileName);

  /*! Loads image from EXR file. */
  Ref<Image> loadExr(const FileName& fileName);

  /*! Loads image using ImageMagick. */
  Ref<Image> loadMagick(const FileName& fileName);

  /*! Loads image from file. Format is auto detected. */
  Ref<Image> loadImage(const FileName& filename, bool cache = false);

  /*! Store image to PPM file. */
  void storePPM(const Ref<Image>& img, const FileName& fileName);

  /*! Store image to PFM file. */
  void storePFM(const Ref<Image>& img, const FileName& fileName);

  /*! Store image to TGA file. */
  void storeTga(const Ref<Image>& img, const FileName& fileName);

  /*! Store image to EXR file. */
  void storeExr(const Ref<Image>& img, const FileName& fileName);

  /*! Store image to file using ImageMagick. */
  void storeMagick(const Ref<Image>& img, const FileName& fileName);

  /*! Store image to file. Format is auto detected. */
  void storeImage(const Ref<Image>& image, const FileName& filename);
}

#endif


text:
Capistrano::Configuration.instance(:must_exist).load do

  def look_for_db_changes
    fetch(:db_changed?, nil) || set(:db_changed?) { check_for_changes('db/migrate') }
  end

  def look_for_stylesheet_changes
    fetch(:stylesheets_changed?, nil) || set(:stylesheets_changed?) { check_for_changes('public/stylesheets') }
  end

  def check_for_changes(dir)
    result = capture("cd #{current_release} && git diff-tree `cat #{previous_release}/REVISION` #{branch} -- #{dir} | wc -l").to_i > 0
    puts "Looking for changes in #{dir}... [ #{result ? 'yes' : 'no'} ]"
    result
  end

end


text:
<?php

namespace Zephir\FileSystem;

interface FileSystemInterface
{
    /**
     * Checks if the filesystem is initialized.
     *
     * @return bool
     */
    public function isInitialized();

    /**
     * Initialize the filesystem.
     */
    public function initialize();

    /**
     * Checks whether a temporary entry does exist.
     *
     * @param string $path
     *
     * @return bool
     */
    public function exists($path);

    /**
     * Creates a directory inside the temporary container.
     *
     * @param string $path
     *
     * @return bool
     */
    public function makeDirectory($path);

    /**
     * Returns a temporary entry as an array.
     *
     * @param string $path
     *
     * @return array
     */
    public function file($path);

    /**
     * Requires a file from the temporary directory.
     *
     * @param string $path
     *
     * @return mixed
     */
    public function requireFile($path);

    /**
     * Attempts to remove recursively the temporary directory with all subdirectories and files.
     */
    public function clean();

    /**
     * Writes data into a temporary entry.
     *
     * @param string $path
     * @param string $data
     */
    public function write($path, $data);

    /**
     * Writes data from a temporary entry.
     *
     * @param string $path
     *
     * @return string
     */
    public function read($path);

    /**
     * Deletes a temporary entry.
     *
     * @param string $path
     */
    public function delete($path);

    /**
     * Generate a hash value using the contents of a given file.
     *
     * @param string $algorithm
     * @param string $sourceFile
     * @param bool   $useCache
     *
     * @return string
     */
    public function getHashFile($algorithm, $sourceFile, $useCache = false);

    /**
     * Returns the modification time of a temporary entry.
     *
     * @param string $path
     *
     * @return int
     */
    public function modificationTime($path);

    /**
     * Executes a command and saves the result into a temporary entry.
     *
     * @param string $command
     * @param string $descriptor
     * @param string $destination
     */
    public function system($command, $descriptor, $destination);

    /**
     * Normalizes path to be used as a temporary entry.
     *
     * @param string $path
     *
     * @return string
     */
    public function normalizePath($path);
}


text:
/*
Theme Name:         Third Rail
Theme URI:          http://thirdrailrep.org/
Github Theme URI:   https://github.com/rollandwalsh/third-rail
Description:        ThirdRail is a WordPress theme built for Third Rail Repertory Theatre
Version:            1.0.0
Author:             Rolland Walsh
Author URI:         http://rollandwalsh.com/

License:            MIT License
License URI:        http://www.opensource.org/licenses/mit-license.php
*/

/* ----------------------------------------------------------------------------

  Unfortunately WordPress will require a style.css file
  located in the theme's root folder for stuff to work.

  However, we will not be using vanilla CSS. We're using Sass.

  Sass is a superset of CSS that adds in amazing features
  such as variables, nested selectors and loops. It's also
  the easiest way to customize Foundation.

  All Sass files are located in the /scss folder.

  Please read the README.md file before getting started. More info on how
  to use Sass with Foundation can be found here:
  http://foundation.zurb.com/docs/sass.html

  If you for some reason would like to write plain css instead of using Sass,
  you could just enqueue this file (style.css) to the header and add your styles in this file

---------------------------------------------------------------------------- */


text:
import org.junit.jupiter.api.*;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.*;
import java.io.*;
import com.example.pinpoint.*;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.pinpointsmsvoice.PinpointSmsVoiceClient;

import java.util.*;

@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class AmazonPinpointTest {

    private static PinpointClient pinpoint;
    private static PinpointSmsVoiceClient voiceClient;
    private static S3Client s3Client;
    private static Region region;
    private static String appName = "";
    private static String appId = ""; //gets set in test 2
    private static String endpointId2 = ""; //gets set in test 3
    private static String bucket = "";
    private static String path= "";
    private static String roleArn= "";
    private static String segmentId= ""; // set in a test 7
    private static String userId = "";
    private static String s3BucketName = "";
    private static String iamExportRoleArn = "";
    private static String existingApplicationId = "";
    private static String filePath = "";
    private static String subject = "";
    private static String senderAddress = "";
    private static String toAddress = "";
    private static String originationNumber = "";
    private static String destinationNumber = "";
    private static String destinationNumber1 = "";
    private static String message = "";

    @BeforeAll
    public static void setUp() throws IOException {

        // Run tests on Real AWS Resources
        region = Region.US_EAST_1;
        pinpoint = PinpointClient.builder()
                .region(region)
                .credentialsProvider(ProfileCredentialsProvider.create())
                .build();

        s3Client = S3Client.builder()
                .region(region)
                .credentialsProvider(ProfileCredentialsProvider.create())
                .build();

        // Set the VoiceClient.
        // Set the content type to application/json.
        List<String> listVal = new ArrayList<>();
        listVal.add("application/json");

        Map<String, List<String>> values = new HashMap<>();
        values.put("Content-Type", listVal);

        ClientOverrideConfiguration config2 = ClientOverrideConfiguration.builder()
                .headers(values)
                .build();

        voiceClient = PinpointSmsVoiceClient.builder()
                .overrideConfiguration(config2)
                .region(Region.US_EAST_1)
                .credentialsProvider(ProfileCredentialsProvider.create())
                .build();

        try (InputStream input = AmazonPinpointTest.class.getClassLoader().getResourceAsStream("config.properties")) {

            Properties prop = new Properties();
             if (input == null) {
                System.out.println("Sorry, unable to find config.properties");
                return;
            }

            //load a properties file from class path, inside static method
            prop.load(input);

            // Populate the data members required for all tests
            appName = prop.getProperty("appName");
            bucket= prop.getProperty("bucket");
            path= prop.getProperty("path");
            roleArn= prop.getProperty("roleArn");
            userId = prop.getProperty("userId");
            s3BucketName = prop.getProperty("s3BucketName");
            s3BucketName = prop.getProperty("s3BucketName");
            iamExportRoleArn = prop.getProperty("iamExportRoleArn");
            existingApplicationId= prop.getProperty("existingApplicationId");
            filePath= prop.getProperty("filePath");
            subject = prop.getProperty("subject");
            senderAddress = prop.getProperty("senderAddress");
            toAddress = prop.getProperty("toAddress");
            originationNumber= prop.getProperty("originationNumber");
            destinationNumber= prop.getProperty("destinationNumber");
            destinationNumber1 = prop.getProperty("destinationNumber1");
            message= prop.getProperty("message");

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Test
    @Order(1)
    public void whenInitializingAWSPinpointService_thenNotNull() {
        assertNotNull(pinpoint);
        assertNotNull(voiceClient);
        assertNotNull(s3Client);
        System.out.println("Test 1 passed");
    }

    @Test
    @Order(2)
    public void CreateApp() {

      appId = CreateApp.createApplication(pinpoint, appName);
      assertTrue(!appId.isEmpty());
      System.out.println("Test 2 passed");
    }

    @Test
    @Order(3)
    public void UpdateEndpoint()
    {
       EndpointResponse response = UpdateEndpoint.createEndpoint(pinpoint, appId);
       endpointId2 = response.id() ;
       assertTrue(!endpointId2.isEmpty());
       System.out.println("Test 3 passed");
    }

    @Test
    @Order(4)
    public void LookUpEndpoint()
    {
        assertDoesNotThrow(() ->LookUpEndpoint.lookupPinpointEndpoint(pinpoint, appId, endpointId2));
        System.out.println("Test 4 passed");
    }

    @Test
    @Order(5)
    public void AddExampleUser()
    {
        assertDoesNotThrow(() ->AddExampleUser.updatePinpointEndpoint(pinpoint,appId,endpointId2));
       System.out.println("Test 5 passed");
    }

    @Test
    @Order(6)
    public void AddExampleEndpoints()
    {
        assertDoesNotThrow(() -> AddExampleEndpoints.updateEndpointsViaBatch(pinpoint,appId));
        System.out.println("Test 6 passed");
    }

    @Test
    @Order(7)
    public void DeleteEndpoint() {
        assertDoesNotThrow(() ->DeleteEndpoint.deletePinEncpoint(pinpoint, appId, endpointId2));
        System.out.println("Test 7 passed");
    }

    @Test
    @Order(8)
    public void SendMessage() {
       assertDoesNotThrow(() ->SendMessage.sendSMSMessage(pinpoint, message, existingApplicationId, originationNumber, destinationNumber));
       System.out.println("Test 8 passed");
    }

    @Test
    @Order(9)
   public void ImportSegments() {
        assertDoesNotThrow(() -> SendMessageBatch.sendSMSMessage(pinpoint, message, "2fdc4442c6a2483f85eaf7a943054815", originationNumber, destinationNumber, destinationNumber));
        System.out.println("Test 8 passed");
    }

    @Test
    @Order(10)
    public void ListSegments() {
        assertDoesNotThrow(() -> ListSegments.listSegs(pinpoint, appId));
        System.out.println("Test 10 passed");
    }

    @Test
    @Order(11)
    public void CreateSegment() {

        SegmentResponse createSegmentResult =  CreateSegment.createSegment(pinpoint, existingApplicationId);
        segmentId =  createSegmentResult.id();
        assertTrue(!segmentId.isEmpty());
        System.out.println("Test 11 passed");
   }

    @Test
    @Order(12)
    public void CreateCampaign() {

       assertDoesNotThrow(() -> CreateCampaign.createPinCampaign(pinpoint, existingApplicationId, segmentId));
       System.out.println("Test 12 passed");
    }

    @Test
    @Order(13)
    public void ExportEndpoints() {

        assertDoesNotThrow(() ->  ExportEndpoints.exportAllEndpoints(pinpoint, s3Client, existingApplicationId, s3BucketName, filePath, iamExportRoleArn));
        System.out.println("Test 13 passed");
    }

    @Test
    @Order(14)
    public void SendEmailMessage() {
        assertDoesNotThrow(() -> SendEmailMessage.sendEmail(pinpoint, subject, existingApplicationId,  senderAddress, toAddress));
        System.out.println("Test 14 passed");
   }

    @Test
    @Order(15)
   public void SendVoiceMessage() {
        assertDoesNotThrow(() ->SendVoiceMessage.sendVoiceMsg(voiceClient, originationNumber, destinationNumber));
        System.out.println("Test 15 passed");
   }

    @Test
    @Order(16)
   public void ListEndpointIds() {
        assertDoesNotThrow(() ->ListEndpointIds.listAllEndpoints(pinpoint, existingApplicationId, userId));
        System.out.println("Test 16 passed");
   }

   @Test
    @Order(17)
    public void DeleteApp() {
       assertDoesNotThrow(() ->DeleteApp.deletePinApp(pinpoint, appId));
         System.out.println("Test 17 passed");
    }
}


text:
package io.github.pauljamescleary.petstore.domain
package pets

import cats.Functor
import cats.data._
import cats.Monad
import cats.syntax.all._

/**
  * The entry point to our domain, works with repositories and validations to implement behavior
  * @param repository where we get our data
  * @param validation something that provides validations to the service
  * @tparam F - this is the container for the things we work with, could be scala.concurrent.Future, Option, anything
  *           as long as it is a Monad
  */
class PetService[F[_]](
    repository: PetRepositoryAlgebra[F],
    validation: PetValidationAlgebra[F],
) {
  def create(pet: Pet)(implicit M: Monad[F]): EitherT[F, PetAlreadyExistsError, Pet] =
    for {
      _ <- validation.doesNotExist(pet)
      saved <- EitherT.liftF(repository.create(pet))
    } yield saved

  /* Could argue that we could make this idempotent on put and not check if the pet exists */
  def update(pet: Pet)(implicit M: Monad[F]): EitherT[F, PetNotFoundError.type, Pet] =
    for {
      _ <- validation.exists(pet.id)
      saved <- EitherT.fromOptionF(repository.update(pet), PetNotFoundError)
    } yield saved

  def get(id: Long)(implicit F: Functor[F]): EitherT[F, PetNotFoundError.type, Pet] =
    EitherT.fromOptionF(repository.get(id), PetNotFoundError)

  /* In some circumstances we may care if we actually delete the pet; here we are idempotent and do not care */
  def delete(id: Long)(implicit F: Functor[F]): F[Unit] =
    repository.delete(id).as(())

  def list(pageSize: Int, offset: Int): F[List[Pet]] =
    repository.list(pageSize, offset)

  def findByStatus(statuses: NonEmptyList[PetStatus]): F[List[Pet]] =
    repository.findByStatus(statuses)

  def findByTag(tags: NonEmptyList[String]): F[List[Pet]] =
    repository.findByTag(tags)
}

object PetService {
  def apply[F[_]](
      repository: PetRepositoryAlgebra[F],
      validation: PetValidationAlgebra[F],
  ): PetService[F] =
    new PetService[F](repository, validation)
}


text:
using Pear.InteractionEngine.EventListeners;
using Pear.InteractionEngine.Interactions;
using Pear.InteractionEngine.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Pear.InteractionEngine.Interactions
{
	public class NamedEventListener : MonoBehaviour
	{
		// Name of the event
		public string EventName;

		// Reacts to the event
		public MonoBehaviour EventListener;

		// Should the event listener script be duplicated
		public bool DuplicateEventListener = true;

		// Used for serialization, this variable stores
		// the type of property (e.g. float, bool, ect)
		// that the event listener fires
		public string EventListenerPropertyType;

		// Determines when the listener should recieve events
		public ReceiveEventStates ReceiveEventState = ReceiveEventStates.WhenObjectActive;

		private IEventListenerDispatcher _eventListenerDispatcher;

		void Awake()
		{
			if (!IsValid())
			{
				Debug.LogError("Named event is invalid for object " + name);
				return;
			}

			if (EventListener.gameObject != gameObject)
				CopyEventListener(EventListener);

			Type eventListnerPropertyType = Type.GetType(EventListenerPropertyType);
			Type eventListenerDispatcherType = typeof(EventListenerDispatcher<>);
			Type instantiableEventListenerDispatcherType = eventListenerDispatcherType.MakeGenericType(eventListnerPropertyType);
			_eventListenerDispatcher = (IEventListenerDispatcher)Activator.CreateInstance(instantiableEventListenerDispatcherType, EventName, EventListener, gameObject, ReceiveEventState);
		}

		/// <summary>
		/// Copies all named event listeners from one object to another
		/// </summary>
		/// <param name="copyFrom">Obj to copy from</param>
		/// <param name="copyTo">Obj to copy to</param>
		public static void CopyAll(GameObject copyFrom, GameObject copyTo)
		{
			// Deactivate this object so we can copy component values without
			// the component's Awake function being called
			bool originalActiveState = copyTo.activeSelf;
			copyTo.SetActive(false);

			// Copy listeners from our placeholder
			foreach (NamedEventListener interaction in copyFrom.GetComponents<NamedEventListener>())
			{
				NamedEventListener newInteraction = copyTo.AddComponent<NamedEventListener>();
				newInteraction.CopyFrom(interaction);
			}

			// Reset the original state
			copyTo.SetActive(originalActiveState);
		}

		/// <summary>
		/// Copy listener properties from the given listener
		/// </summary>
		/// <param name="copyFrom">listener to copy properties from</param>
		public void CopyFrom(NamedEventListener copyFrom)
		{
			if (copyFrom == null || !copyFrom.IsValid())
			{
				UnityEngine.Debug.LogError("Invalid interaction to copy from.");
				return;
			}

			EventName = copyFrom.EventName;
			CopyEventListener(copyFrom.EventListener);
			EventListenerPropertyType = copyFrom.EventListenerPropertyType;
			ReceiveEventState = copyFrom.ReceiveEventState;
		}

		private void OnEnable()
		{
			_eventListenerDispatcher.Enabled = true;
		}

		private void OnDisable()
		{
			_eventListenerDispatcher.Enabled = false;
		}

		private void CopyEventListener(MonoBehaviour eventListener)
		{
			EventListener = DuplicateEventListener ? gameObject.AddComponentFrom(eventListener) : eventListener;
		}

		/// <summary>
		/// Tells whether this event listener is valid
		/// </summary>
		/// <returns>True if event listener is valid. False otherwise.</returns>
		private bool IsValid()
		{
			if (EventListener == null)
			{
				Debug.LogError("The EventHandler needs to be set.");
				return false;
			}

			if (EventListenerPropertyType == null)
			{
				Debug.LogError("EventListener property type not set.");
				return false;
			}

			Type eventListenerPropertyType = Type.GetType(EventListenerPropertyType);
			if (eventListenerPropertyType == null)
			{
				Debug.LogError("EventListener property type is invalid or null.");
				return false;
			}

			return true;
		}

		public interface IEventListenerDispatcher
		{
			bool Enabled { get; set; }
		}

		public class EventListenerDispatcher<T> : IEventListenerDispatcher
		{
			private string EventName;
			private IEventListener<T> EventListener;
			private GameObject GameObject;
			public ReceiveEventStates ReceiveEventState;

			private bool _enabled = false;
			public bool Enabled
			{
				get { return _enabled; }

				set
				{
					if(value != _enabled)
					{
						if(value)
						{
							EventToEventListenerDispatcher<T>.AddListener(EventName, EventListener, GameObject, ReceiveEventState);
						}
						else
						{
							EventToEventListenerDispatcher<T>.RemoveListener(EventName, EventListener, GameObject);
						}
					}

					_enabled = value;
				}
			}

			public EventListenerDispatcher(string eventName, IEventListener<T> eventListener, GameObject gameObject, ReceiveEventStates receiveEventState)
			{
				EventName = eventName;
				EventListener = eventListener;
				GameObject = gameObject;
				ReceiveEventState = receiveEventState;
			}
		}
	}
}


text:
angular.module('app', ['ui.router'])
  .config(function($stateProvider, $urlRouterProvider) {

    $stateProvider
      .state('index', {
        url: '',
        template: 'index'
      })
      .state('contacts', {
        url: '/contacts',
        abstract: true,
        templateUrl: 'partials/contacts.html',
        controller: function($scope) {
          $scope.contacts = [{
            id: 0,
            name: "Alice"
          }, {
            id: 1,
            name: "Bob"
          }];
        }
      })
      .state('contacts.list', {
        // loaded into ui-view of parent's template
        url: '/',
        templateUrl: 'partials/contacts.list.html'
      })
      .state('contacts.detail', {
        // loaded into ui-view of parent's template
        url: '/:id',
        templateUrl: 'partials/contacts.detail.html',
        controller: function($scope, $stateParams) {
          $scope.person = $scope.contacts[$stateParams.id];
        }
      });
  })
  .run(function($rootScope) {
    // fired when the transition begins.
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {

      // これでstateChangeを防ぐことができる
      // event.preventDefault();

      console.log(`${event.name}: ${fromState.name}(${fromState.url}) -> ${toState.name}(${toState.url})`);

    });

    // fired once the state transition is complete.
    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
      console.log(`${event.name}: ${fromState.name}(${fromState.url}) -> ${toState.name}(${toState.url})`);
    });
    // fired once the view begins loading, before the DOM is rendered.
    $rootScope.$on('$viewContentLoading', function(event, viewConfig) {
      console.log(`${event.name}:`, viewConfig);
    });

    // fired once the view is loaded, after the DOM is rendered
    $rootScope.$on('$viewContentLoaded', function(event) {
      console.log(`${event.name}: $scopeが使えるよー`);
    });

    // fired when the not fount state name
    $rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams) {
      console.log(`${event.name}: ${unfoundState.to} ${unfoundState.toParams} ${unfoundState.options}`);
    });

    // fired when an error occurs during transition.
    $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
      console.log(`${event.name}: ${toState.name}(${toState.url}): ${error}`);
    });
  });


text:
package com.github.reflectoring.infiniboard.quartermaster.testframework;

import static org.assertj.core.api.Assertions.assertThat;

import org.springframework.hateoas.PagedResources;
import org.springframework.test.web.servlet.ResultMatcher;

/** Collection of ResultMatchers to be used in MockMvc's fluent API. */
public class ResultMatchers {

  private ResultMatchers() {}

  /**
   * Tests if the response contains the JSON representation of an object of the given type.
   *
   * @param clazz the class of the expected object.
   * @param <T> the type of the expected object.
   * @return ResultMatcher that performs the test described above.
   */
  public static <T> ResultMatcher containsResource(Class<T> clazz) {
    return result -> {
      String json = result.getResponse().getContentAsString();
      try {
        T object = JsonHelper.fromJson(json, clazz);
        assertThat(object).isNotNull();
      } catch (Exception e) {
        throw new RuntimeException(
            String.format("expected JSON representation of class %s but found '%s'", clazz, json),
            e);
      }
    };
  }

  /**
   * Tests if the response contains the JSON representation of a paging result with items of the
   * given type.
   *
   * @param clazz the class of the expected paged objects.
   * @param <T> the type of the expected paged objects.
   * @return ResultMatcher that performs the test described above.
   */
  public static <T> ResultMatcher containsPagedResources(Class<T> clazz) {
    return result -> {
      String json = result.getResponse().getContentAsString();
      try {
        PagedResources<T> pagedResources = JsonHelper.fromPagedResourceJson(json, clazz);
        assertThat(pagedResources).isNotNull();
      } catch (Exception e) {
        throw new RuntimeException(
            String.format("expected JSON representation of class %s but found '%s'", clazz, json),
            e);
      }
    };
  }
}


text:
using System;
using System.Threading;

namespace Avro.ipc
{
    public class CountdownLatch : IDisposable
    {
        private ManualResetEvent evt;
        private int currentCount;

        public int CurrentCount
        {
            get { return currentCount; }
        }

        public CountdownLatch(int count)
        {
            currentCount = count;
            evt = new ManualResetEvent(false);
        }

        public void Signal()
        {
            if (Interlocked.Decrement(ref currentCount) == 0)
                evt.Set();
        }

        public void Wait()
        {
            evt.WaitOne();
        }

        public bool Wait(int milliseconds)
        {
            return evt.WaitOne(milliseconds);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~CountdownLatch()
        {
            // Finalizer calls Dispose(false)
            Dispose(false);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // free managed resources
                if (evt != null)
                {
                    evt.Close();
                    evt = null;
                }
            }
        }
    }
}


text:
<?php
namespace StockRest\Entity;

use Doctrine\ORM\Tools\Pagination\Paginator;

/**
 * Entity abstract with some methods that other classes can use it.
 *
 * @author Thiago Pelizoni <thiago.pelizoni@gmail.com>
 */
abstract class EntityAbstract
{
    /**
     * Default class constructor. This model can be filled automatically
     * with the form data.
     *
     * @param   array   $data
     * @return  StockRest\Entity\EntityAbstract
     */
    public function __construct($data = null)
    {
        $this->exchangeArray($data);

        return $this;
    }

    /**
     * Fill this object from an array
     *
     * @return StockRest\Entity\EntityAbstract
     */
    public function exchangeArray($data)
    {
        if ($data != null) {
            foreach ($data as $attribute => $value) {
                if (! property_exists($this, $attribute)) {
                    continue;
                }
                $this->$attribute = $value;
            }
        }

        return $this;
    }

    /**
     * Magic method used to set a value in a attribute.
     *
     * @param   string $attribute
     * @param   mixed  $value
     * @return  StockRest\Entity\EntityAbstract;
     */
    public function __set($attribute, $value)
    {
        $this->$attribute = $value;

        return $this;
    }

    /**
     * Magic method used to return a value of this class
     *
     * @param   string $attribute
     * @return  StockRest\Entity\EntityAbstract;
     */
    public function __get($attribute)
    {
        return $this->$attribute;
    }

    /**
     * Return this object in array form.
     *
     * @return array
     */
    public function toArray()
    {
        $data = get_object_vars($this);

        foreach ($data as $attribute => $value) {
            if (is_object($value)) {
                $data[$attribute] = get_object_vars($value);
            }
        }

        return $data;
    }

    /**
     * Method to find one or more records where will be returning a Doctrine
     * Paginator object.
     *
     * @return Doctrine\ORM\Tools\Pagination\Paginator
     */
    public function find($entityManager, $params)
    {
        $firstResult = (int) isset($params['firstResult']) ?
            $params['firstResult'] : 1;

        $maxResults  = (int) isset($params['maxResults']) ?
            $params['maxResults'] : 10;

        if ($firstResult < 1) {
            $firstResult = 1;
        }

        if ($maxResults < 1 || $maxResults > 500) {
            $maxResults = 10;
        }

        $alias = 'entity';

        $query = $entityManager->createQueryBuilder($alias)
           ->setFirstResult($firstResult)
           ->setMaxResults($maxResults);

        $query = $this->getCriteria($query, $params, $alias);

        $orderBy  = isset($params['orderBy']) ?
            strtolower($params['orderBy']) : null;

        if ($orderBy != null) {
            $typeOfOrder = isset($params['typeOfOrder']) ?
                strtolower($params['typeOfOrder']) : 'asc';

            if ($typeOfOrder != 'asc' && $typeOfOrder != 'desc') {
                $typeOfOrder = 'asc';
            }
            $query->orderBy("{$alias}.{$orderBy}", $typeOfOrder);
        }

        $paginator = new Paginator($query);

        return $paginator;
    }

    /**
     * Processes the parameters to perform a search with the specific type
     * according to the parameters passed.
     *
     * @return Doctrine\ORM\QueryBuilder
     */
    private function getCriteria($query, $params, $alias)
    {
        $queryType = isset($params['queryType'])
            ? strtolower($params['queryType']) : 'and';

        if ($queryType != 'and' && $queryType != 'or') {
            $queryType = 'and';
        }

        foreach ($params as $attribute => $value) {
            if (! property_exists($this, $attribute)) {
                continue;
            }

            if ($value == null) {
                continue;
            }

            $value = strtoupper($value);
            $value = preg_replace('/[^[:ascii:]]/', '%', $value);
            $value = preg_replace('/[%]{1,}/', '%', $value);

            $criteria = "UPPER({$alias}.{$attribute}) LIKE '%{$value}%'";

            if ($queryType == 'and') {
                $query->andWhere($criteria);
            } else {
                $query->orWhere($criteria);
            }
        }

        return $query;
    }
}


text:
package fake

import (
	api "k8s.io/kubernetes/pkg/api"
	v1 "k8s.io/kubernetes/pkg/api/v1"
	core "k8s.io/kubernetes/pkg/client/testing/core"
	labels "k8s.io/kubernetes/pkg/labels"
	watch "k8s.io/kubernetes/pkg/watch"
)

// FakeServiceAccounts implements ServiceAccountInterface
type FakeServiceAccounts struct {
	Fake *FakeCore
	ns   string
}

func (c *FakeServiceAccounts) Create(serviceAccount *v1.ServiceAccount) (result *v1.ServiceAccount, err error) {
	obj, err := c.Fake.
		Invokes(core.NewCreateAction("serviceaccounts", c.ns, serviceAccount), &v1.ServiceAccount{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1.ServiceAccount), err
}

func (c *FakeServiceAccounts) Update(serviceAccount *v1.ServiceAccount) (result *v1.ServiceAccount, err error) {
	obj, err := c.Fake.
		Invokes(core.NewUpdateAction("serviceaccounts", c.ns, serviceAccount), &v1.ServiceAccount{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1.ServiceAccount), err
}

func (c *FakeServiceAccounts) Delete(name string, options *api.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(core.NewDeleteAction("serviceaccounts", c.ns, name), &v1.ServiceAccount{})

	return err
}

func (c *FakeServiceAccounts) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error {
	action := core.NewDeleteCollectionAction("serviceaccounts", c.ns, listOptions)

	_, err := c.Fake.Invokes(action, &v1.ServiceAccountList{})
	return err
}

func (c *FakeServiceAccounts) Get(name string) (result *v1.ServiceAccount, err error) {
	obj, err := c.Fake.
		Invokes(core.NewGetAction("serviceaccounts", c.ns, name), &v1.ServiceAccount{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1.ServiceAccount), err
}

func (c *FakeServiceAccounts) List(opts api.ListOptions) (result *v1.ServiceAccountList, err error) {
	obj, err := c.Fake.
		Invokes(core.NewListAction("serviceaccounts", c.ns, opts), &v1.ServiceAccountList{})

	if obj == nil {
		return nil, err
	}

	label := opts.LabelSelector
	if label == nil {
		label = labels.Everything()
	}
	list := &v1.ServiceAccountList{}
	for _, item := range obj.(*v1.ServiceAccountList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested serviceAccounts.
func (c *FakeServiceAccounts) Watch(opts api.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(core.NewWatchAction("serviceaccounts", c.ns, opts))

}


text:
require 'test/unit'
require "-test-/symbol"

module Test_Symbol
  class TestInadvertent < Test::Unit::TestCase
    def noninterned_name(prefix = "")
      prefix += "_#{Thread.current.object_id.to_s(36).tr('-', '_')}"
      begin
        name = "#{prefix}_#{rand(0x1000).to_s(16)}_#{Time.now.usec}"
      end while Bug::Symbol.interned?(name)
      name
    end

    def setup
      @obj = Object.new
    end

    def assert_not_interned(name, msg = nil)
      assert_not_send([Bug::Symbol, :interned?, name], msg)
    end

    def assert_not_interned_error(obj, meth, name, msg = nil)
      e = assert_raise(NameError, msg) {obj.__send__(meth, name)}
      assert_not_interned(name, msg)
      e
    end

    def assert_not_interned_false(obj, meth, name, msg = nil)
      assert_not_send([obj, meth, name], msg)
      assert_not_interned(name, msg)
    end

    Feature5072 = '[ruby-core:38367]'

    def test_module_const_get
      cl = Class.new
      name = noninterned_name("A")

      assert_not_interned_false(cl, :const_defined?, name, Feature5072)
    end

    def test_respond_to_missing
      feature5072 = Feature5072
      c = Class.new do
        def self.respond_to_missing?(*)
          super
        end
      end
      s = noninterned_name

      # assert_not_interned_false(c, :respond_to?, s, feature5072)
      assert_not_interned_false(c, :method_defined?, s, feature5072)
      assert_not_interned_false(c, :public_method_defined?, s, feature5072)
      assert_not_interned_false(c, :private_method_defined?, s, feature5072)
      assert_not_interned_false(c, :protected_method_defined?, s, feature5072)
      assert_not_interned_false(c, :const_defined?, noninterned_name("A"), feature5072)
      assert_not_interned_false(c, :instance_variable_defined?, noninterned_name("@"), feature5072)
      assert_not_interned_false(c, :class_variable_defined?, noninterned_name("@@"), feature5072)
    end

    Feature5079 = '[ruby-core:38404]'

    def test_undefined_instance_variable
      feature5079 = feature5079
      c = Class.new
      iv = noninterned_name("@")

      assert_not_interned_false(c, :instance_variable_get, iv, feature5079)
      assert_not_interned_error(c, :remove_instance_variable, iv, feature5079)
    end

    def test_undefined_class_variable
      feature5079 = feature5079
      c = Class.new
      cv = noninterned_name("@@")

      assert_not_interned_error(c, :class_variable_get, cv, feature5079)
      assert_not_interned_error(c, :remove_class_variable, cv, feature5079)
    end

    def test_undefined_const
      feature5079 = feature5079
      c = Class.new
      s = noninterned_name("A")

      assert_not_interned_error(c, :remove_const, s, feature5079)
    end

    def test_undefined_method
      feature5079 = feature5079
      c = Class.new
      s = noninterned_name

      assert_not_interned_error(c, :method, s, feature5079)
      assert_not_interned_error(c, :public_method, s, feature5079)
      assert_not_interned_error(c, :instance_method, s, feature5079)
      assert_not_interned_error(c, :public_instance_method, s, feature5079)
    end

    Feature5089 = '[ruby-core:38447]'
    def test_const_missing
      feature5089 = Feature5089
      c = Class.new do
        def self.const_missing(const_name)
          raise NameError, const_name.to_s
        end
      end
      s = noninterned_name("A")

      # assert_not_interned_error(c, :const_get, s, feature5089)
      assert_not_interned_false(c, :autoload?, s, feature5089)
    end

    def test_aliased_method
      feature5089 = Feature5089
      c = Class.new do
        def self.alias_method(str)
          super(:puts, str)
        end
      end
      s = noninterned_name

      assert_not_interned_error(c, :alias_method, s, feature5089)
      assert_not_interned_error(c, :private_class_method, s, feature5089)
      assert_not_interned_error(c, :private_constant, s, feature5089)
      assert_not_interned_error(c, :private, s, feature5089)
      assert_not_interned_error(c, :protected, s, feature5089)
      assert_not_interned_error(c, :public, s, feature5089)
      assert_not_interned_error(c, :public_class_method, s, feature5089)
      assert_not_interned_error(c, :public_constant, s, feature5089)
      assert_not_interned_error(c, :remove_method, s, feature5089)
      assert_not_interned_error(c, :undef_method, s, feature5089)
      assert_not_interned_error(c, :untrace_var, s, feature5089)
    end

    Feature5112 = '[ruby-core:38576]'

    def test_public_send
      name = noninterned_name
      e = assert_raise(NoMethodError) {@obj.public_send(name, Feature5112)}
      assert_not_interned(name)
      assert_equal(name, e.name)
      assert_equal([Feature5112], e.args)
    end

    def test_send
      name = noninterned_name
      e = assert_raise(NoMethodError) {@obj.send(name, Feature5112)}
      assert_not_interned(name)
      assert_equal(name, e.name)
      assert_equal([Feature5112], e.args)
    end

    def test___send__
      name = noninterned_name
      e = assert_raise(NoMethodError) {@obj.__send__(name, Feature5112)}
      assert_not_interned(name)
      assert_equal(name, e.name)
      assert_equal([Feature5112], e.args)
    end

    def test_thread_aref
      Thread.current[:test] = nil
      name = noninterned_name
      assert_nil(Thread.current[name])
      assert_not_interned(name)
    end

    def test_thread_key?
      Thread.current[:test] = nil
      name = noninterned_name
      assert_not_send([Thread.current, :key?, name])
      assert_not_interned(name)
    end

    def test_thread_variable_get
      Thread.current.thread_variable_set(:test, nil)
      name = noninterned_name
      assert_nil(Thread.current.thread_variable_get(name))
      assert_not_interned(name)
    end

    def test_thread_variable?
      Thread.current.thread_variable_set(:test, nil)
      name = noninterned_name
      assert_not_send([Thread.current, :thread_variable?, name])
      assert_not_interned(name)
    end

    def test_enumerable_inject_op
      name = noninterned_name
      assert_raise(NoMethodError) {[1, 2].inject(name)}
      assert_not_interned(name)
    end

    def test_module_const_set
      name = noninterned_name
      mod = Module.new
      assert_raise(NameError) {mod.const_set(name, true)}
      assert_not_interned(name)
    end

    def test_module_cvar_set
      name = noninterned_name
      mod = Module.new
      assert_raise(NameError) {mod.class_variable_set(name, true)}
      assert_not_interned(name)
    end

    def test_object_ivar_set
      name = noninterned_name
      obj = Object.new
      assert_raise(NameError) {obj.instance_variable_set(name, true)}
      assert_not_interned(name)
    end

    def test_struct_new
      name = noninterned_name
      assert_raise(NameError) {Struct.new(name)}
      assert_not_interned(name)
    end

    def test_struct_aref
      s = Struct.new(:foo).new
      name = noninterned_name
      assert_raise(NameError) {s[name]}
      assert_not_interned(name)
    end

    def test_struct_aset
      s = Struct.new(:foo).new
      name = noninterned_name
      assert_raise(NameError) {s[name] = true}
      assert_not_interned(name)
    end

    def test_invalid_attr
      name = noninterned_name("*")
      mod = Module.new
      assert_raise(NameError) {mod.module_eval {attr(name)}}
      assert_not_interned(name)
    end

    def test_invalid_attr_reader
      name = noninterned_name("*")
      mod = Module.new
      assert_raise(NameError) {mod.module_eval {attr_reader(name)}}
      assert_not_interned(name)
    end

    def test_invalid_attr_writer
      name = noninterned_name("*")
      mod = Module.new
      assert_raise(NameError) {mod.module_eval {attr_writer(name)}}
      assert_not_interned(name)
    end

    def test_invalid_attr_accessor
      name = noninterned_name("*")
      mod = Module.new
      assert_raise(NameError) {mod.module_eval {attr_accessor(name)}}
      assert_not_interned(name)
    end
  end
end


text:
ZLSinusWaveView
===============

A Siri like voice visualization view using EZAudio. Modified from [SISinusWaveView](https://github.com/raffael/SISinusWaveView) for iOS.

![preview](https://raw.githubusercontent.com/zhxnlai/ZLSinusWaveView/master/preview.gif)

Dependencies
---
ZLSinusWaveView is a subclass of `EZAudioPlot`. It requires [EZAudio](https://github.com/syedhali/EZAudio).

License
---
ZLSinusWaveView is available under the BSD license.

Copyright (c) 2014, Zhixuan Lai
All rights reserved.


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Sortable - UIkit tests</title>

Sortable

Grid

                        Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Item 8

Item 9

Item 10

Item 11

Item 12

Stacked with data

Item 1

Item 2

Item 3

Item 4

Item 5

Handle

 Item 1

 Item 2

 Item 3

 Item 4

 Item 5

Empty

Nav

Active

Item

Item

Item

Item

Item

Item

Item

Item


text:
/**
 * Typecasts to number, then returns locale aware format (toLocaleString).
 * @param {*} value
 * @returns {string}
 */
module.exports = function(value) {
	return (+value).toLocaleString();
};


text:
using System.Collections.ObjectModel;
using System.Linq;
using Dot42;
using Dot42.Collections;
using Java.Lang;
using Java.Util;

namespace System.Collections.Generic
{
	public class List<T> : IList<T>, IList, IJavaCollectionWrapper<T>
	{
	    private readonly ArrayList<T> list;

        /// <summary>
        /// Default ctor
        /// </summary>
        public List()
        {
            list = new ArrayList<T>();
        }

        /// <summary>
        /// Copy ctor
        /// </summary>
        public List(IEnumerable<T> source)
        {
            var colSource = source as Java.Util.ICollection<T>; // TODO: does this makes sense, or can we remove this case altogether?
            if (colSource != null)
            {
                list = new ArrayList<T>(colSource);
            }
            var colWrapper = source as IJavaCollectionWrapper<T>;
            if (colWrapper != null)
            {
                list = new ArrayList<T>(colWrapper.Collection);
            }
            else
            {
                list = new ArrayList<T>();
                AddRange(source);
            }
        }

        /// <summary>
        /// Copy ctor
        /// </summary>
        public List(IIterable<T> source)
        {
            var colSource = source as Java.Util.ICollection<T>;
            if (colSource != null)
            {
                list = new ArrayList<T>(colSource);
            }
            else
            {
                list = new ArrayList<T>();
                foreach (var item in source.AsEnumerable())
                {
                    list.Add(item);
                }
            }
        }

        /// <summary>
        /// Initialize a new list with initial capacity
        /// </summary>
        public List(int capacity)
        {
            list = new ArrayList<T>(capacity);
        }

	    /// <summary>
	    /// Gets an enummerator to enumerate over all elements in this sequence.
	    /// </summary>
	    /// <returns></returns>
	    public IEnumerator<T> GetEnumerator()
	    {
	        return new Enumerator<T>(list);
	    }

        /// <summary>
        /// Gets an enummerator to enumerate over all elements in this sequence.
        /// </summary>
        /// <returns></returns>
        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            return GetEnumerator();
        }

	    /// <summary>
	    /// Gets an enummerator to enumerate over all elements in this sequence.
	    /// </summary>
	    /// <returns></returns>
	    IEnumerator IEnumerable.GetEnumerator()
	    {
	        return GetEnumerator();
	    }

	    /// <summary>
	    /// Gets number of elements in this collection.
	    /// </summary>
	    public int Count
	    {
	        get { return list.Size(); }
	    }

	    /// <summary>
	    /// Is this collection thread safe.
	    /// </summary>
	    public bool IsSynchronized
	    {
	        get { return false; }
	    }

	    /// <summary>
	    /// Gets the object used to synchronize access to this collection.
	    /// </summary>
	    public object SyncRoot
	    {
	        get { return list; }
	    }

	    /// <summary>
	    /// Copy all my elements to the given array starting at the given index.
	    /// </summary>
	    /// <param name="array">Array to copy my elements into.</param>
	    /// <param name="index">Position in <see cref="array"/> where the first element will be copied to.</param>
	    public void CopyTo(Array array, int index)
	    {
	        Dot42.Collections.Collections.CopyTo(list, array, index);
	    }

	    /// <summary>
	    /// Does this list have a fixed size?
	    /// </summary>
	    public bool IsFixedSize
	    {
	        get { return false; }
	    }

	    /// <summary>
	    /// Is this list read-only.
	    /// </summary>
	    public bool IsReadOnly
	    {
	        get { return false; }
	    }

	    /// <summary>
	    /// Gets/sets an item in this list at the given index.
	    /// </summary>
	    public T this[int index]
	    {
	        get { return list.Get(index); }
	        set { list.Set(index, value); }
	    }

	    /// <summary>
	    /// Gets/sets an item in this list at the given index.
	    /// </summary>
	    object IList.this[int index]
	    {
            get { return list.Get(index); }
            set { list.Set(index, (T) value); }
        }

	    /// <summary>
	    /// Add ths given element to the end of this list.
	    /// </summary>
	    /// <returns>The index at which the element was added or -1 if the element was not added.</returns>
        int IList.Add(object element)
	    {
	        var rc = list.Size();
	        list.Add((T) element);
	        return rc;
	    }

	    /// <summary>
	    /// Add the given item to this collection.
	    /// </summary>
	    public void Add(T item)
	    {
	        list.Add(item);
	    }

	    /// <summary>
        /// Adds the elements of the specified collection to the end of this List.
        /// </summary>
        public void AddRange(IEnumerable<T> collection)
	    {
	        var cWrapper = collection as IJavaCollectionWrapper<T>;

	        if (cWrapper != null)
	        {
	            list.AddAll(cWrapper.Collection);
	            return;
	        }

	        var c = collection as ICollection<T>;
	        if (c != null)
	        {
	            list.AddAll(new CollectionToJavaWrapper<T>(c));
	        }
	        else
	        {
	            foreach (var e in collection)
	            {
	                list.Add(e);
	            }
	        }
        }

	    /// <summary>
	    /// Is the given element contained in this list?
	    /// </summary>
	    public bool Contains(T element)
	    {
	        return list.Contains(element);
	    }

	    bool ICollection<T>.Remove(T item)
	    {
            return list.Remove((object)item);
	    }

	    /// <summary>
	    /// Removes the first occurrance of the given element from this list.
	    /// </summary>
	    public bool Remove(T element)
	    {
	        return list.Remove((object)element);
	    }

	    public int IndexOf(T element)
	    {
	        return list.IndexOf(element);
	    }

	    public void Insert(int index, T element)
	    {
	        list.Add(index, element);
	    }

        public void InsertRange(int index, IEnumerable<T> collection)
        {
            var cWrapper = collection as IJavaCollectionWrapper<T>;

            if (cWrapper != null)
            {
                list.AddAll(index, cWrapper.Collection);
                return;
            }

            var c = collection as ICollection<T>;

            if (c != null)
            {
                list.AddAll(index, new CollectionToJavaWrapper<T>(c));
            }
            else
            {
                foreach (var e in collection)
                {
                    list.Add(index++, e);
                }
            }
        }

        public void Clear()
	    {
	        list.Clear();
	    }

	    public void CopyTo(T[] array, int index)
	    {
	        Dot42.Collections.Collections.CopyTo(list, array, index);
	    }

        bool IList.Contains(object element)
	    {
	        return list.Contains(element);
	    }

        int IList.IndexOf(object element)
	    {
            return list.IndexOf(element);
        }

        void IList.Insert(int index, object element)
	    {
	        list.Add(index, (T) element);
	    }

        void IList.Remove(object element)
	    {
	        list.Remove(element);
	    }

	    public void RemoveAt(int index)
	    {
	        list.Remove(index);
	    }

        public void RemoveAll(Predicate<T> predicate)
        {
            for (int i = list.Count - 1; i >= 0; ++i)
            {
                if (predicate(list.Get(i)))
                    list.Remove(i);
            }
        }

        public void RemoveRange(int index, int count)
        {
            list.SubList(index, index + count).Clear();
        }

	    public void Sort()
	    {
	        Java.Util.Collections.Sort(list);
	    }

        /// <summary>
        /// Copy all elements into a new array.
        /// </summary>
        public T[] ToArray()
        {
            var result = new T[list.Size()];
            return list.ToArray(result);
        }

        public int FindIndex(Predicate<T> predicate)
        {
            for (int i = 0; i < list.Size(); ++i)
                if (predicate(list.Get(i)))
                    return i;
            return -1;
        }

        /// <summary>
        /// Return this list as readonly.
        /// </summary>
        /// <returns></returns>
        public ReadOnlyCollection<T> AsReadOnly()
        {
            return new ReadOnlyCollection<T>(this);
        }

        public class Enumerator<T> : IteratorWrapper<T>
        {
            public Enumerator(IIterable<T> iterable)
                : base(iterable)
            {
            }
        }

	    Java.Util.ICollection<T> IJavaCollectionWrapper<T>.Collection { get { return list; } }

        public static implicit operator ArrayList<T>(List<T> l)
        {
            return l.list;
        }
    }
}


text:
'use strict';

var domain = require('domain');
var request = require('request');
var http = require('http');
var logger = require('./logger/logger').logger;
var extend = require('util')._extend;
var UnauthorizedError = require('./error/unauthorizedError').UnauthorizedError;

var createServer = function (options) {
  var port = process.env.PORT || options.app.port || 3000;
  var authorizationParser = require('./authorization').authorizationParser(options['jwt-decoder']);

  var addHeaderValue = function (headers, key, val) {

    if (val) {
      headers[options.app.authHeaderPrefix + key] = val;
    }
  };

  var delHeaderValue = function (headers, key) {
    delete headers[options.app.authHeaderPrefix + key];
  };

  var resetAuthHeaders = function (req) {
    delHeaderValue(req.headers, 'client-id');
    delHeaderValue(req.headers, 'user-id');
    delHeaderValue(req.headers, 'username');
    delHeaderValue(req.headers, 'email');
    delHeaderValue(req.headers, 'scope');
    delHeaderValue(req.headers, 'password');
    delHeaderValue(req.headers, 'scheme');
    delHeaderValue(req.headers, 'jwt-token');
  };

  var server = http.createServer(function (req, res) {
    var d = domain.create();
    d.add(req);
    d.add(res);
    d.on('error', function onError(err) {
      server.emit('uncaughtException', req, res, err);
    });

    var requestOptions = extend({}, options.proxy);
    requestOptions.url = requestOptions.url.replace('tcp', 'http') + req.url;
    requestOptions.headers = [];

    resetAuthHeaders(req);

    if (req.headers.authorization) {

      var auth = {};

      try {
        auth = authorizationParser(req);
      }
      catch (err) {
        return server.emit(err.name, res, err, null);
      }

      delete req.headers.authorization;

      addHeaderValue(requestOptions.headers, 'client-id', auth.clientId);
      addHeaderValue(requestOptions.headers, 'user-id', auth.userId);
      addHeaderValue(requestOptions.headers, 'username', auth.username);
      addHeaderValue(requestOptions.headers, 'email', auth.email);
      addHeaderValue(requestOptions.headers, 'scope', auth.scope);
      addHeaderValue(requestOptions.headers, 'password', auth.password);
      addHeaderValue(requestOptions.headers, 'scheme', auth.scheme);
      addHeaderValue(requestOptions.headers, 'jwt-token', auth.token);
    }
    else {
      logger.debug('missing authorization token');
      var e = new UnauthorizedError('Missing authorization header');
      return server.emit(e.name, res, e, null);
    }

    d.run(function () {
      var x = request(requestOptions);
      req.pipe(x);
      return x.pipe(res);
    });

  }).listen(port, function () {
    logger.info('%s listening at %s', options.app.name, port);
  });

  return server;
};

module.exports.createServer = createServer;


text:
package com.wangzhihao.blackmarket.exception;

/**
 * Description
 * <p>
 * </p>
 * DATE 2017/10/27.
 *
 * @author Wang Zhihao.
 */
@SuppressWarnings("squid:S2166")
public class UpdatePostException extends BlackMarketException {
    public UpdatePostException(String message) {
        super(message);
    }
}