text:
@implementation DJTableViewVM(UITableViewDelegate)

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self checkAvaliableForIndexPath:indexPath] == NO) {
        return 0;
    }

    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)]){
        return [self.delegate tableView:tableView heightForRowAtIndexPath:indexPath];
    }
    DJTableViewVMSection *section = [self.sections objectAtIndex:indexPath.section];
    DJTableViewVMRow *row = [section.rows objectAtIndex:indexPath.row];
    if (row.cellHeight == 0 || row.heightForceRefreshEnable) {
        if (row.heightCaculateType == DJCellHeightCaculateDefault) {
            NSString *cellClassName = [self objectAtKeyedSubscript:NSStringFromClass(row.class)];
            row.cellHeight = [NSClassFromString(cellClassName) heightWithRow:row tableViewVM:self];
        }else{
            row.cellHeight = [self heightWithAutoLayoutCellForIndexPath:indexPath];
            DJLog(@"auto caculate cell(position:%@) height:%f",indexPath,row.cellHeight);
        }
    }
    return row.cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)sectionIndex
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:heightForHeaderInSection:)]){
        return [self.delegate tableView:tableView heightForHeaderInSection:sectionIndex];
    }

    return [self heightWithSectionIndex:sectionIndex isHeader:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)sectionIndex
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:heightForFooterInSection:)]){
        return [self.delegate tableView:tableView heightForFooterInSection:sectionIndex];
    }

    return [self heightWithSectionIndex:sectionIndex isHeader:NO];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self checkAvaliableForIndexPath:indexPath] == NO) {
        return 0;
    }

    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:estimatedHeightForRowAtIndexPath:)]){
        return [self.delegate tableView:tableView estimatedHeightForRowAtIndexPath:indexPath];
    }

    if (self.sections.count <= indexPath.section) {
        return UITableViewAutomaticDimension;
    }

    if (self.estimatedRowHeight > 0.0f) {
        return self.estimatedRowHeight;
    }

    DJTableViewVMSection *section = [self.sections objectAtIndex:indexPath.section];
    DJTableViewVMRow *row = [section.rows objectAtIndex:indexPath.row];
    NSString *cellClassName = [self objectAtKeyedSubscript:NSStringFromClass(row.class)];
    CGFloat height = 0;
    if (row.cellHeight == 0) {
        height = [NSClassFromString(cellClassName) heightWithRow:row tableViewVM:self];
    }else{
        height = row.cellHeight;
    }

    return height ? height : UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0)
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:estimatedHeightForHeaderInSection:)]){
        return [self.delegate tableView:tableView estimatedHeightForHeaderInSection:section];
    }

    if (section < self.sections.count){
        DJTableViewVMSection *sectionVM = [self.sections objectAtIndex:section];
        if (sectionVM.headerView){
            return sectionVM.headerView.frame.size.height;
        }

        if (sectionVM.headerTitle){
            return 28;// default height for header
        }
    }

    return self.tableView.estimatedSectionHeaderHeight;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section NS_AVAILABLE_IOS(7_0)
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:estimatedHeightForFooterInSection:)]){
        return [self.delegate tableView:tableView estimatedHeightForFooterInSection:section];
    }

    if (section < self.sections.count){
        DJTableViewVMSection *sectionVM = [self.sections objectAtIndex:section];
        if (sectionVM.footerView){
            return sectionVM.footerView.frame.size.height;
        }

        if (sectionVM.footerTitle){
            return 28;// default height for footer
        }
    }

    return self.tableView.estimatedSectionFooterHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)sectionIndex
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]){
        return [self.delegate tableView:tableView viewForHeaderInSection:sectionIndex];
    }

    if (self.sections.count <= sectionIndex) {
        return nil;
    }
    DJTableViewVMSection *section = [self.sections objectAtIndex:sectionIndex];
    return section.headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)sectionIndex
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:viewForFooterInSection:)]){
        return [self.delegate tableView:tableView viewForFooterInSection:sectionIndex];
    }

    if (self.sections.count <= sectionIndex) {
        return nil;
    }
    DJTableViewVMSection *section = [self.sections objectAtIndex:sectionIndex];
    return section.footerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self checkAvaliableForIndexPath:indexPath] == NO) {
        return;
    }

    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]){
        [self.delegate tableView:tableView didSelectRowAtIndexPath:indexPath];
    }

    DJTableViewVMSection *section = [self.sections objectAtIndex:indexPath.section];
    DJTableViewVMRow *row = [section.rows objectAtIndex:indexPath.row];
    if ([row respondsToSelector:@selector(setSelectionHandler:)]){
        DJTableViewVMRow *actionRow = (DJTableViewVMRow *)row;
        if (actionRow.selectionHandler) {
            actionRow.selectionHandler(actionRow);
        }else{
            if (DJ_LOG_ENABLE) {
                static int tapCount = 0;
                tapCount ++;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    tapCount = 0;
                });
                if (tapCount == 3){
                    //tap three times in 1 second
                    DJRevealViewController *aDJRevealViewController = [DJRevealViewController new];
                    aDJRevealViewController.tableViewVM = self;
                    [[UIApplication sharedApplication].keyWindow.rootViewController showViewController:aDJRevealViewController sender:nil];
                }
            }
        }
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:willDisplayCell:forRowAtIndexPath:)]){
        [self.delegate tableView:tableView willDisplayCell:cell forRowAtIndexPath:indexPath];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:willDisplayHeaderView:forSection:)]){
        [self.delegate tableView:tableView willDisplayHeaderView:view forSection:section];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:willDisplayFooterView:forSection:)]){
        [self.delegate tableView:tableView willDisplayFooterView:view forSection:section];
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath
{
    if ([cell respondsToSelector:@selector(cellDidDisappear)]){
        [(UITableViewCell<DJTableViewVMCellProtocol> *)cell cellDidDisappear];
    }

    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:didEndDisplayingCell:forRowAtIndexPath:)]){
        [self.delegate tableView:tableView didEndDisplayingCell:cell forRowAtIndexPath:indexPath];
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:didEndDisplayingHeaderView:forSection:)]){
        [self.delegate tableView:tableView didEndDisplayingHeaderView:view forSection:section];
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingFooterView:(UIView *)view forSection:(NSInteger)section
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:didEndDisplayingFooterView:forSection:)]){
        [self.delegate tableView:tableView didEndDisplayingFooterView:view forSection:section];
    }
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    if ([self checkAvaliableForIndexPath:indexPath] == NO) {
        return;
    }

    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:accessoryButtonTappedForRowWithIndexPath:)]){
        [self.delegate tableView:tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
    }
    DJTableViewVMSection *section = [self.sections objectAtIndex:indexPath.section];
    DJTableViewVMRow *row = [section.rows objectAtIndex:indexPath.row];
    if ([row respondsToSelector:@selector(setSelectionHandler:)]){
        DJTableViewVMRow *actionRow = (DJTableViewVMRow *)row;
        if (actionRow.accessoryButtonTapHandler) {
            actionRow.accessoryButtonTapHandler(actionRow);
        }
    }
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:shouldHighlightRowAtIndexPath:)]){
        return [self.delegate tableView:tableView shouldHighlightRowAtIndexPath:indexPath];
    }

    return YES;
}

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:didHighlightRowAtIndexPath:)]){
        [self.delegate tableView:tableView didHighlightRowAtIndexPath:indexPath];
    }
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:didUnhighlightRowAtIndexPath:)]){
        [self.delegate tableView:tableView didUnhighlightRowAtIndexPath:indexPath];
    }
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:willSelectRowAtIndexPath:)]){
        return [self.delegate tableView:tableView willSelectRowAtIndexPath:indexPath];
    }

    return indexPath;
}

- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:willDeselectRowAtIndexPath:)]){
        return [self.delegate tableView:tableView willDeselectRowAtIndexPath:indexPath];
    }

    return indexPath;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:didDeselectRowAtIndexPath:)]){
        [self.delegate tableView:tableView didDeselectRowAtIndexPath:indexPath];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self checkAvaliableForIndexPath:indexPath] == NO) {
        return UITableViewCellEditingStyleNone;
    }

    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:editingStyleForRowAtIndexPath:)]){
        return [self.delegate tableView:tableView editingStyleForRowAtIndexPath:indexPath];
    }
    DJTableViewVMSection *sectionVM = [self.sections objectAtIndex:indexPath.section];
    DJTableViewVMRow *rowVM = [sectionVM.rows objectAtIndex:indexPath.row];
    return rowVM.editingStyle;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self checkAvaliableForIndexPath:indexPath] == NO) {
        return nil;
    }

    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:editActionsForRowAtIndexPath:)]){
        return [self.delegate tableView:tableView editActionsForRowAtIndexPath:indexPath];
    }
    DJTableViewVMSection *sectionVM = [self.sections objectAtIndex:indexPath.section];
    DJTableViewVMRow *rowVM = [sectionVM.rows objectAtIndex:indexPath.row];
    return rowVM.editActions;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:)]){
        return [self.delegate tableView:tableView titleForDeleteConfirmationButtonForRowAtIndexPath:indexPath];
    }

    return NSLocalizedString(@"Delete", @"Delete");
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:shouldIndentWhileEditingRowAtIndexPath:)]){
        return [self.delegate tableView:tableView shouldIndentWhileEditingRowAtIndexPath:indexPath];
    }

    return YES;
}

- (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:willBeginEditingRowAtIndexPath:)]){
        [self.delegate tableView:tableView willBeginEditingRowAtIndexPath:indexPath];
    }
}

- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:didEndEditingRowAtIndexPath:)]){
        [self.delegate tableView:tableView didEndEditingRowAtIndexPath:indexPath];
    }
}

- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    if ([self checkAvaliableForIndexPath:sourceIndexPath] == NO) {
        return sourceIndexPath;
    }

    DJTableViewVMSection *sourceSection = [self.sections objectAtIndex:sourceIndexPath.section];
    DJTableViewVMRow *rowVM = [sourceSection.rows objectAtIndex:sourceIndexPath.row];
    if (rowVM.moveCellHandler) {
        BOOL allowed = rowVM.moveCellHandler(rowVM, sourceIndexPath, proposedDestinationIndexPath);
        if (!allowed){
            return sourceIndexPath;
        }
    }

    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:)]){
        return [self.delegate tableView:tableView targetIndexPathForMoveFromRowAtIndexPath:sourceIndexPath toProposedIndexPath:proposedDestinationIndexPath];
    }

    return proposedDestinationIndexPath;
}

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:indentationLevelForRowAtIndexPath:)]){
        return [self.delegate tableView:tableView indentationLevelForRowAtIndexPath:indexPath];
    }

    return 0;
}

- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self checkAvaliableForIndexPath:indexPath] == NO) {
        return NO;
    }
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:shouldShowMenuForRowAtIndexPath:)]){
        return [self.delegate tableView:tableView shouldShowMenuForRowAtIndexPath:indexPath];
    }

    DJTableViewVMSection *sectionVM = [self.sections objectAtIndex:indexPath.section];
    DJTableViewVMRow *rowVM = [sectionVM.rows objectAtIndex:indexPath.row];
    return (rowVM.copyHandler || rowVM.pasteHandler);
}

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    if ([self checkAvaliableForIndexPath:indexPath] == NO) {
        return NO;
    }

    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:canPerformAction:forRowAtIndexPath:withSender:)]){
        return [self.delegate tableView:tableView canPerformAction:action forRowAtIndexPath:indexPath withSender:sender];
    }
    DJTableViewVMSection *sectionVM = [self.sections objectAtIndex:indexPath.section];
    DJTableViewVMRow *rowVM = [sectionVM.rows objectAtIndex:indexPath.row];
    if (rowVM.copyHandler && action == @selector(copy:)){
        return YES;
    }
    if (rowVM.pasteHandler && action == @selector(paste:)){
        return YES;
    }
    if (rowVM.cutHandler && action == @selector(cut:)){
        return YES;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    if ([self checkAvaliableForIndexPath:indexPath] == NO) {
        return;
    }
    if ([self.delegate conformsToProtocol:@protocol(UITableViewDelegate)] && [self.delegate respondsToSelector:@selector(tableView:performAction:forRowAtIndexPath:withSender:)]){
        [self.delegate tableView:tableView performAction:action forRowAtIndexPath:indexPath withSender:sender];
    }

    DJTableViewVMSection *sectionVM = [self.sections objectAtIndex:indexPath.section];
    DJTableViewVMRow *rowVM = [sectionVM.rows objectAtIndex:indexPath.row];

    if (action == @selector(copy:) && rowVM.copyHandler) {
        rowVM.copyHandler(rowVM);
    }
    if (action == @selector(paste:) && rowVM.pasteHandler) {
        rowVM.pasteHandler(rowVM);
    }
    if (action == @selector(cut:) && rowVM.cutHandler) {
        rowVM.cutHandler(rowVM);
    }
}

#pragma mark - private methods
- (BOOL)checkAvaliableForIndexPath:(NSIndexPath *)indexPath
{
    if (self.sections.count > indexPath.section) {
        DJTableViewVMSection *sectionVM = [self.sections objectAtIndex:indexPath.section];
        if (sectionVM.rows.count > indexPath.row) {
            return YES;
        }
    }

    return NO;
}

- (CGFloat)heightWithSectionIndex:(NSInteger )sectionIndex isHeader:(BOOL)isHeader
{
    if (self.sections.count <= sectionIndex) {
        return 0;
    }

    DJTableViewVMSection *sectionVM = [self.sections objectAtIndex:sectionIndex];
    UIView *sectionView = isHeader ? sectionVM.headerView : sectionVM.footerView;
    DJSectionHeightCaculateType caculateType = isHeader ? sectionVM.headerHeightCaculateType : sectionVM.footerHeightCaculateType;
    NSString *heightCacheKey = isHeader ? @"DJSectionVMHeaderHeightKey" : @"DJSectionVMFooterHeightKey";

    //UITableView init in Xib has default height 28
    //    if (self.sectionHeaderHeight > 0.0f) {
    //        return self.sectionHeaderHeight;
    //    }

    if(sectionView) {
        if (caculateType == DJSectionHeightCaculateTypeDefault) {
            return sectionView.frame.size.height;
        }else if(caculateType == DJSectionHeightCaculateTypeAutomatic){
            CGFloat cacheHeight = [[sectionVM.automaticHeightCache valueForKey:heightCacheKey] floatValue];
            if (cacheHeight == 0 || sectionVM.isSectionHeightNeedRefresh) {
                CGFloat contentViewWidth = CGRectGetWidth(self.tableView.frame);
                if (contentViewWidth > 0) {
                    NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:sectionView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth];
                    [sectionView addConstraint:widthFenceConstraint];
                    CGSize sectionViewSize = [sectionView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
                    [sectionView removeConstraint:widthFenceConstraint];

                    [sectionVM.automaticHeightCache setValue:@(sectionViewSize.height) forKey:heightCacheKey];
                    sectionVM.isSectionHeightNeedRefresh = NO;

                    return sectionViewSize.height;
                }
            }else{
                return cacheHeight;
            }

        }
    }

    return UITableViewAutomaticDimension;
}

@end


text:
import { ReactiveVar } from 'meteor/reactive-var';
import { RocketChatTabBar } from 'meteor/rocketchat:lib';
import { Tracker } from 'meteor/tracker';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { Template } from 'meteor/templating';
import { RocketChat } from 'meteor/rocketchat:lib';
import { SideNav } from 'meteor/rocketchat:ui';
import s from 'underscore.string';

Template.adminSounds.helpers({
	isReady() {
		if (Template.instance().ready != null) {
			return Template.instance().ready.get();
		}
		return undefined;
	},
	customsounds() {
		return Template.instance().customsounds();
	},
	isLoading() {
		if (Template.instance().ready != null) {
			if (!Template.instance().ready.get()) {
				return 'btn-loading';
			}
		}
	},
	hasMore() {
		if (Template.instance().limit != null) {
			if (typeof Template.instance().customsounds === 'function') {
				return Template.instance().limit.get() === Template.instance().customsounds().length;
			}
		}
		return false;
	},
	flexData() {
		return {
			tabBar: Template.instance().tabBar,
			data: Template.instance().tabBarData.get(),
		};
	},
});

Template.adminSounds.onCreated(function() {
	const instance = this;
	this.limit = new ReactiveVar(50);
	this.filter = new ReactiveVar('');
	this.ready = new ReactiveVar(false);

	this.tabBar = new RocketChatTabBar();
	this.tabBar.showGroup(FlowRouter.current().route.name);
	this.tabBarData = new ReactiveVar();

	RocketChat.TabBar.addButton({
		groups: ['custom-sounds', 'custom-sounds-selected'],
		id: 'add-sound',
		i18nTitle: 'Custom_Sound_Add',
		icon: 'plus',
		template: 'adminSoundEdit',
		openClick(/* e, t*/) {
			instance.tabBarData.set();
			return true;
		},
		order: 1,
	});

	RocketChat.TabBar.addButton({
		groups: ['custom-sounds-selected'],
		id: 'admin-sound-info',
		i18nTitle: 'Custom_Sound_Info',
		icon: 'customize',
		template: 'adminSoundInfo',
		order: 2,
	});

	this.autorun(function() {
		const limit = (instance.limit != null) ? instance.limit.get() : 0;
		const subscription = instance.subscribe('customSounds', '', limit);
		instance.ready.set(subscription.ready());
	});

	this.customsounds = function() {
		const filter = (instance.filter != null) ? s.trim(instance.filter.get()) : '';

		let query = {};

		if (filter) {
			const filterReg = new RegExp(s.escapeRegExp(filter), 'i');
			query = { name: filterReg };
		}

		const limit = (instance.limit != null) ? instance.limit.get() : 0;

		return RocketChat.models.CustomSounds.find(query, { limit, sort: { name: 1 } }).fetch();
	};
});

Template.adminSounds.onRendered(() =>
	Tracker.afterFlush(function() {
		SideNav.setFlex('adminFlex');
		SideNav.openFlex();
	})
);

Template.adminSounds.events({
	'keydown #sound-filter'(e) {
		// stop enter key
		if (e.which === 13) {
			e.stopPropagation();
			e.preventDefault();
		}
	},

	'keyup #sound-filter'(e, t) {
		e.stopPropagation();
		e.preventDefault();
		t.filter.set(e.currentTarget.value);
	},

	'click .sound-info'(e, instance) {
		e.preventDefault();
		instance.tabBarData.set(RocketChat.models.CustomSounds.findOne({ _id: this._id }));
		instance.tabBar.showGroup('custom-sounds-selected');
		instance.tabBar.open('admin-sound-info');
	},

	'click .load-more'(e, t) {
		e.preventDefault();
		e.stopPropagation();
		t.limit.set(t.limit.get() + 50);
	},

	'click .icon-play-circled'(e) {
		e.preventDefault();
		e.stopPropagation();
		const $audio = $(`audio#${ this._id }`);
		if ($audio && $audio[0] && $audio[0].play) {
			$audio[0].play();
		}
	},
});

redpajama_set_name: RedPajamaGithub


text:
import * as React from 'react';
import styled from 'styled-components';
import Input from '/component/base/Input';
import SpacedContent from '/component/base/SpacedContent';

const FieldLabel = styled.label`
  display: block;
`;

class InputField extends React.Component {
  render() {
    const {label, ...rest} = this.props;
    return (
      <FieldLabel>
        <SpacedContent f={1}>
          <div>{label}</div>
          <Input {...rest} />
        </SpacedContent>
      </FieldLabel>
    );
  }
}
export default InputField;


text:
package com.elytradev.correlated.network;

import com.elytradev.correlated.CLog;
import com.elytradev.correlated.client.gui.GuiAutomaton;
import com.elytradev.correlated.client.gui.GuiDrive;
import com.elytradev.correlated.client.gui.GuiImporterChest;
import com.elytradev.correlated.client.gui.GuiInterface;
import com.elytradev.correlated.client.gui.GuiTerminal;
import com.elytradev.correlated.entity.EntityAutomaton;
import com.elytradev.correlated.inventory.ContainerAutomaton;
import com.elytradev.correlated.inventory.ContainerDrive;
import com.elytradev.correlated.inventory.ContainerImporterChest;
import com.elytradev.correlated.inventory.ContainerInterface;
import com.elytradev.correlated.inventory.ContainerTerminal;
import com.elytradev.correlated.item.ItemDrive;
import com.elytradev.correlated.item.ItemHandheldTerminal;
import com.elytradev.correlated.storage.WirelessTerminal;
import com.elytradev.correlated.tile.TileEntityInterface;
import com.elytradev.correlated.tile.TileEntityTerminal;
import com.elytradev.correlated.tile.importer.TileEntityImporterChest;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;

public class CorrelatedGuiHandler implements IGuiHandler {

	@Override
	public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {
		switch (id) {
			case 0: {
				TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
				if (te instanceof TileEntityTerminal) {
					return new ContainerTerminal(player.inventory, player, (TileEntityTerminal)te);
				} else {
					CLog.warn("Expected TileEntityTerminal at {}, {}, {} - got {} instead", x, y, z, te == null ? "null" : te.getClass());
					break;
				}
			}
			case 1: {
				Container open = player.openContainer;
				if (open != null && open instanceof ContainerTerminal) {
					ItemStack drive = ((ContainerTerminal)open).terminal.getMaintenanceSlotContent();
					if (drive.getItem() instanceof ItemDrive) {
						return new ContainerDrive((ContainerTerminal)open, player.inventory, player);
					} else {
						CLog.warn("Expected a drive, got {} instead", drive);
						break;
					}
				} else {
					CLog.warn("Expected a ContainerTerminal, got {} instead", open == null ? "null" : open.getClass());
					break;
				}
			}
			case 2: {
				TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
				if (te instanceof TileEntityInterface) {
					return new ContainerInterface(player.inventory, player, (TileEntityInterface)te);
				} else {
					CLog.warn("Expected TileEntityInterface at {}, {}, {} - got {} instead", x, y, z, te == null ? "null" : te.getClass());
					break;
				}
			}
			case 3: {
				ItemStack terminal = x == -1 ? player.inventory.offHandInventory.get(0) : player.inventory.getStackInSlot(x);
				if (terminal.getItem() instanceof ItemHandheldTerminal) {
					return new ContainerTerminal(player.inventory, player, new WirelessTerminal(world, player, (ItemHandheldTerminal)terminal.getItem(), terminal));
				} else {
					CLog.warn("Expected a wireless terminal, got {} instead", terminal);
					break;
				}
			}
			case 4: {
				Entity ent = world.getEntityByID(x);
				if (ent != null && ent instanceof EntityAutomaton) {
					return new ContainerAutomaton(player.inventory, player, (EntityAutomaton)ent);
				} else {
					CLog.warn("Expected an Automaton, got {} instead", ent == null ? "null" : ent.getClass());
					break;
				}
			}
			case 5: {
				TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
				if (te instanceof TileEntityImporterChest) {
					return new ContainerImporterChest(player.inventory, player, (TileEntityImporterChest)te);
				} else {
					CLog.warn("Expected TileEntityImporterChest at {}, {}, {} - got {} instead", x, y, z, te == null ? "null" : te.getClass());
					break;
				}
			}
		}
		return null;
	}

	@Override
	public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {
		switch (id) {
			case 0: {
				TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
				if (te instanceof TileEntityTerminal) {
					return new GuiTerminal(new ContainerTerminal(player.inventory, player, (TileEntityTerminal)te));
				} else {
					CLog.warn("Expected TileEntityTerminal at {}, {}, {} - got {} instead", x, y, z, te == null ? "null" : te.getClass());
					break;
				}
			}
			case 1: {
				GuiScreen open = Minecraft.getMinecraft().currentScreen;
				if (open != null && open instanceof GuiTerminal) {
					ContainerTerminal ct = ((ContainerTerminal)((GuiTerminal)open).inventorySlots);
					ItemStack drive = ct.maintenanceSlot.getStack();
					if (drive.getItem() instanceof ItemDrive) {
						return new GuiDrive((GuiTerminal)open, new ContainerDrive(ct, player.inventory, player));
					} else {
						CLog.warn("Expected a drive, got {} instead", drive);
						break;
					}
				} else {
					CLog.warn("Expected a GuiTerminal, got {} instead", open == null ? "null" : open.getClass());
					break;
				}
			}
			case 2: {
				TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
				if (te instanceof TileEntityInterface) {
					return new GuiInterface(new ContainerInterface(player.inventory, player, (TileEntityInterface)te));
				} else {
					CLog.warn("Expected TileEntityInterface at {}, {}, {} - got {} instead", x, y, z, te == null ? "null" : te.getClass());
					break;
				}
			}
			case 3: {
				ItemStack terminal = x == -1 ? player.inventory.offHandInventory.get(0) : player.inventory.getStackInSlot(x);
				if (terminal.getItem() instanceof ItemHandheldTerminal) {
					return new GuiTerminal(new ContainerTerminal(player.inventory, player, new WirelessTerminal(world, player, (ItemHandheldTerminal)terminal.getItem(), terminal)));
				} else {
					CLog.warn("Expected a wireless terminal, got {} instead", terminal);
					break;
				}
			}
			case 4: {
				Entity ent = world.getEntityByID(x);
				if (ent != null && ent instanceof EntityAutomaton) {
					return new GuiAutomaton(new ContainerAutomaton(player.inventory, player, (EntityAutomaton)ent));
				} else {
					CLog.warn("Expected an Automaton, got {} instead", ent == null ? "null" : ent.getClass());
					break;
				}
			}
			case 5: {
				TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
				if (te instanceof TileEntityImporterChest) {
					return new GuiImporterChest(new ContainerImporterChest(player.inventory, player, (TileEntityImporterChest)te));
				} else {
					CLog.warn("Expected TileEntityImporterChest at {}, {}, {} - got {} instead", x, y, z, te == null ? "null" : te.getClass());
					break;
				}
			}
		}
		return null;
	}

}


text:
import declare from 'dojo/_base/declare';
import lang from 'dojo/_base/lang';
import _ModelBase from 'argos/Models/_ModelBase';
import MODEL_NAMES from '../Names';
import getResource from 'argos/I18n';

const resource = getResource('productModel');

const __class = declare('crm.Integrations.BOE.Models.Product.Base', [_ModelBase], {
  contractName: 'dynamic',
  resourceKind: 'products',
  entityName: 'Product',
  entityDisplayName: resource.entityDisplayName,
  entityDisplayNamePlural: resource.entityDisplayNamePlural,
  modelName: MODEL_NAMES.PRODUCT,
  iconClass: '',
  detailViewId: '',
  listViewId: '',
  editViewId: '',
  createRelationships: function createRelationships() {
    const rel = this.relationships || (this.relationships = []);
    return rel;
  },
});
lang.setObject('icboe.Models.Product.Base', __class);
export default __class;


text:
"""Generate .gclient file for Angle.

Because gclient won't accept "--name ." use a different name then edit.
"""

import subprocess
import sys

def main():
    gclient_cmd = ('gclient config --name change2dot --unmanaged '
                   'https://chromium.googlesource.com/angle/angle.git')
    try:
        rc = subprocess.call(gclient_cmd, shell=True)
    except OSError:
        print 'could not run "%s" via shell' % gclient_cmd
        sys.exit(1)

    if rc:
        print 'failed command: "%s"' % gclient_cmd
        sys.exit(1)

    with open('.gclient') as gclient_file:
        content = gclient_file.read()

    with open('.gclient', 'w') as gclient_file:
        gclient_file.write(content.replace('change2dot', '.'))

    print 'created .gclient'

if __name__ == '__main__':
    main()


text:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using Windows.Phone.Media.Capture;

namespace CameraExplorer
{
    /// <summary>
    /// CameraExplorer.DataContext holds all application widely used instances, like parameters,
    /// camera instance and image memory stream.
    /// </summary>
    class DataContext : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private static DataContext _singleton;
        private static IsolatedStorageSettings _settings = IsolatedStorageSettings.ApplicationSettings;
        private PhotoCaptureDevice _device = null;
        private ObservableCollection<Parameter> _parameters = new ObservableCollection<Parameter>();

        /// <summary>
        /// Singleton instance accessor.
        /// </summary>
        public static DataContext Singleton
        {
            get
            {
                if (_singleton == null)
                {
                    _singleton = new DataContext();
                }

                return _singleton;
            }
        }

        /// <summary>
        /// Collection of camera parameters.
        /// </summary>
        public ObservableCollection<Parameter> Parameters
        {
            get
            {
                return _parameters;
            }

            private set
            {
                if (_parameters != value)
                {
                    _parameters = value;

                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("Parameters"));
                    }
                }
            }
        }

        /// <summary>
        /// Camera instance. Setting new camera instance to this property causes the Parameters
        /// property to be updated as well with the new parameters from the new camera.
        /// </summary>
        public PhotoCaptureDevice Device
        {
            get
            {
                return _device;
            }

            set
            {
                if (_device != value)
                {
                    _device = value;

                    if (_device != null)
                    {
                        ObservableCollection<Parameter> newParameters = new ObservableCollection<Parameter>();

                        Action<Parameter> addParameter = (Parameter parameter) =>
                        {
                            if (parameter.Supported && parameter.Modifiable)
                            {
                                try
                                {
                                    parameter.Refresh();
                                    parameter.SetSavedOrDefault();

                                    newParameters.Add(parameter);
                                }
                                catch (Exception)
                                {
                                    System.Diagnostics.Debug.WriteLine("Setting default to " + parameter.Name.ToLower() + " failed");
                                }
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("Parameter " + parameter.Name.ToLower() + " is not supported or not modifiable");
                            }
                        };

                        addParameter(new SceneModeParameter(_device));
                        addParameter(new WhiteBalancePresetParameter(_device));
                        addParameter(new FlashModeParameter(_device));
                        addParameter(new FlashPowerParameter(_device));
                        addParameter(new IsoParameter(_device));
                        addParameter(new ExposureCompensationParameter(_device));
                        addParameter(new ExposureTimeParameter(_device));
                        addParameter(new AutoFocusRangeParameter(_device));
                        addParameter(new FocusIlluminationModeParameter(_device));
                        addParameter(new CaptureResolutionParameter(_device));

                        Parameters = newParameters;
                    }

                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("Device"));
                    }
                }
            }
        }

        /// <summary>
        /// Settings accessors.
        /// </summary>
        public static IsolatedStorageSettings Settings
        {
            get
            {
                return _settings;
            }
        }

        /// <summary>
        /// Memory stream to hold the image data captured in MainPage but consumed in PreviewPage.
        /// </summary>
        public MemoryStream ImageStream { get; set; }
    }
}


text:
class CreateGames < ActiveRecord::Migration
  def change
    create_table :games do |t|
      t.string :name, null: false

      t.timestamps(null: false)
    end
  end
end


text:
Desafios propostos pelo professor Lenardo Vilela, implementados na linguagem de programação R.

- Diretório **data** contém os arquivos de dados (data sets).
- Diretório **demo** contém alguns resultados esperados do processamento de cada função (A melhor maneira de visualizar o conteúdo deste diretório é fazendo o download ou clonando o projeto).
- Diretório **prototipos** contém os protótipos das funções que deverão ser desenvolvidas.

## Introduction
For this first programming assignment you will write three functions that are meant to interact with dataset that accompanies this assignment. The dataset is contained in a zip file specdata.zip that you can download from the Coursera web site.

## Data
The zip file containing the data is atached;
* [specdata.zip [2.4MB]] (https://github.com/franciscomoura/data-science-and-bigdata/raw/master/introducao-linguagens-estatisticas/desafios-01/data/specdata.zip)

The zip file contains 332 comma-separated-value (CSV) files containing pollution monitoring data for fine particulate matter (PM) air pollution at 332 locations in the United States. Each file contains data from a single monitor and the ID number for each monitor is contained in the file name. For example, data for monitor 200 is contained in the file "200.csv". Each file contains three variables:

- *Date*: the date of the observation in YYYY-MM-DD format (year-month-day)
- *sulfate*: the level of sulfate PM in the air on that date (measured in micrograms per cubic meter)
- *nitrate*: the level of nitrate PM in the air on that date (measured in micrograms per cubic meter)

For this programming assignment you will need to unzip this file and create the directory 'specdata'. Once you have unzipped the zip file, do not make any modifications to the files in the 'specdata' directory. In each file you'll notice that there are many days where either sulfate or nitrate (or both) are missing (coded as NA). This is common with air pollution monitoring data in the United States.

## Part 1
Write a function named 'pollutantmean' that calculates the mean of a pollutant (sulfate or nitrate) across a specified list of monitors. The function 'pollutantmean' takes three arguments: 'directory', 'pollutant', and 'id'. Given a vector monitor ID numbers, 'pollutantmean' reads that monitors' particulate matter data from the directory specified in the 'directory' argument and returns the mean of the pollutant across all of the monitors, ignoring any missing values coded as NA. A prototype of the function is as follows

[prototype](https://github.com/franciscomoura/data-science-and-bigdata/blob/master/introducao-linguagens-estatisticas/desafios-01/prototipos/pollutantmean.png)

You can see some [example output from this function](https://d396qusza40orc.cloudfront.net/rprog%2Fdoc%2Fpollutantmean-demo.html). The function that you write should be able to match this output. Please save your code to a file named pollutantmean.R.

### My solution
[Here is the R archive] (https://github.com/franciscomoura/data-science-and-bigdata/blob/master/introducao-linguagens-estatisticas/desafios-01/pollutantmean.R)
```R
# The RStudio or R environment work space directory needs to be set
# to the appropriate directory.

# This file should be into this directory and the directory of the csv files
# should be under this directory too.

pollutantmean <- function(directory = "specdata", pollutant, id = 1:332) {
    ## 'directory' is a character vector of length 1 indicating the location of
    ## the CSV files

    ## 'pollutant' is a character vector of length 1 indicating the name of the
    ## pollutant for which we will calculate the mean; either 'sulfate' or
    ## 'nitrate'.

    ## 'id' is an integer vector indicating the monitor ID numbers to be used

    ## Return the mean of the pollutant across all monitors list in the 'id'
    ## vector (ignoring NA values)
    ## NOTE: Do not round the result!

    # Read the csv file, load, filtering and cleaning the data set
    reduce_csv_file <- function(file) {

        # Column names present on the data files an their data types.
        col_classes <- c("Date" = "character",
                         "sulfate" = "numeric",
                         "nitrate" = "numeric",
                         "ID" = "numeric")

        # Loaded data from CSV files
        income <- read.csv(file,
                           stringsAsFactors = FALSE,
                           sep = ",",
                           colClasses = col_classes)

        # Subsetting the income data set by the pollutant name.
        # The column of the data set will be selected by the pollutant name
        pollutant_dataset <- subset(income, select = c(pollutant))

        colnames(pollutant_dataset) <- c(pollutant)

        # Clean the data set
        # Subsetting the pollutant data set without NA values
        return(na.omit(pollutant_dataset))
    }

    # create a list of csv files to be read based on the id vector
    csv_files <- file.path(getwd(),
                           directory,
                           paste(formatC(id, width = 3, flag = 0),
                                 ".csv",
                                 sep=""))

    # Load, subsetting and merge the files
    data <- do.call(rbind, lapply(csv_files, reduce_csv_file ))

    return (mean(data[, 1], na.rm = TRUE))
}
```

## Part 2
Write a function that reads a directory full of files and reports the number of completely observed cases in each data file. The function should return a data frame where the first column is the name of the file and the second column is the number of complete cases. A prototype of this function follows

[prototype](https://github.com/franciscomoura/data-science-and-bigdata/blob/master/introducao-linguagens-estatisticas/desafios-01/prototipos/complete.png)

You can see some [example output from this function](https://d396qusza40orc.cloudfront.net/rprog%2Fdoc%2Fcomplete-demo.html). The function that you write should be able to match this output. Please save your code to a file named complete.R. To run the submit script for this part, make sure your working directory has the file complete.R in it.

### My solution
[Here is the R archive] (https://github.com/franciscomoura/data-science-and-bigdata/blob/master/introducao-linguagens-estatisticas/desafios-01/complete.R)
```R
# The RStudio or R environment work space directory needs to be set
# to the appropriate directory.

# This file should be into this directory and the directory of the csv files
# should be under this directory too.

complete <- function(directory = "specdata", id = 1:332) {
    ## 'directory' is a character vector of length 1 indicating the location
    ## of the CSV files.

    ## 'id' is an integer vector indicating the monitor ID numbers to be used

    ## Return a data frame of the form:
    ## id   nobs
    ##  1    117
    ##  2   1041
    ## ...
    ## where 'id' is the monitor ID number and 'nobs' is the number of
    ## complete cases

    # Read the csv file, load the data and calculate the complete cases
    calculate_completes <- function(id) {

        # create a list of csv files to be read based on the id vector
        file <- file.path(getwd(),
                           directory,
                           paste(formatC(id, width = 3, flag = 0),
                                 ".csv",
                                 sep=""))

        # Column names present on the data files an their data types.
        col_classes <- c("Date" = "character",
                         "sulfate" = "numeric",
                         "nitrate" = "numeric",
                         "ID" = "numeric")

        # Loaded data from CSV files
        income <- read.csv(file,
                           stringsAsFactors = FALSE,
                           sep = ",",
                           colClasses = col_classes)

        # compute and sum the complete cases present on the data file
        return(sum(complete.cases(income)))
    }

    # Compute the complete cases for each given id
    nobs <- sapply(id, calculate_completes)
    data <- data.frame(id, nobs)

    return(data)
}
```
## Part 3
Write a function that takes a directory of data files and a threshold for complete cases and calculates the correlation between sulfate and nitrate for monitor locations where the number of completely observed cases (on all variables) is greater than the threshold. The function should return a vector of correlations for the monitors that meet the threshold requirement. If no monitors meet the threshold requirement, then the function should return a numeric vector of length 0. A prototype of this function follows

[prototype](https://github.com/franciscomoura/data-science-and-bigdata/blob/master/introducao-linguagens-estatisticas/desafios-01/prototipos/corr.png)

For this function you will need to use the 'cor' function in R which calculates the correlation between two vectors. Please read the help page for this function via '?cor' and make sure that you know how to use it.

You can see some [example output from this function](https://d396qusza40orc.cloudfront.net/rprog%2Fdoc%2Fcorr-demo.html).

The function that you write should be able to match this output. Please save your code to a file named corr.R. To run the submit script for this part, make sure your working directory has the file corr.R in it.

### My solution
[Here is the R archive] (https://github.com/franciscomoura/data-science-and-bigdata/blob/master/introducao-linguagens-estatisticas/desafios-01/corr.R)
```R
# The RStudio or R environment work space directory needs to be set
# to the appropriate directory.

# This file should be into this directory and the directory of the csv files
# should be under this directory too.

# This file depends on complete.R file. So, load the last one first with the
# command source("complete.R")

corr <- function(directory = "specdata", threshold = 0) {
    ## 'directory' is a character vector of length 1 indicating the location
    ## of the CSV files.

    ## 'threshold' is a numeric vector of length 1 indicating the number of
    ## completely observed observations (on all variables) required to compute
    ## the correlation between nitrate and sulfate; the default is 0

    ## Return a numeric vector of correlations
    ## NOTE: Do not round the result!

    # verify the observations on all files under the given directory
    observations <- complete(directory)

    # select the monitor ids's that match the threshold condition
    monitor_ids <- observations[observations["nobs"] > threshold, ]$id

    correlations <- numeric()

    # read all csv files relative to the selected monitor id's
    for (id in monitor_ids) {

        # Column names present on the data files an their data types.
        col_classes <- c("Date" = "character",
                         "sulfate" = "numeric",
                         "nitrate" = "numeric",
                         "ID" = "numeric")

        file <- file.path(getwd(),
                          directory,
                          paste(formatC(id, width = 3, flag = 0),
                                ".csv",
                                sep=""))

        # Loaded data from CSV files
        income <- read.csv(file,
                           stringsAsFactors = FALSE,
                           sep = ",",
                           colClasses = col_classes)

        complete_cases <- income[complete.cases(income), ]
        correlations <- c(correlations,
                          cor(complete_cases$sulfate, complete_cases$nitrate))
    }

    return (correlations)
}
```

### External references
1. [specdata.zip [~3MB]](https://d396qusza40orc.cloudfront.net/rprog%2Fdata%2Fspecdata.zip)
2. [Pollutantmean function output demo](https://d396qusza40orc.cloudfront.net/rprog%2Fdoc%2Fpollutantmean-demo.html)
3. [Complete funcion output demo](https://d396qusza40orc.cloudfront.net/rprog%2Fdoc%2Fcomplete-demo.html)
4. [Corr function output demo](https://d396qusza40orc.cloudfront.net/rprog%2Fdoc%2Fcorr-demo.html)


text:
namespace Algorithms.RobertSedgewick.Fundamentals.DataStructures
{
    public sealed class GraphCyclePaths
    {
        private readonly bool[] _marked;

        public GraphCyclePaths(Graph graph)
        {
            _marked = new bool[graph.VertexCount];
            Dfs(graph, 0, 0);
        }

        public bool HasCycle { get; private set; }

        private void Dfs(Graph graph, int current, int past)
        {
            _marked[current] = true;

            foreach (int vertex in graph.Adjacent(current))
            {
                if (_marked[vertex] && vertex != past)
                {
                    HasCycle = true;
                    return;
                }
                else if (_marked[vertex])
                {
                    continue;
                }
                Dfs(graph, vertex, current);
            }
        }
    }
}


text: void v30xinit(void);


text:
'use strict';

module.exports = {
  name: 'input',
  classNames: ['modal', 'date', 'verify', 'draw'],
  sizes: ['smallsize']
};


text:
<?php

declare(strict_types=1);

namespace Windwalker\Database\Driver\Pdo;

use Windwalker\Database\Driver\AbstractConnection;

/**
 * The PdoConnection class.
 */
abstract class AbstractPdoConnection extends AbstractConnection
{
    protected static $name = 'pdo';

    /**
     * @var string
     */
    protected static $dbtype = '';

    protected static $defaultAttributes = [
        \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
        \PDO::ATTR_EMULATE_PREPARES => true,
        \PDO::ATTR_STRINGIFY_FETCHES => false
    ];

    /**
     * isSupported
     *
     * @return  bool
     */
    public static function isSupported(): bool
    {
        if (!class_exists(\PDO::class)) {
            return false;
        }

        return in_array(strtolower(static::$dbtype), \PDO::getAvailableDrivers(), true);
    }

    /**
     * getDsn
     *
     * @param  array  $options
     *
     * @return  string
     */
    public static function getDsn(array $options): string
    {
        return DsnHelper::build($options, static::$dbtype);
    }

    /**
     * doConnect
     *
     * @param  array  $options
     *
     * @return  \PDO
     */
    protected function doConnect(array $options)
    {
        $attrs = array_replace(
            static::$defaultAttributes,
            $options['driverOptions'] ?? []
        );

        return new \PDO(
            $options['dsn'],
            $options['username'] ?? null,
            $options['password'] ?? null,
            $attrs
        );
    }

    /**
     * @return \PDO|null
     */
    public function get(): ?\PDO
    {
        return parent::get();
    }

    /**
     * @inheritDoc
     */
    public function disconnect()
    {
        $this->connection = null;
    }

    /**
     * @return string
     */
    public static function getDbType(): string
    {
        return self::$dbtype;
    }
}


text:
<?php

namespace Plethora\Helper;

use Plethora\Helper;
use Plethora\Router;

class Html extends Helper {
    /**
     * Factory method.
     *
     * @access     public
     * @since      1.0.0-alpha
     * @version    1.0.0-alpha
     */
    public static function factory() {
        return new Html();
    }

    /**
     * Create anchor tag.
     *
     * @static
     * @access     public
     * @param      string     $sPath
     * @param      string     $sText
     * @param      Attributes $oAttributes
     * @return     string
     * @since      1.0.0-alpha
     * @version    1.0.0-alpha
     */
    public static function a($sPath, $sText, Attributes $oAttributes = NULL) {
        if($oAttributes === NULL) {
            $oAttributes = new Attributes();
        }

        $oAttributes->setAttribute('href', $sPath);

        return '<a '.$oAttributes->renderAttributes().'>'.$sText.'</a>';
    }

    /**
     * Create image tag.
     *
     * @static
     * @access     public
     * @param      string     $sImageSource
     * @param      string     $aAltText
     * @param      Attributes $oAttributes
     * @return     string
     * @since      1.0.0-alpha
     * @version    1.0.0-alpha
     */
    public static function img($sImageSource, $aAltText, Attributes $oAttributes = NULL) {
        if($oAttributes === NULL) {
            $oAttributes = new Attributes();
        }

        $oAttributes->setAttribute('src', $sImageSource);
        $oAttributes->setAttribute('alt', $aAltText);

        return '<img '.$oAttributes->renderAttributes().' />';
    }

    /**
     * Use the following method to remove white-spaces from the HTML code.
     *
     * @static
     * @access     public
     * @param      string $sString
     * @return     string
     * @since      1.0.0-alpha
     * @version    1.0.0-alpha
     */
    public static function minify($sString) {
        $aSearch = [
            '/\>[^\S ]+/s', // strip whitespaces after tags, except space
            '/[^\S ]+\</s', // strip whitespaces before tags, except space
            '/(\s)+/s'      // shorten multiple whitespace sequences
        ];

        $aReplace = [
            '>',
            '<',
            '\\1',
        ];

        $sSanitized = preg_replace($aSearch, $aReplace, $sString);

        return $sSanitized;
    }
}


text:
const unsigned g_REMOTE_CLIENT_TIMEOUT_MS = 1500;

// This class will handle the progress bar animation.
class AsyncProgressUpdater :
    public osThread
{
public:

    AsyncProgressUpdater() : osThread(GPU_STR_REMOTE_PROFILING_TASK_THREAD_NAME), mIsInProgress(true)
    {
        gtString progBarMsg = GPU_STR_REMOTE_PROFILE_IN_PROGRESS_PREFIX;
        progBarMsg.append(afProjectManager::instance().currentProjectSettings().remoteTargetName());
    }

    virtual int entryPoint()
    {
        unsigned char counter = 1;
        gtString progBarMsg = GPU_STR_REMOTE_PROFILE_IN_PROGRESS_PREFIX;
        progBarMsg.append(afProjectManager::instance().currentProjectSettings().remoteTargetName());

        while (mIsInProgress)
        {
            unsigned char val = counter++;

            if (counter > 3)
            {
                counter = 1;
            }

            gtString strToShow = progBarMsg;

            switch (val)
            {
                case 1:
                    strToShow.append(L".");
                    break;

                case 2:
                    strToShow.append(L"..");
                    break;

                case 3:
                    strToShow.append(L"...");
                    break;

                default:
                    strToShow.append(L".");
                    break;
            }

            // Notify.
            static const gtString profileName(GPU_STR_GENERAL_SETTINGS);
            apProfileProgressEvent eve(profileName, strToShow, 0);
            apEventsHandler::instance().registerPendingDebugEvent(eve);
            osSleep(500);
        }

        return 0;
    }

    void Stop()
    {
        mIsInProgress = false;
    }

private:
    bool mIsInProgress;

};

AsyncRemoteGpuProfilingTask::AsyncRemoteGpuProfilingTask(bool isCounterFileRequired, const gtString& strCounterFile,
                                                         bool isEnvVarFileRequired, bool isApiRulesFileRequired, bool isApiFilterFileRequired, const gtString& apiRulesFile, const gtString& strArguments,
                                                         const gtString& tempEnvVarFileName, const gtString& apiFilterFileName, const gtString& profileOutputDir, bool isKernelSpecific, const gtString& specificKernels) :
    osThread(L"AsyncRemoteGpuProfilingTask"),
    mCounterFileName(strCounterFile),
    mApiRulesFileName(apiRulesFile),
    mTempEnvVarFileName(tempEnvVarFileName),
    mApiFilterFileName(apiFilterFileName),
    mProfileOutputDir(profileOutputDir),
    mCmdLineArgsStr(strArguments),
    mSpecificKernels(specificKernels),
    mIsCounterFileRequired(isCounterFileRequired),
    mIsEnvVarFileRequired(isEnvVarFileRequired),
    mIsApiRulesFileRequired(isApiRulesFileRequired),
    mIsApiFilterFileRequired(isApiFilterFileRequired),
    mIsKernelSpecific(isKernelSpecific),
    mErrorObservers()
{

}

AsyncRemoteGpuProfilingTask::~AsyncRemoteGpuProfilingTask(void)
{
}

int AsyncRemoteGpuProfilingTask::entryPoint()
{
    // First, let the user know that we are attempting to start a remote GPU profiling session.
    static const gtString profileName(GPU_STR_GENERAL_SETTINGS);
    apProfileProgressEvent eve(profileName, GPU_STR_STARTING_REMOTE_SESSION, 0);
    apEventsHandler::instance().registerPendingDebugEvent(eve);

    QString errMsg;
    int rc = (ExecuteRemoteGpuProfiling(true, errMsg) ? 0 : -1);

    // Notify the observers.
    std::list<IAsyncErrorMessageConsumer*>::iterator iter;

    for (iter = mErrorObservers.begin(); iter != mErrorObservers.end(); ++iter)
    {
        if (*iter != NULL)
        {
            (*iter)->ConsumeErrorMessage(errMsg);
        }
    }

    return rc;
}

bool AsyncRemoteGpuProfilingTask::RemoteGpuProfilingHelper(CXLDaemonClient* pDmnClient, QString& strErrorMessageOut, bool& isRetryRelevant)
{
    // Verify the daemon's version.
    gtString handshakeErrorStrBuffer;
    bool isHandshakeMatch = false;
    bool retVal = pDmnClient->PerformHandshake(isHandshakeMatch, handshakeErrorStrBuffer);
    GT_ASSERT_EX(retVal, GPU_STR_REMOTE_HANDSHAKE_FALIURE);

    // Basically, retry should be helpful only if the first connection failed.
    isRetryRelevant = !retVal;

    if (retVal)
    {
        if (isHandshakeMatch)
        {
            // Handle kernel-specific profiling if required.
            gtVector<gtString> specificKernels;

            if (mIsKernelSpecific && !mSpecificKernels.isEmpty())
            {
                // Extract the kernel names.
                gtStringTokenizer tokenizer(mSpecificKernels, L";");
                gtString currKernelName;

                while (tokenizer.getNextToken(currKernelName))
                {
                    // Remove white spaces.
                    QString tmpStr = acGTStringToQString(currKernelName);
                    currKernelName = acQStringToGTString(tmpStr.trimmed());
                    specificKernels.push_back(currKernelName);
                    currKernelName.makeEmpty();
                }
            }

            // Progress notification.
            AsyncProgressUpdater* pProgUpdater = new(std::nothrow)AsyncProgressUpdater();

            pProgUpdater->execute();

            // Launch CodeXLGpuProfiler on the remote machine, and wait for it to finish.
            // An asynchronous implementation will be available in the future.
            RemoteClientError errorCode = rceUnknown;
            retVal = pDmnClient->LaunchGPUProfiler(mCmdLineArgsStr, mProfileOutputDir, mCounterFileName,
                                                   mTempEnvVarFileName, mApiFilterFileName, mApiRulesFileName, specificKernels, errorCode);

            if (errorCode == rceTargetAppNotFound)
            {
                // Do not retry.
                isRetryRelevant = false;

                // Set the relevant error message.
                strErrorMessageOut = GPU_STR_REMOTE_TARGET_APP_NOT_FOUND;
            }
            else if (errorCode == rcePortUnavailable)
            {
                // Do not retry.
                isRetryRelevant = false;

                // Set the relevant error message.
                strErrorMessageOut = QString::fromWCharArray(GPU_STR_REMOTE_TARGET_APP_PORT_OCCUPIED);
            }
            else if (errorCode == rceTargetAppIsAlreadyRunning)
            {
                // Do not retry.
                isRetryRelevant = false;

                // Set the relevant error message.
                strErrorMessageOut = GPU_STR_REMOTE_TARGET_APP_ALREADY_RUNNING;
            }

            // Stop progress notification.
            pProgUpdater->Stop();
            pProgUpdater->terminate();
            delete pProgUpdater;

        }
        else
        {
            retVal = false;

            if (handshakeErrorStrBuffer.isEmpty())
            {
                handshakeErrorStrBuffer = GPU_STR_REMOTE_HANDSHAKE_UNKNOWN_FAILURE;
            }

            OS_OUTPUT_DEBUG_LOG(handshakeErrorStrBuffer.asCharArray(), OS_DEBUG_LOG_ERROR);
            strErrorMessageOut = acGTStringToQString(handshakeErrorStrBuffer);
        }
    }
    else
    {
        gtString errMsg = GPU_STR_REMOTE_AGENT_VERSION_NOT_RETRIEVED;
        OS_OUTPUT_DEBUG_LOG(errMsg.asCharArray(), OS_DEBUG_LOG_ERROR);
        strErrorMessageOut = acGTStringToQString(errMsg);
    }

    return retVal;
}

bool AsyncRemoteGpuProfilingTask::ExecuteRemoteGpuProfiling(bool isRetryEnabled, QString& strErrorMessageOut)
{
    // Retrieve the daemon's address.
    gtUInt16 dmnPort = afProjectManager::instance().currentProjectSettings().remoteTargetDaemonConnectionPort();
    gtString dmnIp = afProjectManager::instance().currentProjectSettings().remoteTargetName();
    osPortAddress daemonAddr(dmnIp, dmnPort);

    // Initialize the daemon if required.
    bool retVal = CXLDaemonClient::IsInitialized(daemonAddr) ||
                  CXLDaemonClient::Init(daemonAddr, g_REMOTE_CLIENT_TIMEOUT_MS);
    GT_ASSERT_EX(retVal, GPU_STR_REMOTE_AGENT_INIT_FAILURE_WITH_CTX);

    // In recursive calls, make sure only one invocation handles the profile results.
    bool isHandleProfileResultRequired = true;

    CXLDaemonClient* pDmnClient = CXLDaemonClient::GetInstance();
    GT_IF_WITH_ASSERT(pDmnClient != NULL)
    {
        if (retVal)
        {

            // Connect to the daemon.
            osPortAddress addrBuffer;
            retVal = pDmnClient->ConnectToDaemon(addrBuffer);
            GT_IF_WITH_ASSERT(retVal)
            {
                bool isRetryRelevant = true;
                retVal = RemoteGpuProfilingHelper(pDmnClient, strErrorMessageOut, isRetryRelevant);

                if (!retVal && isRetryEnabled && isRetryRelevant)
                {
                    // Give it another shot. This is for scenarios where the remote daemon was terminated and then re-launched.
                    strErrorMessageOut.clear();
                    bool isTerminationSuccess = pDmnClient->TerminateWholeSession();
                    GT_ASSERT_EX(isTerminationSuccess, GPU_STR_REMOTE_SESSION_TERMINATION_FAILURE);
                    retVal = CXLDaemonClient::Init(daemonAddr, g_REMOTE_CLIENT_TIMEOUT_MS, true) && ExecuteRemoteGpuProfiling(false, strErrorMessageOut);

                    // No need to handle profile result, since the recursive call will do it for us.
                    isHandleProfileResultRequired = false;
                }
                else if (!isRetryRelevant)
                {
                    // Probably a communication loss issue. Notify the user.
                    gtString errMsg = GPU_STR_REMOTE_COMMUNICATION_FAILURE;

                    if (!strErrorMessageOut.isEmpty())
                    {
                        // If we got a more specific error message, then we
                        // should use it instead of the default message.
                        errMsg = acQStringToGTString(strErrorMessageOut);
                    }

                    OS_OUTPUT_DEBUG_LOG(errMsg.asCharArray(), OS_DEBUG_LOG_ERROR);
                    strErrorMessageOut = acGTStringToQString(errMsg);
                }
            }
            else
            {
                gtString errMsg = GPU_STR_REMOTE_CONNECTION_FAILURE;
                OS_OUTPUT_DEBUG_LOG(errMsg.asCharArray(), OS_DEBUG_LOG_ERROR);
                strErrorMessageOut = acGTStringToQString(errMsg);
            }
        }

        if (isHandleProfileResultRequired)
        {
            // Disconnect from the remote agent.
            pDmnClient->TerminateWholeSession();

            // Now handle the profile result.
            apProfileProcessTerminatedEvent eve(GPU_STR_GENERAL_SETTINGS, (retVal ? 0 : -1));
            apEventsHandler::instance().registerPendingDebugEvent(eve);
        }

    }
    else
    {
        gtString errMsg = GPU_STR_REMOTE_AGENT_INIT_FAILURE;
        OS_OUTPUT_DEBUG_LOG(errMsg.asCharArray(), OS_DEBUG_LOG_ERROR);
        strErrorMessageOut = acGTStringToQString(errMsg);
    }

    return retVal;
}

void AsyncRemoteGpuProfilingTask::Register(IAsyncErrorMessageConsumer* pAsyncErrorMessageConsumer)
{
    mErrorObservers.push_back(pAsyncErrorMessageConsumer);
}


text:
IAA-EACHUSP
===========

Repositório para códigos produzidos na matéria de Introdução à Análise de Algoritmos da EACH-USP

EP 2 IAA
========
### Produzido por:
* Adriano Augusto Satti Ortega Boschi
* Caio Vinícius Marques Teixeira
* Felipe Grecov Santana
* João Pedro Nardari dos Santos


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/RxDownloader.iml" filepath="$PROJECT_DIR$/RxDownloader.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/rxdownloader-lib/rxdownloader-lib.iml" filepath="$PROJECT_DIR$/rxdownloader-lib/rxdownloader-lib.iml" />
    </modules>
  </component>
</project>


text:
package main.util.codetester;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import main.student.studentdao.StudentDAO;
import main.util.filedetails.FileDetails;
import main.util.sshcommands.UsingJsch;

/*
 * - Partial marking System
 * - Destroy .class, .txt, .exe files
 */
public class FileOutputMatcher {
	static String path_output="";//path to the output file generated by the compiler
	static String path_check="";//Path to the actual output file uploaded by the professor
	static int m;
	static String ip;
	static String username;
	static String password;
	static int port=22;
	public FileOutputMatcher(String out,String check,int m){

		path_output = out;
		path_check = check;
		this.m = m;
		Properties prop=new Properties();
		try {
			prop.load(FileOutputMatcher.class.getResourceAsStream("/SSHinfo.properties"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		ip=prop.getProperty("ip");
		username=prop.getProperty("username");
		password=prop.getProperty("password");
	}

	public int CheckOutputs()throws IOException {
		// TODO Auto-generated method stub
		Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        PrintWriter pw=new PrintWriter(System.out);
        try{
        	JSch jsch = new JSch();
            session = jsch.getSession(username, ip, port);
            session.setPassword(password);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
           /* InputStream stream1=channelSftp.get(path_check);
   			BufferedReader reader2=new BufferedReader(new InputStreamReader(stream1));
            InputStream stream=channelSftp.get(path_output);
			BufferedReader reader1=new BufferedReader(new InputStreamReader(stream));
     		*/
            //String actual_output = reader1.readLine(); //This string reads the actual output file
			//String output = reader2.readLine();//This String reads the output file uploaded by the student
			String actual_output = UsingJsch.readingFile(path_output);
			String output = UsingJsch.readingFile(path_check);
            System.out.println("INSIDE FILEOUTPUTMATCHER");
			System.out.println("Actual Output::::\n"+actual_output+"Ends\n"+"Our output::::::\n"+output+"Ends");
			int lineNum=1;//The line being compared
			boolean areEqual=true;
			String actual_array[]=actual_output.split("\n");
			String output_array[]=output.split("\n");
			if(actual_array.length==output_array.length)
			{
				for(int i=0;i<actual_array.length;i++)
				{
					String actual_line=actual_array[i].trim();
					String output_line=output_array[i].trim();
					if(actual_line.equals(output_line))
					{
						continue;
					}
					else
					{
						areEqual=false;
						break;
					}
				}
			}
			else
			{
				areEqual=false;
			}
			if(actual_output.equals(output))
				areEqual = true;
	/*		while(actual_output!=null&&output!=null){
				pw.println(actual_output+" "+output);
				if(actual_output.equals(output)){
					//add marks
					areEqual = true;
				}else{
					areEqual = false;
					break;
				}
				actual_output = reader1.readLine();
				output = reader2.readLine();
				lineNum++;
			}*/
	//		reader1.close();
	//		reader2.close();
			if(areEqual){
				System.out.println("Test passed::"+m);
				pw.println("All test cases passed");
				return m;
			}else{
				System.out.println("Test Failed::"+lineNum);
				pw.println("Wrong Outputs at line = "+lineNum);
				return 0;//Confusion on what marks to reward for wrong output
			}
        }catch(Exception exc){
        	pw.println("Error Executing Code");
        	exc.printStackTrace();
        }
        pw.close();
        return 0;
	}

	public void DeleteFiles() throws Exception{
		FileDetails fl=new FileDetails();
		fl.deleteSSHFiles(path_output.substring(0, path_output.lastIndexOf("/")+1));
	}
}


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

namespace WoWLauncher
{
    public class Post
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public DateTime Date { get; set; }
        public string Url { get; set; }
    }

    public class NewsParser
    {
        private readonly Func<string, IEnumerable<Post>> _parse;
        public string PostFormat { get; }
        public NewsParser(Func<string, IEnumerable<Post>> parse, string format)
        {
            _parse = parse;
            PostFormat = format;
        }

        public IEnumerable<Post> Parse(string html)
        {
            return _parse(html);
        }
    }
}


text:
package parser

import (
	. "github.com/smartystreets/goconvey/convey"
	"testing"
)

func TestAssembleConditionCase(t *testing.T) {
	Convey("Given a parseStack", t, func() {
		ps := parseStack{}

		Convey("When the stack contains only WhenThenPairs in the given range (and no ELSE)", func() {
			ps.PushComponent(0, 4, Raw{"PRE"})
			ps.PushComponent(6, 7, StringLiteral{"foo"})
			ps.PushComponent(7, 8, RowValue{"", "a"})
			ps.AssembleWhenThenPair()
			ps.PushComponent(8, 9, StringLiteral{"bar"})
			ps.PushComponent(9, 10, RowValue{"", "b"})
			ps.AssembleWhenThenPair()
			ps.AssembleConditionCase(6, 10)

			Convey("Then AssembleConditionCase transforms them into one item", func() {
				So(ps.Len(), ShouldEqual, 2)

				Convey("And that item is a ConditionCaseAST", func() {
					top := ps.Peek()
					So(top, ShouldNotBeNil)
					So(top.begin, ShouldEqual, 6)
					So(top.end, ShouldEqual, 10)
					So(top.comp, ShouldHaveSameTypeAs, ConditionCaseAST{})

					Convey("And it contains the previously pushed data", func() {
						comp := top.comp.(ConditionCaseAST)
						So(len(comp.Checks), ShouldEqual, 2)
						So(comp.Checks[0], ShouldResemble,
							WhenThenPairAST{StringLiteral{"foo"}, RowValue{"", "a"}})
						So(comp.Checks[1], ShouldResemble,
							WhenThenPairAST{StringLiteral{"bar"}, RowValue{"", "b"}})
						So(comp.Else, ShouldBeNil)
					})
				})
			})
		})

		Convey("When the stack contains only WhenThenPairs in the given range and an ELSE", func() {
			ps.PushComponent(0, 4, Raw{"PRE"})
			ps.PushComponent(6, 7, StringLiteral{"foo"})
			ps.PushComponent(7, 8, RowValue{"", "a"})
			ps.AssembleWhenThenPair()
			ps.PushComponent(8, 9, StringLiteral{"bar"})
			ps.PushComponent(9, 10, RowValue{"", "b"})
			ps.AssembleWhenThenPair()
			ps.PushComponent(10, 12, RowValue{"", "y"})
			ps.AssembleConditionCase(6, 10)

			Convey("Then AssembleConditionCase transforms them into one item", func() {
				So(ps.Len(), ShouldEqual, 2)

				Convey("And that item is a ConditionCaseAST", func() {
					top := ps.Peek()
					So(top, ShouldNotBeNil)
					So(top.begin, ShouldEqual, 6)
					So(top.end, ShouldEqual, 12)
					So(top.comp, ShouldHaveSameTypeAs, ConditionCaseAST{})

					Convey("And it contains the previously pushed data", func() {
						comp := top.comp.(ConditionCaseAST)
						So(len(comp.Checks), ShouldEqual, 2)
						So(comp.Checks[0], ShouldResemble,
							WhenThenPairAST{StringLiteral{"foo"}, RowValue{"", "a"}})
						So(comp.Checks[1], ShouldResemble,
							WhenThenPairAST{StringLiteral{"bar"}, RowValue{"", "b"}})
						So(comp.Else, ShouldResemble, RowValue{"", "y"})
					})
				})
			})
		})

		Convey("When the given range is empty", func() {
			ps.PushComponent(0, 4, Raw{"PRE"})
			ps.PushComponent(4, 6, RowValue{"", "x"})

			Convey("Then AssembleConditionCase panics", func() {
				f := func() {
					ps.AssembleConditionCase(6, 6)
				}
				So(f, ShouldPanic)
			})
		})
	})

	Convey("Given a parser", t, func() {
		p := &bqlPeg{}

		Convey("When selecting a function of multiple columns", func() {
			p.Buffer = "SELECT ISTREAM " +
				`CASE WHEN "foo" THEN a WHEN "bar" THEN b ELSE y END, ` +
				`CASE WHEN "hoge" THEN x END`
			p.Init()

			Convey("Then the statement should be parsed correctly", func() {
				err := p.Parse()
				So(err, ShouldBeNil)
				p.Execute()

				ps := p.parseStack
				So(ps.Len(), ShouldEqual, 1)
				top := ps.Peek().comp
				So(top, ShouldHaveSameTypeAs, SelectStmt{})
				s := top.(SelectStmt)
				So(len(s.Projections), ShouldEqual, 2)

				So(s.Projections[0], ShouldHaveSameTypeAs, ConditionCaseAST{})
				comp := s.Projections[0].(ConditionCaseAST)
				So(len(comp.Checks), ShouldEqual, 2)
				So(comp.Checks[0], ShouldResemble,
					WhenThenPairAST{StringLiteral{"foo"}, RowValue{"", "a"}})
				So(comp.Checks[1], ShouldResemble,
					WhenThenPairAST{StringLiteral{"bar"}, RowValue{"", "b"}})
				So(comp.Else, ShouldResemble, RowValue{"", "y"})

				So(s.Projections[1], ShouldHaveSameTypeAs, ConditionCaseAST{})
				comp = s.Projections[1].(ConditionCaseAST)
				So(len(comp.Checks), ShouldEqual, 1)
				So(comp.Checks[0], ShouldResemble,
					WhenThenPairAST{StringLiteral{"hoge"}, RowValue{"", "x"}})
				So(comp.Else, ShouldBeNil)

				Convey("And String() should return the original statement", func() {
					So(s.String(), ShouldEqual, p.Buffer)
				})
			})
		})
	})
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>materials_commons.cli.sqltable module — materials_commons.cli 2.0b9 documentation</title>

  <link rel="stylesheet" href="../../site-static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../site-static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../site-static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../site-static/css/theme.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="materials_commons.cli.tmp_functions module" href="materials_commons.cli.tmp_functions.html" />
    <link rel="prev" title="materials_commons.cli.print_formatter module" href="materials_commons.cli.print_formatter.html" />

             materials_commons.cli

                2.0

  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Overview

Installation

User Manual

``mc`` Reference

``materials_commons.cli`` Reference

materials_commons namespace

Subpackages

materials_commons.cli package

Getting help

License

          materials_commons.cli

 »

materials_commons »

materials_commons namespace »

materials_commons.cli package »

materials_commons.cli.sqltable module

             View page source

materials_commons.cli.sqltable module¶

class materials_commons.cli.sqltable.SqlTable(proj_local_path)[source]¶

Bases: object

Generic code for interacting with one table in a project database

This is a base class. Derived classes must implement:

@staticmethod default_print_fmt(): list of tuple, used to format a table

@staticmethod tablecolumns(): dict, column name as key, list of table creation args for value

@staticmethod tablename(): str, table name in sqlite database

Parameters

proj_local_path – str, local project path

close()[source]¶

connect()[source]¶

Connect to sqlite database, creating database and table if necessary

insert_or_replace(record, verbose=False)[source]¶

Insert or replace individual entries in the table

Parameters

record – dict
Record to insert or replace in the database.

verbose – bool
If True, print status

print_selection(iterable, fmt=None)[source]¶

print_selection_detail(iterable, fmt=None)[source]¶

size()[source]¶

Return table size

materials_commons.cli.sqltable.dbpath(proj_local_path)[source]¶

Location of a sqlite database to cache project data locally

materials_commons.cli.sqltable.sql_iter(curs, fetchsize=1000)[source]¶

Iterate over the results of a SELECT statement

        Next
         Previous

        © Copyright 2021, PRISMS Center.

    Built with Sphinx using a

    theme

    provided by Read the Docs.


text:
/*
 * colorseg_reg.c
 *
 *   This explores the space of the four parameters input for color
 *   segmentation.  Of the four, only two strongly determine the
 *   output result:
 *      maxdist (the maximum distance between pixels that get
 *               clustered: 20 is very small, 180 is very large)
 *      selsize (responsible for smoothing the result: 0 is no
 *               smoothing (fine texture), 8 is large smoothing)
 *
 *   For large selsize (>~ 6), large regions get the same color,
 *   and there are few colors in the final result.
 *
 *   The other two parameters, maxcolors and finalcolors, can be
 *   set small (~4) or large (~20).  When set large, @maxdist will
 *   be most influential in determining the actual number of colors.
 */

#include "allheaders.h"

static const l_int32  MaxColors[] = {4, 8, 16};
static const l_int32  FinalColors[] = {4, 8, 16};

int main(int    argc,
         char **argv)
{
l_int32       i, j, k, maxdist, maxcolors, selsize, finalcolors;
l_int32       nc, rval, gval, bval;
PIX          *pixs, *pix1, *pix2;
PIXA         *pixa;
PIXCMAP      *cmap, *cmapr;
L_REGPARAMS  *rp;

    if (regTestSetup(argc, argv, &rp))
        return 1;

    pixs = pixRead("tetons.jpg");
    for (k = 0; k < 3; k++) {
        maxcolors = MaxColors[k];
        finalcolors = FinalColors[k];
        pixa = pixaCreate(0);
        pixSaveTiled(pixs, pixa, 1.0, 1, 15, 32);
        for (i = 1; i <= 9; i++) {
            maxdist = 20 * i;
            for (j = 0; j <= 6; j++) {
                selsize = j;
                pix1 = pixColorSegment(pixs, maxdist, maxcolors, selsize,
                                       finalcolors, 0);
                pixSaveTiled(pix1, pixa, 1.0, j == 0 ? 1 : 0, 15, 32);
                pixDestroy(&pix1);
            }
        }

        pix2 = pixaDisplay(pixa, 0, 0);
        regTestWritePixAndCheck(rp, pix2, IFF_JFIF_JPEG);  /* 0, 1, 2 */
        pixDisplayWithTitle(pix2, 100, k * 300, "colorseg", rp->display);
        pixDestroy(&pix2);
        pixaDestroy(&pixa);
    }
    pixDestroy(&pixs);

    pixs = pixRead("wyom.jpg");
    pix1 = pixColorSegment(pixs, 50, 6, 6, 6, 0);
    cmap = pixGetColormap(pix1);
    nc = pixcmapGetCount(cmap);
    cmapr = pixcmapCreateRandom(8, 0, 0);
    for (i = 0; i < nc; i++) {
        pix2 = pixMakeMaskFromVal(pix1, i);
        pixcmapGetColor(cmapr, i, &rval, &gval, &bval);
        pixRenderHashMaskArb(pixs, pix2, 0, 0, 8, 3, i % 4, 0,
                             rval, gval, bval);
        pixDestroy(&pix2);
    }
    regTestWritePixAndCheck(rp, pix1, IFF_PNG);  /* 3 */
    regTestWritePixAndCheck(rp, pixs, IFF_JFIF_JPEG);  /* 4 */
    pixDisplayWithTitle(pix1, 800, 0, NULL, rp->display);
    pixDisplayWithTitle(pixs, 800, 640, NULL, rp->display);
    pixDestroy(&pix1);
    pixDestroy(&pixs);
    pixcmapDestroy(&cmapr);

    return regTestCleanup(rp);
}