text:
@interface ViewController()

@property (nonatomic, strong) LayoutProvider *layoutProvider;
@property (nonatomic, strong) NoteManager *noteManager;
@property (nonatomic, strong) LocalNoteManager *localNoteManager;
@property (nonatomic, strong) DropboxNoteManager *dropboxManager;
@property (nonatomic, strong) ThemeManager *themeManager;
@property (nonatomic, strong) LeftPanelViewController *leftPanelViewController;
@property (nonatomic, strong) SettingsPanelViewController *settingsPanelViewController;
@property (nonatomic, strong) UISearchBar *searchBar;
@property NSString *currentNotebook;
@property NSArray *notesArray;
@property UIVisualEffectView *bluredView;
@property NSMutableArray *filteredNotes;
@property NSArray *allNotes;
@property BOOL isSearching;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }

    [DBClientsManager authorizeFromController:[UIApplication sharedApplication]
                                   controller:self
                                      openURL:^(NSURL *url) {
                                          [[UIApplication sharedApplication] openURL:url];
                                      }];

    self.layoutProvider = [LayoutProvider sharedInstance];
    self.localNoteManager = [[LocalNoteManager alloc] init];
    self.noteManager = [[NoteManager alloc] init];
    self.themeManager = [ThemeManager sharedInstance];
    self.filteredNotes = [[NSMutableArray alloc] init];

    [self createGeneralNotebook];
    [self setupNavigationBar];
    [self loadTheme];
    [self reloadTableViewData];
    [self.tableView registerNib:[UINib nibWithNibName:TABLEVIEW_CELL_ID bundle:nil] forCellReuseIdentifier:TABLEVIEW_CELL_ID];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNoteListChanged) name:NOTE_LIST_CHANGED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onThemeChanged) name:THEME_CHANGED_EVENT object:nil];
    self.currentNotebook = GENERAL_NOTEBOOK_NAME;
    [self.noteManager requestNoteListForNotebook:[[Notebook alloc]initWithName:self.currentNotebook]];
}

- (void)createGeneralNotebook
{
    [self.noteManager addNotebookWithName:GENERAL_NOTEBOOK_NAME];
}

- (void)reloadTableViewData
{
    dispatch_async(dispatch_get_main_queue(), ^(void){
        self.notesArray = [self.noteManager getNoteListForNotebookWithName:self.currentNotebook];
        [self.tableView reloadData];
    });
}

-   (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    self.bluredView.frame = CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, size.width, size.height);
}

- (void)setupBlurView
{
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.bluredView = [[UIVisualEffectView alloc] initWithEffect:effect];
    self.bluredView.frame = [UIScreen mainScreen].bounds;
    self.bluredView.alpha = BLUR_VIEW_ALPHA;
    self.bluredView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;

    UITapGestureRecognizer *tapRecogniser = [[UITapGestureRecognizer alloc]
                                             initWithTarget:self
                                             action:@selector(tapGestureRecognised:)];
    [self.bluredView addGestureRecognizer:tapRecogniser];
    tapRecogniser.delegate = self;
}

- (void)setupNavigationBar
{
    [self.navigationController.navigationBar setTintColor:[self.themeManager.styles objectForKey:TINT]];
    UIBarButtonItem *leftNavigationBarButton = [self.layoutProvider setupLeftBarButton:self
                                                                          action:@selector(drawerButtonPressed)];
    self.navigationController.topViewController.navigationItem.leftBarButtonItem = leftNavigationBarButton;
    leftNavigationBarButton.enabled = TRUE;

    UIBarButtonItem *rightNavigationBarButton = [self.layoutProvider setupRightBarButton:self
                                                                            action:@selector(addButtonPressed)];
    self.navigationController.topViewController.navigationItem.rightBarButtonItem = rightNavigationBarButton;
    rightNavigationBarButton.enabled = TRUE;

    self.searchBar = [[UISearchBar alloc] init];
    [self.searchBar setBarStyle:[[self.themeManager.styles objectForKey:SEARCH_BAR] integerValue]];
    self.searchBar.delegate = self;
    self.navigationController.topViewController.navigationItem.titleView = self.searchBar;
}

- (void)loadTheme
{
    [self.themeManager reload];
    self.tableView.backgroundColor = [self.themeManager.styles objectForKey:TABLEVIEW_BACKGROUND_COLOR];
    [self.navigationController.navigationBar setBarTintColor:[self.themeManager.styles objectForKey:NAVIGATION_BAR_COLOR]];
    [self.tableView reloadData];
    [self setupNavigationBar];
}

- (void)setupLeftPanel
{
    self.leftPanelViewController = [[LeftPanelViewController alloc] initWithNibName:LEFT_PANEL_NIBNAME bundle:nil manager:self.noteManager];
    self.leftPanelViewController.presentingViewControllerDelegate = self;
    [self.view addSubview:self.leftPanelViewController.view];
    [self setupBlurView];
    [self.view addSubview:self.bluredView];
    [self.view sendSubviewToBack:self.bluredView];
}

- (void)setupSettingsPanel
{
    self.settingsPanelViewController = [[SettingsPanelViewController alloc] initWithNibName:SETTINGS_PANEL_NIBNAME bundle:nil];
    self.settingsPanelViewController.delegate = self;
    [self.view addSubview:self.settingsPanelViewController.view];
}

#pragma mark -
#pragma mark Navigation bar buttons

- (void)drawerButtonPressed
{
    if(self.leftPanelViewController == nil)
    {
        [self setupLeftPanel];
    }

    if(self.leftPanelViewController.isHidden)
    {
        [self.noteManager requestNotebookList];
        [self showLeftPanel];
    }
    else
    {
        [self hideLeftPanel];
    }
}

- (void)addButtonPressed
{
    [self showNoteCreationControllerWithNote:[[Note alloc] init]];
}

-(void) showNoteCreationControllerWithNote:(Note *) note
{
    NoteCreationController *noteCreationController = [[NoteCreationController alloc] initWithManager:self.noteManager];
    noteCreationController.note = note;
    noteCreationController.currentNotebook = self.currentNotebook;
    [self.navigationController pushViewController:noteCreationController animated:YES];
}

#pragma mark -
#pragma mark TableViewCell delegates

- (void)panGestureRecognisedOnCell:(TableViewCell *)cell
{
    NSIndexPath *pathForDeleting = [self.tableView indexPathForCell:cell];
    [self.noteManager removeNote:cell.cellNote fromNotebookWithName:self.currentNotebook];
    self.notesArray = [self.noteManager getNoteListForNotebookWithName:self.currentNotebook];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:pathForDeleting] withRowAnimation:UITableViewRowAnimationRight];
}

- (void)tapGestureRecognisedOnCell:(TableViewCell *)cell
{
    [self showNoteCreationControllerWithNote:cell.cellNote];
}

- (void)exchangeObjectAtIndex:(NSInteger)firstIndex withObjectAtIndex:(NSInteger)secondIndex
{
    [self.noteManager exchangeNoteAtIndex:firstIndex withNoteAtIndex:secondIndex fromNotebook:self.currentNotebook];
}

#pragma mark -
#pragma mark TableView delegates

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.isSearching)
    {
        return [self.filteredNotes count];
    }
    else
    {
        return [self.notesArray count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.isSearching)
    {
        Note *note = [self.filteredNotes objectAtIndex:indexPath.row];
        return [self.layoutProvider searchResultCellWithNote:note notebook:[self.noteManager notebookContainingNote:note]];
    }
    else
    {
        return [self.layoutProvider newTableViewCell:tableView note:[self.notesArray objectAtIndex:indexPath.row] delegate:self];
    }
}

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

#pragma mark -
#pragma mark Notification handlers

-(void)onNoteListChanged
{
    [self reloadTableViewData];
}

- (void)onNoteCreated
{
    [self reloadTableViewData];
}

- (void)onThemeChanged
{
    [self loadTheme];
}

#pragma mark -
#pragma mark LeftPanelViewController delegates

- (void)hideLeftPanel
{
    [self.leftPanelViewController exitEditingMode];
    self.settingsPanelViewController.isHidden = YES;
    self.leftPanelViewController.isHidden = YES;
    [UIView animateWithDuration:0.5 animations:^{
        self.bluredView.alpha = 0;
        CGRect hiddenFrame = CGRectMake(-1 * LEFT_PANEL_WIDTH, 0, LEFT_PANEL_WIDTH, self.view.frame.size.height);
        self.leftPanelViewController.view.frame = hiddenFrame;
        self.settingsPanelViewController.view.frame = hiddenFrame;
    } completion:^(BOOL finished) {
        [self.view sendSubviewToBack:self.bluredView];
    }];
}

- (void)showLeftPanel
{
    [self.leftPanelViewController reloadTableViewData];
    [self.view bringSubviewToFront:self.bluredView];
    [self.view bringSubviewToFront:self.leftPanelViewController.view];
    self.leftPanelViewController.isHidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        self.bluredView.alpha = 0.9;
        self.leftPanelViewController.view.frame = CGRectMake(0, 0, LEFT_PANEL_WIDTH, self.view.frame.size.height);
    }];
}

- (void)showSettings
{
    if(self.settingsPanelViewController == nil)
    {
         [self setupSettingsPanel];
    }
    [self.view bringSubviewToFront:self.settingsPanelViewController.view];
    self.settingsPanelViewController.isHidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        self.settingsPanelViewController.view.frame = CGRectMake(0, 0, LEFT_PANEL_WIDTH, self.view.frame.size.height);
    }];
}

- (void)changeCurrentNotebook:(NSString *)newNotebookName
{
    self.currentNotebook = newNotebookName;
    self.notesArray = [self.noteManager getNoteListForNotebookWithName:self.currentNotebook];
    [self.tableView reloadData];
}

-(void)authDropbox
{
    [DBClientsManager authorizeFromController:[UIApplication sharedApplication]
                                   controller:self
                                      openURL:^(NSURL *url) {
                                          [[UIApplication sharedApplication] openURL:url];
                                      }];
}

#pragma mark -
#pragma mark Gesture recogniser delegates

- (void)tapGestureRecognised:(UITapGestureRecognizer *)tap
{
    [self hideLeftPanel];
}

#pragma mark -
#pragma mark SearchBar delegates

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    self.isSearching = YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.filteredNotes removeAllObjects];

    if([searchText length] != 0)
    {
        self.isSearching = YES;
        [self filterNotes];
    }
    else
    {
        self.isSearching = NO;
    }
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}

- (void)filterNotes
{
    NSString *searchString = self.searchBar.text;
    for (Note *currentNote in self.allNotes)
    {
        NSString *currentNoteName = currentNote.name;

        if ([currentNoteName rangeOfString:searchString options:NSCaseInsensitiveSearch].location != NSNotFound)
        {
            [self.filteredNotes addObject:currentNote];
        }
    }
}

@end


text:
typedef enum {
  NOFILEOPENED,
  READINGFILE,
  FILEREADERERROR,
} FileReaderState;

typedef struct FileReaderProcessConfig {

  int channels;
  int read_size;
  bstring pattern;

  // number of files to read before quitting
  // mostly used for testing
  // -1 means forever
  int filenumber;

  int thread_sleep;
  int max_push_msgs;

  int *status_var;

  RingBuffer *pipe_out;

} FileReaderProcessConfig;

FileReaderProcessConfig *filereader_config_create(int channels,
                                                  int read_size,
                                                  bstring pattern,
                                                  int filenumber,
                                                  int thread_sleep,
                                                  int max_push_msgs,
                                                  int *status_var,
                                                  RingBuffer *pipe_out);

void filereader_config_destroy(FileReaderProcessConfig *cfg);

void *start_filereader(void *_cfg);

#endif

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by chensheng on 17/5/28.
 */
function sys_menu_update() {
    var form = jQuery('#sys_menu_update_form');
    var url = form.attr("action");
    form.form('submit',{
        url: url,
        success: function (data) {
            data = jQuery.parseJSON(data);
            if(data.success){
                tabRefresh("/sys_menu/index");
            }else{
                jQuery.messager.show({msg: data.message});
            }
        }
    });
}


text:
<?php

namespace Gearbox\ApiBundle\Model;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;
use Gearbox\ApiBundle\Exception\InvalidFormException;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormTypeInterface;

class AbstractApiManager implements ApiManagerInterface
{
    const METHOD_PUT = 'PUT';

    const METHOD_POST = 'POST';

    const METHOD_PATCH = 'PATCH';

    /**
     * @var ObjectManager
     */
    protected $om;

    /**
     * @var string
     */
    protected $entityClass;

    /**
     * @var FormFactoryInterface
     */
    protected $formFactory;

    /**
     * @var string|FormInterface
     */
    protected $form;

    /**
     * @param string $entityClass
     * @param string|FormTypeInterface $form Form name or actual form instance
     */
    public function __construct($entityClass, $form)
    {
        $this->entityClass = $entityClass;
        $this->form        = $form;
    }

    /**
     * @param ObjectManager $objectManager
     *
     * @return $this
     */
    public function setObjectManager(ObjectManager $objectManager)
    {
        $this->om = $objectManager;

        return $this;
    }

    /**
     * @param FormFactoryInterface $formFactory
     *
     * @return $this
     */
    public function setFormFactory(FormFactoryInterface $formFactory)
    {
        $this->formFactory = $formFactory;

        return $this;
    }

    /**
     * Create form
     *
     * @param object $entity
     * @param string $method
     *
     * @return FormInterface
     */
    protected function createForm($entity, $method = self::METHOD_PUT)
    {
        if (is_string($this->form)) {
            return $this->formFactory->createNamed($this->form, 'form', $entity, array('method' => $method));
        }

        return $this->formFactory->create($this->form, $entity, array('method' => $method));
    }

    /**
     * Process entity parameters using a form
     *
     * @param object $entity
     * @param array $parameters
     * @param string $method
     *
     * @return object
     *
     * @throws InvalidFormException
     */
    protected function processForm($entity, array $parameters, $method = self::METHOD_PUT)
    {
        $form     = $this->createForm($entity, $method);
        $formName = $form->getName();
        if (array_key_exists($formName, $parameters)) {
            $form->submit($parameters[$formName], self::METHOD_PATCH !== $method);
            if ($form->isValid()) {
                return $this->saveEntity($form->getData());
            }
        }

        throw new InvalidFormException('Invalid submitted data', $form);
    }

    /**
     * Get new entity
     *
     * @return object New instance of entityClass
     */
    protected function createEntity()
    {
        return new $this->entityClass();
    }

    /**
     * Save entity
     *
     * @param object $entity
     *
     * @return object
     */
    protected function saveEntity($entity)
    {
        $this->om->persist($entity);
        $this->om->flush($entity);

        return $entity;
    }

    /**
     * Delete entity
     *
     * @param object $entity
     */
    protected function deleteEntity($entity)
    {
        $this->om->remove($entity);
        $this->om->flush($entity);
    }

    /**
     * Get entity repository
     *
     * @return ObjectRepository
     */
    protected function getRepository()
    {
        return $this->om->getRepository($this->entityClass);
    }
}


text:
---
title : Children (Pages filles)
description : Liste les pages filles de la page
---

Utilisez le shortcode *children* pour lister les pages filles de la page et tous ses déscendants (pages filles de pages filles). Par défaut, le shortcode affiche des liens vers les pages filles.

## Utilisation

| Paramètre | Défaut | Description |
|:--|:--|:--|
| page | _current_ | Spécifie le nom de la page (nom de la section) à afficher |
| style | "li" | Choisi le style à utiliser pour afficher les descendants. Cela peut être n'importe quel balise HTML |
| showhidden | "false" | Quand *true*, pages filles cachées dans le menu seront affichées quand même |
| description  | "false" | Permet d'inclure le texte de la description de la page sous chaque entré de la liste.
quand aucune description existe pour la page, le shortcode prend les 70 premiers mots du contenu. [plus d'infos sur gohugo.io](https://gohugo.io/content/summaries/)  |
| depth | 1 | Nombre de descendants à afficher. Par exemple, si la valeur est 2, le shortcode va afficher 2 niveaux de pages filels.
 **Astuce:** Utilisez 999 pour avoir tous les descendants|
| sort | <rien> | Tri les pages filles par

Weight - Poids

Name - Nom

Identifier - Trier alphabétiquement par identifiant configuré dans le front matter

URL - URL
 |

## Démo

	{{%/* children  */%}}

{{% children %}}

	{{%/* children description="true"   */%}}

{{%children description="true"   %}}

	{{%/* children depth="3" showhidden="true" */%}}

{{% children depth="3" showhidden="true" %}}

	{{%/* children style="h2" depth="3" description="true" */%}}

{{% children style="h2" depth="3" description="true" %}}

	{{%/* children style="div" depth="999" */%}}

{{% children style="div" depth="999" %}}


text:
package edu.brown.ebirenbaum.barwidget;

import android.app.Activity;
import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.NumberPicker;

/**
 * The main Activity for the BarView demo app.
 *
 * @author evanb
 */
public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction()
					.add(R.id.container, new BarViewFragment()).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu. This adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * The main Fragment for the BarView demo app.
	 *
	 * @author evanb
	 */
	public static class BarViewFragment extends Fragment implements OnClickListener {

		// The bars in the "Animate!" section
		private BarView mStandardBar, mDividedBar, mStandardBarReversed, mDividedBarReversed;

		// The views associated with the customizable BarView at the bottom of the app
		private BarView mCustomizableBar;
		private NumberPicker mPercentagePicker, mPrimaryPicker, mSecondaryPicker;
		private CheckBox mDividerCheckbox, mVerticalCheckbox, mReversedCheckbox, mAnimateCheckbox;

		public BarViewFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			// Inflate the main fragment
			View rootView = inflater.inflate(R.layout.fragment_main, container, false);

			// Find the BarView's in the "Animate!" section
			mStandardBar = (BarView) rootView.findViewById(R.id.demo_bar_view_standard);
			mDividedBar = (BarView) rootView.findViewById(R.id.demo_bar_view_divided);
			mStandardBarReversed = (BarView) rootView.findViewById(R.id.demo_bar_view_standard_reversed);
			mDividedBarReversed = (BarView) rootView.findViewById(R.id.demo_bar_view_divided_reversed);

			// Find the customizable BarView
			mCustomizableBar = (BarView) rootView.findViewById(R.id.demo_bar_customizable);

			// Find and set up the pickers for fill and color for the customizable BarView
			mPercentagePicker = (NumberPicker) rootView.findViewById(R.id.demo_bar_option_fill);
			mPrimaryPicker = (NumberPicker) rootView.findViewById(R.id.demo_bar_option_primary_color);
			mSecondaryPicker = (NumberPicker) rootView.findViewById(R.id.demo_bar_option_secondary_color);
			setupPickers();

			// Find the check boxes for the customizable BarView
			mDividerCheckbox = (CheckBox) rootView.findViewById(R.id.demo_bar_option_divider);
			mVerticalCheckbox = (CheckBox) rootView.findViewById(R.id.demo_bar_option_vertical);
			mReversedCheckbox = (CheckBox) rootView.findViewById(R.id.demo_bar_option_reversed);
			mAnimateCheckbox = (CheckBox) rootView.findViewById(R.id.demo_bar_option_animate);

			// Find the animate buttons and give them an OnClickListener
			Button animateButton = (Button) rootView.findViewById(R.id.demo_bar_view_animate_button);
			animateButton.setOnClickListener(this);
			Button resetButton = (Button) rootView.findViewById(R.id.demo_bar_view_reset_button);
			resetButton.setOnClickListener(this);

			return rootView;
		}

		/**
		 * Sets up the fill and color pickers for the customizable BarView.
		 */
		private void setupPickers() {

			// The bar will have a fill of [0,100], which is divided by 100
			mPercentagePicker.setMinValue(0);
			mPercentagePicker.setMaxValue(100);
			mPercentagePicker.setValue(50);
			mPercentagePicker.setWrapSelectorWheel(false);

			// The following colors can be parsed by android.graphics.Color.parseColor()
			String[] colors = { "red", "blue", "green", "black", "white",
								"gray", "cyan", "magenta", "yellow", "lightgray",
								"darkgray" };

			// Give both pickers the available colors, and have the secondary start on a different one
			mPrimaryPicker.setDisplayedValues(colors);
			mPrimaryPicker.setMinValue(0);
			mPrimaryPicker.setMaxValue(colors.length - 1);
			mSecondaryPicker.setDisplayedValues(colors);
			mSecondaryPicker.setMinValue(0);
			mSecondaryPicker.setMaxValue(colors.length - 1);
			mSecondaryPicker.setValue(1);
		}

		@Override
		public void onClick(View v) {

			// If this is the animate button, start animations on the appropriate BarViews
			if (v.getId() == R.id.demo_bar_view_animate_button) {
				mStandardBar.startBarAnimation();
				mDividedBar.startBarAnimation();
				mStandardBarReversed.startBarAnimation();
				mDividedBarReversed.startBarAnimation();

			// If this is the reset button, interpret the current state of the UI and customize the BarView
			} else if (v.getId() == R.id.demo_bar_view_reset_button) {

				// First do visibility and orientation updates
				mCustomizableBar.setDividerVisibility(mDividerCheckbox.isChecked());
				mCustomizableBar.setVertical(mVerticalCheckbox.isChecked());
				mCustomizableBar.setReversed(mReversedCheckbox.isChecked());
				mCustomizableBar.setBarPercentage((float)mPercentagePicker.getValue() / 100f);

				// Then update colors
				mCustomizableBar.setPrimaryBarColor(Color.parseColor(
						mPrimaryPicker.getDisplayedValues()[mPrimaryPicker.getValue()]));
				mCustomizableBar.setSecondaryBarColor(Color.parseColor(
						mSecondaryPicker.getDisplayedValues()[mSecondaryPicker.getValue()]));

				// Animate the bar if requested, else invalidate it to force a re-draw
				if (mAnimateCheckbox.isChecked()) {
					mCustomizableBar.startBarAnimation();
				} else {
					mCustomizableBar.invalidate();
				}
			}
		}
	}
}


text:
namespace MassTransit.AzureServiceBusTransport.Pipeline
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Contexts;
    using GreenPipes;
    using Logging;
    using Transport;

    public abstract class ClientContextFactory :
        JoinContextFactory<NamespaceContext, MessagingFactoryContext, ClientContext>
    {
        static readonly ILog _log = Logger.Get<ClientContextFactory>();

        readonly ClientSettings _settings;

        protected ClientContextFactory(IMessagingFactoryCache messagingFactoryCache, INamespaceCache namespaceCache, IPipe<MessagingFactoryContext> messagingFactoryPipe,
            IPipe<NamespaceContext> namespacePipe, ClientSettings settings)
            : base(namespaceCache, namespacePipe, messagingFactoryCache, messagingFactoryPipe)
        {
            _settings = settings;
        }

        protected override ClientContext CreateClientContext(NamespaceContext leftContext, MessagingFactoryContext rightContext)
        {
            var inputAddress = _settings.GetInputAddress(rightContext.ServiceAddress, _settings.Path);

            if (_log.IsDebugEnabled)
                _log.DebugFormat("Creating client: {0}", inputAddress);

            return CreateClientContext(rightContext, inputAddress);
        }

        protected abstract ClientContext CreateClientContext(MessagingFactoryContext connectionContext, Uri inputAddress);

        protected override async Task<ClientContext> CreateSharedContext(Task<ClientContext> context, CancellationToken cancellationToken)
        {
            var clientContext = await context.ConfigureAwait(false);

            var sharedContext = new SharedClientContext(clientContext, cancellationToken);

            return sharedContext;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Reflection;

using bsn.GoldParser.Grammar;

namespace bsn.GoldParser.Semantic {
	public class SemanticNonterminalTypeFactory<TBase, TOutput>: SemanticNonterminalFactory<TBase, TOutput> where TBase: SemanticToken where TOutput: TBase {
		private readonly SemanticNonterminalTypeFactoryHelper<TBase>.Activator<TOutput> activator;
		private readonly ReadOnlyCollection<Type> inputTypes;

		public SemanticNonterminalTypeFactory(MethodBase methodBase, int[] parameterMapping, int handleCount, Type baseTokenType) {
			if (methodBase == null) {
				throw new ArgumentNullException("methodBase");
			}
			if (parameterMapping == null) {
				throw new ArgumentNullException("parameterMapping");
			}
			if (baseTokenType == null) {
				throw new ArgumentNullException("baseTokenType");
			}
			ParameterInfo[] parameters = methodBase.GetParameters();
			if (parameterMapping.Length != parameters.Length) {
				throw new ArgumentException("The parameter mapping must have exactly as many items as the "+methodBase.MemberType+" has parameters", "parameterMapping");
			}
			int requiredHandles = 0;
			foreach (int i in parameterMapping) {
				if (i >= 0) {
					requiredHandles++;
				}
			}
			if (handleCount < requiredHandles) {
				throw new ArgumentOutOfRangeException("handleCount");
			}
			Type[] inputTypeBuilder = new Type[handleCount];
			for (int i = 0; i < handleCount; i++) {
				inputTypeBuilder[i] = baseTokenType;
			}
			foreach (ParameterInfo parameter in parameters) {
				int tokenIndex = parameterMapping[parameter.Position];
				if (tokenIndex != -1) {
					inputTypeBuilder[tokenIndex] = parameter.ParameterType;
				}
			}
			inputTypes = Array.AsReadOnly(inputTypeBuilder);
			activator = SemanticNonterminalTypeFactoryHelper<TBase>.CreateActivator(this, methodBase, parameterMapping);
			Debug.Assert(activator != null);
		}

		public override ReadOnlyCollection<Type> InputTypes {
			get {
				return inputTypes;
			}
		}

		public override TOutput Create(Rule rule, IList<TBase> tokens) {
			Debug.Assert((tokens != null) && (tokens.Count == inputTypes.Count));
			return activator(tokens);
		}
	}
}


text:
namespace domains {
template <typename T>
concept bool Commit = requires(T t) {
   { t.id() } const noexcept -> EqualityComparable;
   { t.stream_id() } const noexcept -> EqualityComparable;
   { t.timestamp() } const noexcept -> TimePoint;
   { t.commit_sequence() } const noexcept -> UnsignedIntegral;
   { t.version() } const noexcept -> UnsignedIntegral;
   { t.events() } const noexcept -> EventRange;
};

template <EqualityComparable CommitIdType = std::uint64_t,
          EqualityComparable StreamIdType = std::uint64_t,
          TimePoint TimestampType = std::chrono::nanoseconds,
          UnsignedIntegral CommitSequenceType = std::uint32_t,
          UnsignedIntegral StreamVersionType = std::uint32_t>
class commit {
   CommitIdType id_;
   CommitSequenceType commit_sequence_;
   StreamIdType stream_id_;
   StreamVersionType stream_version_;
   TimestampType timestamp_;

public:
   constexpr commit(
         CommitIdType cid, CommitSequenceType const cs, StreamIdType sid, StreamVersionType const sv,
         TimestampType const ts) noexcept :
      id_{std::move(cid)},
      commit_sequence_{cs},
      stream_id_{std::move(sid)},
      stream_version_{sv},
      timestamp_{ts}
   {
   }

   constexpr auto id() const noexcept {
      return id_;
   }

   constexpr auto sequence() const noexcept {
      return commit_sequence_;
   }

   constexpr auto stream_id() const noexcept {
      reutrn stream_id_;
   }

   constexpr auto stream_version() const noexcept {
      return stream_version_;
   }

   constexpr auto timestamp() const noexcept {
      return timestamp_;
   }
};

}


text:
package org.killbill.billing.tenant.api;

public interface TenantData {

    public String getExternalKey();

    public String getApiKey();

    /**
     * Note that we don't expose in the API how the
     * secret is stored (with or without salt, hashing algorithm)
     * so we can change it later
     *
     * @return the decrypted api secret
     */
    public String getApiSecret();
}


text:
.. clitool documentation master file, created by
   sphinx-quickstart on Thu Nov  8 00:56:18 2012.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

===================================
What's clitool
===================================

`clitool` is a handy library to support you implementing command line script.
This library cuts off redundant argument parsing and configuration loading,
and also provides a feature to handle streaming data with some logging.

You can try a simple solution to parse Apache accesslog and create key/value
report. This will be suitable for Hadoop Streaming environment.

List of features are:

* One line argument parsing function and decorator
* Simple configuration loader
* Stream utility with some logging
* CSV reader/writer unicode support for Python 2.x (in official document)
* Apache accesslog parser

Contents:

.. toctree::
   :maxdepth: 2

   examples
   clitool

==========
Changes
==========

.. include:: ../CHANGES.rst


text:
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_HEAP_GC_TRACER_H_
#define V8_HEAP_GC_TRACER_H_

#include "src/base/compiler-specific.h"
#include "src/base/platform/platform.h"
#include "src/base/ring-buffer.h"
#include "src/counters.h"
#include "src/globals.h"
#include "testing/gtest/include/gtest/gtest_prod.h"

namespace v8 {
namespace internal {

typedef std::pair<uint64_t, double> BytesAndDuration;

inline BytesAndDuration MakeBytesAndDuration(uint64_t bytes, double duration) {
  return std::make_pair(bytes, duration);
}

enum ScavengeSpeedMode { kForAllObjects, kForSurvivedObjects };

#define INCREMENTAL_SCOPES(F)                                      \
  /* MC_INCREMENTAL is the top-level incremental marking scope. */ \
  F(MC_INCREMENTAL)                                                \
  F(MC_INCREMENTAL_SWEEPING)                                       \
  F(MC_INCREMENTAL_WRAPPER_PROLOGUE)                               \
  F(MC_INCREMENTAL_WRAPPER_TRACING)                                \
  F(MC_INCREMENTAL_FINALIZE)                                       \
  F(MC_INCREMENTAL_FINALIZE_BODY)                                  \
  F(MC_INCREMENTAL_FINALIZE_OBJECT_GROUPING)                       \
  F(MC_INCREMENTAL_EXTERNAL_EPILOGUE)                              \
  F(MC_INCREMENTAL_EXTERNAL_PROLOGUE)

#define TRACER_SCOPES(F)                      \
  INCREMENTAL_SCOPES(F)                       \
  F(EXTERNAL_EPILOGUE)                        \
  F(EXTERNAL_PROLOGUE)                        \
  F(EXTERNAL_WEAK_GLOBAL_HANDLES)             \
  F(MC_CLEAR)                                 \
  F(MC_CLEAR_CODE_FLUSH)                      \
  F(MC_CLEAR_DEPENDENT_CODE)                  \
  F(MC_CLEAR_GLOBAL_HANDLES)                  \
  F(MC_CLEAR_MAPS)                            \
  F(MC_CLEAR_SLOTS_BUFFER)                    \
  F(MC_CLEAR_STORE_BUFFER)                    \
  F(MC_CLEAR_STRING_TABLE)                    \
  F(MC_CLEAR_WEAK_CELLS)                      \
  F(MC_CLEAR_WEAK_COLLECTIONS)                \
  F(MC_CLEAR_WEAK_LISTS)                      \
  F(MC_EPILOGUE)                              \
  F(MC_EVACUATE)                              \
  F(MC_EVACUATE_CANDIDATES)                   \
  F(MC_EVACUATE_CLEAN_UP)                     \
  F(MC_EVACUATE_COPY)                         \
  F(MC_EVACUATE_UPDATE_POINTERS)              \
  F(MC_EVACUATE_UPDATE_POINTERS_TO_EVACUATED) \
  F(MC_EVACUATE_UPDATE_POINTERS_TO_NEW)       \
  F(MC_EVACUATE_UPDATE_POINTERS_WEAK)         \
  F(MC_FINISH)                                \
  F(MC_MARK)                                  \
  F(MC_MARK_FINISH_INCREMENTAL)               \
  F(MC_MARK_PREPARE_CODE_FLUSH)               \
  F(MC_MARK_ROOTS)                            \
  F(MC_MARK_WEAK_CLOSURE)                     \
  F(MC_MARK_WEAK_CLOSURE_EPHEMERAL)           \
  F(MC_MARK_WEAK_CLOSURE_WEAK_HANDLES)        \
  F(MC_MARK_WEAK_CLOSURE_WEAK_ROOTS)          \
  F(MC_MARK_WEAK_CLOSURE_HARMONY)             \
  F(MC_MARK_WRAPPER_EPILOGUE)                 \
  F(MC_MARK_WRAPPER_PROLOGUE)                 \
  F(MC_MARK_WRAPPER_TRACING)                  \
  F(MC_MARK_OBJECT_GROUPING)                  \
  F(MC_PROLOGUE)                              \
  F(MC_SWEEP)                                 \
  F(MC_SWEEP_CODE)                            \
  F(MC_SWEEP_MAP)                             \
  F(MC_SWEEP_OLD)                             \
  F(MINOR_MC_MARK)                            \
  F(MINOR_MC_MARK_CODE_FLUSH_CANDIDATES)      \
  F(MINOR_MC_MARK_GLOBAL_HANDLES)             \
  F(MINOR_MC_MARK_OLD_TO_NEW_POINTERS)        \
  F(MINOR_MC_MARK_ROOTS)                      \
  F(MINOR_MC_MARK_WEAK)                       \
  F(SCAVENGER_CODE_FLUSH_CANDIDATES)          \
  F(SCAVENGER_OLD_TO_NEW_POINTERS)            \
  F(SCAVENGER_ROOTS)                          \
  F(SCAVENGER_SCAVENGE)                       \
  F(SCAVENGER_SEMISPACE)                      \
  F(SCAVENGER_WEAK)

#define TRACE_GC(tracer, scope_id)                             \
  GCTracer::Scope::ScopeId gc_tracer_scope_id(scope_id);       \
  GCTracer::Scope gc_tracer_scope(tracer, gc_tracer_scope_id); \
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"),             \
               GCTracer::Scope::Name(gc_tracer_scope_id))

// GCTracer collects and prints ONE line after each garbage collector
// invocation IFF --trace_gc is used.
class V8_EXPORT_PRIVATE GCTracer {
 public:
  struct IncrementalMarkingInfos {
    IncrementalMarkingInfos() : duration(0), longest_step(0), steps(0) {}

    void Update(double duration) {
      steps++;
      this->duration += duration;
      if (duration > longest_step) {
        longest_step = duration;
      }
    }

    void ResetCurrentCycle() {
      duration = 0;
      longest_step = 0;
      steps = 0;
    }

    double duration;
    double longest_step;
    int steps;
  };

  class Scope {
   public:
    enum ScopeId {
#define DEFINE_SCOPE(scope) scope,
      TRACER_SCOPES(DEFINE_SCOPE)
#undef DEFINE_SCOPE
          NUMBER_OF_SCOPES,

      FIRST_INCREMENTAL_SCOPE = MC_INCREMENTAL,
      LAST_INCREMENTAL_SCOPE = MC_INCREMENTAL_EXTERNAL_PROLOGUE,
      NUMBER_OF_INCREMENTAL_SCOPES =
          LAST_INCREMENTAL_SCOPE - FIRST_INCREMENTAL_SCOPE + 1
    };

    Scope(GCTracer* tracer, ScopeId scope);
    ~Scope();
    static const char* Name(ScopeId id);

   private:
    GCTracer* tracer_;
    ScopeId scope_;
    double start_time_;
    RuntimeCallTimer timer_;

    DISALLOW_COPY_AND_ASSIGN(Scope);
  };

  class Event {
   public:
    enum Type {
      SCAVENGER = 0,
      MARK_COMPACTOR = 1,
      INCREMENTAL_MARK_COMPACTOR = 2,
      MINOR_MARK_COMPACTOR = 3,
      START = 4
    };

    Event(Type type, GarbageCollectionReason gc_reason,
          const char* collector_reason);

    // Returns a string describing the event type.
    const char* TypeName(bool short_name) const;

    // Type of event
    Type type;

    GarbageCollectionReason gc_reason;
    const char* collector_reason;

    // Timestamp set in the constructor.
    double start_time;

    // Timestamp set in the destructor.
    double end_time;

    // Memory reduction flag set.
    bool reduce_memory;

    // Size of objects in heap set in constructor.
    size_t start_object_size;

    // Size of objects in heap set in destructor.
    size_t end_object_size;

    // Size of memory allocated from OS set in constructor.
    size_t start_memory_size;

    // Size of memory allocated from OS set in destructor.
    size_t end_memory_size;

    // Total amount of space either wasted or contained in one of free lists
    // before the current GC.
    size_t start_holes_size;

    // Total amount of space either wasted or contained in one of free lists
    // after the current GC.
    size_t end_holes_size;

    // Size of new space objects in constructor.
    size_t new_space_object_size;

    // Size of survived new space objects in destructor.
    size_t survived_new_space_object_size;

    // Bytes marked incrementally for INCREMENTAL_MARK_COMPACTOR
    size_t incremental_marking_bytes;

    // Duration of incremental marking steps for INCREMENTAL_MARK_COMPACTOR.
    double incremental_marking_duration;

    // Amounts of time spent in different scopes during GC.
    double scopes[Scope::NUMBER_OF_SCOPES];

    // Holds details for incremental marking scopes.
    IncrementalMarkingInfos
        incremental_marking_scopes[Scope::NUMBER_OF_INCREMENTAL_SCOPES];
  };

  static const int kThroughputTimeFrameMs = 5000;

  explicit GCTracer(Heap* heap);

  // Start collecting data.
  void Start(GarbageCollector collector, GarbageCollectionReason gc_reason,
             const char* collector_reason);

  // Stop collecting data and print results.
  void Stop(GarbageCollector collector);

  // Sample and accumulate bytes allocated since the last GC.
  void SampleAllocation(double current_ms, size_t new_space_counter_bytes,
                        size_t old_generation_counter_bytes);

  // Log the accumulated new space allocation bytes.
  void AddAllocation(double current_ms);

  void AddContextDisposalTime(double time);

  void AddCompactionEvent(double duration, size_t live_bytes_compacted);

  void AddSurvivalRatio(double survival_ratio);

  // Log an incremental marking step.
  void AddIncrementalMarkingStep(double duration, size_t bytes);

  // Compute the average incremental marking speed in bytes/millisecond.
  // Returns 0 if no events have been recorded.
  double IncrementalMarkingSpeedInBytesPerMillisecond() const;

  // Compute the average scavenge speed in bytes/millisecond.
  // Returns 0 if no events have been recorded.
  double ScavengeSpeedInBytesPerMillisecond(
      ScavengeSpeedMode mode = kForAllObjects) const;

  // Compute the average compaction speed in bytes/millisecond.
  // Returns 0 if not enough events have been recorded.
  double CompactionSpeedInBytesPerMillisecond() const;

  // Compute the average mark-sweep speed in bytes/millisecond.
  // Returns 0 if no events have been recorded.
  double MarkCompactSpeedInBytesPerMillisecond() const;

  // Compute the average incremental mark-sweep finalize speed in
  // bytes/millisecond.
  // Returns 0 if no events have been recorded.
  double FinalIncrementalMarkCompactSpeedInBytesPerMillisecond() const;

  // Compute the overall mark compact speed including incremental steps
  // and the final mark-compact step.
  double CombinedMarkCompactSpeedInBytesPerMillisecond();

  // Allocation throughput in the new space in bytes/millisecond.
  // Returns 0 if no allocation events have been recorded.
  double NewSpaceAllocationThroughputInBytesPerMillisecond(
      double time_ms = 0) const;

  // Allocation throughput in the old generation in bytes/millisecond in the
  // last time_ms milliseconds.
  // Returns 0 if no allocation events have been recorded.
  double OldGenerationAllocationThroughputInBytesPerMillisecond(
      double time_ms = 0) const;

  // Allocation throughput in heap in bytes/millisecond in the last time_ms
  // milliseconds.
  // Returns 0 if no allocation events have been recorded.
  double AllocationThroughputInBytesPerMillisecond(double time_ms) const;

  // Allocation throughput in heap in bytes/milliseconds in the last
  // kThroughputTimeFrameMs seconds.
  // Returns 0 if no allocation events have been recorded.
  double CurrentAllocationThroughputInBytesPerMillisecond() const;

  // Allocation throughput in old generation in bytes/milliseconds in the last
  // kThroughputTimeFrameMs seconds.
  // Returns 0 if no allocation events have been recorded.
  double CurrentOldGenerationAllocationThroughputInBytesPerMillisecond() const;

  // Computes the context disposal rate in milliseconds. It takes the time
  // frame of the first recorded context disposal to the current time and
  // divides it by the number of recorded events.
  // Returns 0 if no events have been recorded.
  double ContextDisposalRateInMilliseconds() const;

  // Computes the average survival ratio based on the last recorded survival
  // events.
  // Returns 0 if no events have been recorded.
  double AverageSurvivalRatio() const;

  // Returns true if at least one survival event was recorded.
  bool SurvivalEventsRecorded() const;

  // Discard all recorded survival events.
  void ResetSurvivalEvents();

  void NotifyIncrementalMarkingStart();

  V8_INLINE void AddScopeSample(Scope::ScopeId scope, double duration) {
    DCHECK(scope < Scope::NUMBER_OF_SCOPES);
    if (scope >= Scope::FIRST_INCREMENTAL_SCOPE &&
        scope <= Scope::LAST_INCREMENTAL_SCOPE) {
      incremental_marking_scopes_[scope - Scope::FIRST_INCREMENTAL_SCOPE]
          .Update(duration);
    } else {
      current_.scopes[scope] += duration;
    }
  }

 private:
  FRIEND_TEST(GCTracer, AverageSpeed);
  FRIEND_TEST(GCTracerTest, AllocationThroughput);
  FRIEND_TEST(GCTracerTest, NewSpaceAllocationThroughput);
  FRIEND_TEST(GCTracerTest, NewSpaceAllocationThroughputWithProvidedTime);
  FRIEND_TEST(GCTracerTest, OldGenerationAllocationThroughputWithProvidedTime);
  FRIEND_TEST(GCTracerTest, RegularScope);
  FRIEND_TEST(GCTracerTest, IncrementalMarkingDetails);
  FRIEND_TEST(GCTracerTest, IncrementalScope);
  FRIEND_TEST(GCTracerTest, IncrementalMarkingSpeed);

  // Returns the average speed of the events in the buffer.
  // If the buffer is empty, the result is 0.
  // Otherwise, the result is between 1 byte/ms and 1 GB/ms.
  static double AverageSpeed(const base::RingBuffer<BytesAndDuration>& buffer);
  static double AverageSpeed(const base::RingBuffer<BytesAndDuration>& buffer,
                             const BytesAndDuration& initial, double time_ms);

  void ResetForTesting();
  void ResetIncrementalMarkingCounters();
  void RecordIncrementalMarkingSpeed(size_t bytes, double duration);

  // Print one detailed trace line in name=value format.
  // TODO(ernstm): Move to Heap.
  void PrintNVP() const;

  // Print one trace line.
  // TODO(ernstm): Move to Heap.
  void Print() const;

  // Prints a line and also adds it to the heap's ring buffer so that
  // it can be included in later crash dumps.
  void PRINTF_FORMAT(2, 3) Output(const char* format, ...) const;

  double TotalExternalTime() const {
    return current_.scopes[Scope::EXTERNAL_WEAK_GLOBAL_HANDLES] +
           current_.scopes[Scope::EXTERNAL_EPILOGUE] +
           current_.scopes[Scope::EXTERNAL_PROLOGUE] +
           current_.scopes[Scope::MC_INCREMENTAL_EXTERNAL_EPILOGUE] +
           current_.scopes[Scope::MC_INCREMENTAL_EXTERNAL_PROLOGUE];
  }

  // Pointer to the heap that owns this tracer.
  Heap* heap_;

  // Current tracer event. Populated during Start/Stop cycle. Valid after Stop()
  // has returned.
  Event current_;

  // Previous tracer event.
  Event previous_;

  // Size of incremental marking steps (in bytes) accumulated since the end of
  // the last mark compact GC.
  size_t incremental_marking_bytes_;

  // Duration of incremental marking steps since the end of the last mark-
  // compact event.
  double incremental_marking_duration_;

  double incremental_marking_start_time_;

  double recorded_incremental_marking_speed_;

  // Incremental scopes carry more information than just the duration. The infos
  // here are merged back upon starting/stopping the GC tracer.
  IncrementalMarkingInfos
      incremental_marking_scopes_[Scope::NUMBER_OF_INCREMENTAL_SCOPES];

  // Timestamp and allocation counter at the last sampled allocation event.
  double allocation_time_ms_;
  size_t new_space_allocation_counter_bytes_;
  size_t old_generation_allocation_counter_bytes_;

  // Accumulated duration and allocated bytes since the last GC.
  double allocation_duration_since_gc_;
  size_t new_space_allocation_in_bytes_since_gc_;
  size_t old_generation_allocation_in_bytes_since_gc_;

  double combined_mark_compact_speed_cache_;

  // Counts how many tracers were started without stopping.
  int start_counter_;

  // Separate timer used for --runtime_call_stats
  RuntimeCallTimer timer_;

  base::RingBuffer<BytesAndDuration> recorded_minor_gcs_total_;
  base::RingBuffer<BytesAndDuration> recorded_minor_gcs_survived_;
  base::RingBuffer<BytesAndDuration> recorded_compactions_;
  base::RingBuffer<BytesAndDuration> recorded_incremental_mark_compacts_;
  base::RingBuffer<BytesAndDuration> recorded_mark_compacts_;
  base::RingBuffer<BytesAndDuration> recorded_new_generation_allocations_;
  base::RingBuffer<BytesAndDuration> recorded_old_generation_allocations_;
  base::RingBuffer<double> recorded_context_disposal_times_;
  base::RingBuffer<double> recorded_survival_ratios_;

  DISALLOW_COPY_AND_ASSIGN(GCTracer);
};
}  // namespace internal
}  // namespace v8

#endif  // V8_HEAP_GC_TRACER_H_


text:
""" Utilities for transforming the syntax/style/grammar of a document, usually asciidoc or markdown

Instantiates Objects derived from the `_sre.SRE_Pattern` class (compiled regular expressions) so they work with regex.sub()
"""
import logging
# Simport regex
from copy import copy

from nlpia.regexes import Pattern, RE_HYPERLINK

# from nlpia.constants import DATA_PATH
log = logging.getLogger(__name__)

def looks_like_name(s):
    if len(s) < 3:
        return None
    if ' ' in s or '.' not in s or '/' not in s:
        return s

class Matcher(Pattern):
    """ Pattern with additional .ismatch() that returns bool(re.match())

    ismatch is desicned to be overriden by a custom function that returns a bool

    >>> chars = list('Hello World!')
    >>> m = Matcher('[a-z]')
    >>> [m.ismatch(s) for s in chars]
    [False, True, True, True, True, False, False, True, True, True, True, False]
    >>> m = Matcher('^[A-Z][a-z]+$')

    >>> tokens = 'A BIG Hello World to You!'.split()
    >>> m = Matcher(lambda s: len(s) <= 3)
    >>> [m.ismatch(s) for s in tokens]
    [True, True, False, False, True, False]
    >>> m = Matcher(None)
    >>> [m.ismatch(s) for s in tokens]
    [True, True, True, True, True, True]
    """

    def __init__(self, pattern='', ismatchfun=None):
        if callable(pattern):
            ismatchfun = pattern
            pattern = ''
        self._ismatchfun = ismatchfun or self._return_true
        super().__init__(pattern or '')

    def _return_true(self, *args, **kwargs):
        return True

    def _return_false(self, *args, **kwargs):
        return False

    def _ismatchfun(self, s):
        return self._return_true()

    def ismatch(self, s):
        """ like compiled_re.match() but returns True or False """
        if self._ismatchfun(s) and self._compiled_pattern.match(s):
            return True
        return False

    def match(self, s, *args, **kwargs):
        if self.ismatchfun(s):
            return super().match(s, *args, **kwargs)

class Filter(Matcher):
    """ Pattern with additional .ismatch() and .filter() methods

    >>> chars = list('Hello World!')
    >>> m = Filter('[a-z]')
    >>> [m.filter(c) for c in chars]
    ['', 'e', 'l', 'l', 'o', '', '', 'o', 'r', 'l', 'd', '']
    >>> m = Filter('^[A-Z][a-z]+$')
    >>> tokens = 'A BIG Hello World to You!'.split()
    >>> [m.filter(s) for s in tokens]
    ['', '', 'Hello', 'World', '', '']
    >>> m = Filter(None)
    >>> [m.filter(s) for s in tokens]
    ['A', 'BIG', 'Hello', 'World', 'to', 'You!']
    """

    def filter(self, s):
        """ like compiled_re.match() but returns the entire string if it matches or empty string otherwise """
        if self.ismatch(s):
            return s
        return ''

class Translator(Pattern):
    r""" A pattern for translating a diff file into a more human (non-programmer) readable form

    This is the start of a translator demo that turns diff patch files into human-readable email.
    >> from nlpia.loaders import get_data
    >> difftxt = get_data('forum_user_557658.patch')

    >>> tran = Translator()
    """

    def __init__(self, pattern=r'^\-(?P<text>.*)', template='      was: {text}'):
        super().__init__(pattern=pattern)

    def replace(self, text, to_template='{name} ({url})', from_template=None,
                name_matcher=Matcher(looks_like_name), url_matcher=Matcher(r'.*[^:]+$')):
        """ Replace all occurrences of rendered from_template in text with `template` rendered from each match.groupdict()

        TODO: from_template

        >>> translator = HyperlinkStyleCorrector()
        >>> adoc = 'See http://totalgood.com[Total Good] about that.'
        >>> translator.replace(adoc, '{scheme_type}s://', '{scheme}://')
        'See http://totalgood.com[Total Good] about that.'
        >>> adoc = "Nada here:// Only a .com & no (parens.symbol) or http/[hyperlinks] or anything!"
        >>> translator.translate(adoc)
        'Nada here:// Only a .com & no (parens.symbol) or http/[hyperlinks] or anything!'
        >>> adoc = "Two http://what.com[WAT] with https://another.com/api?q=1&a=2[longer url]."
        >>> translator.translate(adoc)
        'Two WAT (http://what.com) with longer url (https://another.com/api?q=1&a=2).'
        """
        self.name_matcher = name_matcher or Matcher()
        self.url_matcher = url_matcher or Matcher()
        matches = self.finditer(text)
        newdoc = copy(text)
        log.debug('before translate: {}'.format(newdoc))
        for m in matches:
            # this outer m.captures() loop is overkill:
            #   overlapping pattern matches probably won't match after the first replace
            log.debug('match: {}'.format(m))
            log.debug('match.captures(): {}'.format(m.captures()))
            for i, captured_str in enumerate(m.captures()):
                captureddict = {'name': None, 'scheme': None, 'url': None}
                for k, v in m.capturesdict().items():
                    if len(v) > i:
                        captureddict[k] = v[i]
                    else:
                        captureddict[k] = None
                        log.warning('Overlapping captured matches were mishandled: {}'.format(m.capturesdict()))
                # need to check for optional args:
                name = captureddict.get('name', None)
                url = captureddict.get('url', None)
                scheme = captureddict.get('scheme', None)
                if (not scheme or not name or not self.name_matcher.ismatch(name) or
                        not url or not self.url_matcher.ismatch(url)):
                    continue
                if from_template:
                    rendered_from_template = from_template.format(**captureddict)
                else:
                    rendered_from_template = captured_str
                # TODO: render numbered references like r'\1' before rendering named references
                #    or do them together in one `.format(**kwargs)` after translating \1 to {1} and groupsdict().update({1: ...})
                rendered_to_template = to_template.format(**m.groupdict())
                newdoc = newdoc.replace(rendered_from_template, rendered_to_template)
        return newdoc

class HyperlinkStyleCorrector(Pattern):
    """ A pattern for matching asciidoc hyperlinks for transforming them to print-book version (Manning Style)

    >>> adoc = 'See http://totalgood.com[Total Good] about that.'
    >>> translator = HyperlinkStyleCorrector()
    >>> matches = list(translator.finditer(adoc))
    >>> m = matches[0]
    >>> m
    <regex.Match object; span=(4, 36), match='http://totalgood.com[Total Good]'>
    >>> for m in matches:
    ...     newdoc = adoc.replace(
    ...         '{scheme}'.format(**m.groupdict()),
    ...         ''.format(**m.groupdict()))
    >>> newdoc
    'See totalgood.com[Total Good] about that.'
    >>> translator.replace(adoc, '{scheme}', '{scheme_type}s://')
    'See http://totalgood.com[Total Good] about that.'
    """

    def __init__(self, pattern=RE_HYPERLINK):
        super().__init__(pattern=pattern)

    def name_matcher(s):
        return s

    def replace(self, text, to_template='{name} ({url})', from_template=None,
                name_matcher=Matcher(looks_like_name), url_matcher=Matcher(r'.*[^:]+$')):
        """ Replace all occurrences of rendered from_template in text with `template` rendered from each match.groupdict()

        TODO: from_template

        >>> translator = HyperlinkStyleCorrector()
        >>> adoc = 'See http://totalgood.com[Total Good] about that.'
        >>> translator.replace(adoc, '{scheme_type}s://', '{scheme}')
        'See https://totalgood.com[Total Good] about that.'
        >>> adoc = "Nada here:// Only a .com & no (parens.symbol) or http/[hyperlinks] or anything!"
        >>> translator.translate(adoc)
        'Nada here:// Only a .com & no (parens.symbol) or http/[hyperlinks] or anything!'
        >>> adoc = "Two http://what.com[WAT] with https://another.com/api?q=1&a=2[longer url]."
        >>> translator.translate(adoc)
        'Two WAT (http://what.com) with longer url (https://another.com/api?q=1&a=2).'
        """
        self.name_matcher = name_matcher or Matcher()
        self.url_matcher = url_matcher or Matcher()
        matches = self.finditer(text)
        newdoc = copy(text)
        log.debug('before translate: {}'.format(newdoc))
        for m in matches:
            # this outer m.captures() loop is overkill:
            #   overlapping pattern matches probably won't match after the first replace
            log.debug('match: {}'.format(m))
            log.debug('match.captures(): {}'.format(m.captures()))
            for i, captured_str in enumerate(m.captures()):
                captureddict = {'name': None, 'scheme': None, 'url': None}
                for k, v in m.capturesdict().items():
                    if len(v) > i:
                        captureddict[k] = v[i]
                    else:
                        captureddict[k] = None
                        log.warning('Overlapping captured matches were mishandled: {}'.format(m.capturesdict()))
                # need to check for optional args:
                name = captureddict.get('name', None)
                url = captureddict.get('url', None)
                scheme = captureddict.get('scheme', None)
                if (not scheme or not name or not self.name_matcher.ismatch(name) or
                        not url or not self.url_matcher.ismatch(url)):
                    continue
                if from_template:
                    rendered_from_template = from_template.format(**captureddict)
                else:
                    rendered_from_template = captured_str
                # TODO: render numbered references like r'\1' before rendering named references
                #    or do them together in one `.format(**kwargs)` after translating \1 to {1} and groupsdict().update({1: ...})
                rendered_to_template = to_template.format(**m.groupdict())
                newdoc = newdoc.replace(rendered_from_template, rendered_to_template)
        return newdoc

    def translate(self, text, to_template='{name} ({url})', from_template=None, name_matcher=None, url_matcher=None):
        """ Translate hyperinks into printable book style for Manning Publishing

        >>> translator = HyperlinkStyleCorrector()
        >>> adoc = 'See http://totalgood.com[Total Good] about that.'
        >>> translator.translate(adoc)
        'See Total Good (http://totalgood.com) about that.'
        """
        return self.replace(text, to_template=to_template, from_template=from_template,
                            name_matcher=name_matcher, url_matcher=url_matcher)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:ns1="urn:oasis:names:tc:xliff:document:1.2">
    <string msgid="4600421777120114993" name="abc_action_bar_home_description">"پیمایش به صفحه اصلی"</string>
    <string msgid="1594238315039666878" name="abc_action_bar_up_description">"پیمایش به بالا"</string>
    <string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"گزینه‌های بیشتر"</string>
    <string msgid="4076576682505996667" name="abc_action_mode_done">"تمام"</string>
    <string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"مشاهده همه"</string>
    <string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"انتخاب برنامه"</string>
    <string msgid="121134116657445385" name="abc_capital_off">"خاموش"</string>
    <string msgid="3405795526292276155" name="abc_capital_on">"روشن"</string>
    <string msgid="7723749260725869598" name="abc_search_hint">"جستجو…"</string>
    <string msgid="3691816814315814921" name="abc_searchview_description_clear">"پاک کردن عبارت جستجو"</string>
    <string msgid="2550479030709304392" name="abc_searchview_description_query">"عبارت جستجو"</string>
    <string msgid="8264924765203268293" name="abc_searchview_description_search">"جستجو"</string>
    <string msgid="8928215447528550784" name="abc_searchview_description_submit">"ارسال عبارت جستجو"</string>
    <string msgid="893419373245838918" name="abc_searchview_description_voice">"جستجوی گفتاری"</string>
    <string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"اشتراک‌گذاری با"</string>
    <string msgid="3300176832234831527" name="abc_shareactionprovider_share_with_application">"اشتراک‌گذاری با <ns1:g id="APPLICATION_NAME">%s</ns1:g>"</string>
    <string msgid="1603543279005712093" name="abc_toolbar_collapse_description">"کوچک کردن"</string>
    <string msgid="146198913615257606" name="search_menu_title">"جستجو"</string>
    <string msgid="2869576371154716097" name="status_bar_notification_info_overflow">"۹۹۹+"</string>
</resources>


text:
GLuint BuildSahder(demoSource* vertexSource, demoSource* fragmentSource);
void EndOfSahders(GLuint prgName);

#endif


text:
import cookielib
import copy
import httplib
import os
import json
import pickle
import Queue
import random
import re
import socket
import sys
import time
import urllib2
import urlparse
from threading import Thread
from task import *
import config

GENERATE_RESULTS = config.GENERATE_RESULTS
COOKIES_ENABLED = config.COOKIES_ENABLED
HTTP_DEBUG = config.HTTP_DEBUG
SHUFFLE_TESTCASES = config.SHUFFLE_TESTCASES
WAITFOR_AGENT_FINISH = config.WAITFOR_AGENT_FINISH
SOCKET_TIMEOUT = config.SOCKET_TIMEOUT

class TaskAgent(Thread):
    def __init__(self, id, runtime_stats, task, signal):
        Thread.__init__(self)
        socket.setdefaulttimeout(SOCKET_TIMEOUT)
        self.id = id
        self.runtime_stats = runtime_stats
        self.running = True
        self.count = 0
        self.error_count = 0
        self.default_timer = time.time
        self.trace_logging = False
        self.task = task
        self.signal = signal

    def run(self):
        agent_start_time = time.strftime('%H:%M:%S', time.localtime())

        total_latency = 0
        total_connect_latency = 0
        total_bytes = 0

        while self.running:
            if self.signal['setted']:
                self.cookie_jar = cookielib.CookieJar()
                resp, content, req_start_time, req_end_time, connect_end_time = self.send(self.task)
                self.count += 1

                if resp.code != 200:
                    self.error_count += 1
                    self.task.error = resp.code
                    self.task.result = content

                else:
                    (r, emsg) = self.task.verify(content)
                    if not r:
                        self.error_count += 1
                        self.task.error = -1000
                        self.task.result = '发生错误:\n【%s】\n实际返回:\n%s' % (emsg, content)

                    else:
                        self.task.result = content

                latency = (req_end_time - req_start_time)
                connect_latency = (connect_end_time - req_start_time)
                resp_bytes = len(content)

                total_bytes += resp_bytes
                total_latency += latency
                total_connect_latency += connect_latency

                self.runtime_stats[self.id] = StatCollection(
                    resp.code, resp.msg, latency, self.count, self.error_count,
                    total_latency, total_connect_latency, total_bytes
                )
                self.runtime_stats[self.id].agent_start_time = agent_start_time

                if self.error_count > 0:
                    break

                if not self.task.loop:
                    break
            else:
                time.sleep(0.01)

    def stop(self):
        self.running = False

    def send(self, req):
        if HTTP_DEBUG:
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar), urllib2.HTTPHandler(debuglevel=1))
        elif COOKIES_ENABLED:
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar))
        else:
            opener = urllib2.build_opener()
        if req.method.upper() == 'POST':
            request = urllib2.Request(req.url, req.body, req.headers)
        else:
            request = urllib2.Request(req.url, None, req.headers)

        req_start_time = self.default_timer()
        try:
            resp = opener.open(request)
            connect_end_time = self.default_timer()
            content = resp.read()
            req_end_time = self.default_timer()
        except httplib.HTTPException, e:
            connect_end_time = self.default_timer()
            resp = ErrorResponse()
            resp.code = 0
            resp.msg = str(e)
            resp.headers = {}
            content = ''
        except urllib2.HTTPError, e:
            connect_end_time = self.default_timer()
            resp = ErrorResponse()
            resp.code = e.code
            resp.msg = httplib.responses[e.code]
            resp.headers = dict(e.info())
            content = e.read()
        except urllib2.URLError, e:
            connect_end_time = self.default_timer()
            resp = ErrorResponse()
            resp.code = 0
            resp.msg = str(e.reason)
            resp.headers = {}
            content = ''
        except IOError, e:
            connect_end_time = self.default_timer()
            resp = ErrorResponse()
            resp.code = 0
            resp.msg = str(e)
            resp.headers = {}
            resp.content = 'IOError'
            content = ''
        except Exception, e:
            connect_end_time = self.default_timer()
            resp = ErrorResponse()
            resp.code = 0
            resp.msg = str(e)
            resp.headers = {}
            resp.content = 'Exception'
            content = ''

        req_end_time = self.default_timer()

        if self.trace_logging:
            self.log_http_msgs(req, request, resp, content)

        return (resp, content, req_start_time, req_end_time, connect_end_time)

class LoadManager(Thread):
    def __init__(self, tasks, runtime_stats, error_queue, output_dir = None, test_name = None):
        Thread.__init__(self)
        socket.setdefaulttimeout(SOCKET_TIMEOUT)
        self.running = True
        self.tasks = tasks
        self.num_agents = len(tasks)
        self.runtime_stats = runtime_stats
        self.error_queue = error_queue
        self.test_name = test_name

        if output_dir and test_name:
            self.output_dir = time.strftime(output_dir + '/' + test_name + '_' + 'results_%Y.%m.%d_%H.%M.%S', time.localtime())
        elif output_dir:
            self.output_dir = time.strftime(output_dir + '/' + 'results_%Y.%m.%d_%H.%M.%S', time.localtime())
        elif test_name:
            self.output_dir = time.strftime('results/' + test_name + '_' + 'results_%Y.%m.%d_%H.%M.%S', time.localtime())
        else:
            self.output_dir = time.strftime('results/results_%Y.%m.%d_%H.%M.%S', time.localtime())

        for i in range(self.num_agents):
            self.runtime_stats[i] = StatCollection(0, '', 0, 0, 0, 0, 0, 0)

        self.results_queue = Queue.Queue()
        self.agent_refs = []
        self.msg_queue = []

    def run(self):
        self.running = True
        self.agents_started = False
        try:
            os.makedirs(self.output_dir, 0755)
        except OSError:
            self.output_dir = self.output_dir + time.strftime('/results_%Y.%m.%d_%H.%M.%S', time.localtime())
            try:
               os.makedirs(self.output_dir, 0755)
            except OSError:
                sys.stderr.write('ERROR: Can not create output directory\n')
                sys.exit(1)

        self.results_writer = ResultWriter(self.results_queue, self.output_dir)
        self.results_writer.setDaemon(True)
        self.results_writer.start()

        signal = {
            'setted': False
        }

        print('-------------------------------------------------')
        print('开始启动并发测试')
        for i in range(self.num_agents):
            if self.running:
                agent = TaskAgent(i, self.runtime_stats, self.tasks[i], signal)
                agent.start()
                self.agent_refs.append(agent)
                agent_started_line = u'激活虚拟用户 %d 个' % (i + 1)
                if sys.platform.startswith('win'):
                    sys.stdout.write(chr(0x08) * len(agent_started_line))
                    sys.stdout.write(agent_started_line)
                else:
                    esc = chr(27) # escape key
                    sys.stdout.write(esc + '[G' )
                    sys.stdout.write(esc + '[A' )
                    sys.stdout.write(agent_started_line + '\n')

        signal['setted'] = True

        if sys.platform.startswith('win'):
            sys.stdout.write('\n')

        print '开始测试 ...\n'
        self.agents_started = True

    def stop(self, wait = True):
        self.running = False
        for agent in self.agent_refs:
            agent.stop()

        if wait:
            keep_running = True
            while keep_running:
                keep_running = False
                for agent in self.agent_refs:
                    if agent.isAlive():
                        keep_running = True
                        time.sleep(0.1)

        self.results_writer.stop()

class ErrorResponse():
    def __init__(self):
        self.code = 0
        self.msg = 'Connection error'
        self.headers = {}

class StatCollection():
    def __init__(self, status, reason, latency, count, error_count, total_latency, total_connect_latency, total_bytes):
        self.status = status
        self.reason = reason
        self.latency = latency
        self.count = count
        self.error_count = error_count
        self.total_latency = total_latency
        self.total_connect_latency = total_connect_latency
        self.total_bytes = total_bytes

        self.agent_start_time = None

        if count > 0:
            self.avg_latency = (total_latency / count)
            self.avg_connect_latency = (total_connect_latency / count)
        else:
            self.avg_latency = 0
            self.avg_connect_latency = 0

class ResultWriter(Thread):
    def __init__(self, results_queue, output_dir):
        Thread.__init__(self)
        self.running = True
        self.results_queue = results_queue
        self.output_dir = output_dir

    def run(self):
        fh = open('%s/agent_stats.csv' % self.output_dir, 'w')
        fh.close()

        while self.running:
            try:
                q_tuple = self.results_queue.get(False)
                f = open('%s/agent_stats.csv' % self.output_dir, 'a')
                f.write('%s,%s,%s,%s,%s,%d,%s,%d,%f,%f,%s\n' % q_tuple)  # log as csv
                f.flush()
                f.close()
            except Queue.Empty:
                time.sleep(.10)

    def stop(self):
        self.running = False


text:
layout: post
date: 2015-10-12 22:04:00
title:  "Android学习手记(06) TabActivity和TabHost"
category: Android-Study
tags:   [Android, TabActivity, TabHost]
---

* content
{:toc}

使用TabHost可以实现标签式效果,将两个Activity放在两个Tab内。

首先,需要基于MainActivity创建一个TabHost对象。

>TabHost tabHost = this.getTabHost();

通过 TabHost.addTab() 可以创建一个新Tab。

>TabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Sign In").setContent(new Intent(this, SignIn.class)));

其中,newTabSpec() 设置新建Tab名称。setIndicator("") 设置新建标签的内容。setContent()设置Tab的内容。

---

首先,新建两个Activity,分别命名为"SignIn"和"SignUp"。

然后在MainActivity中加入如下代码,即可实现下图所示功能。

MainActivity.java

{% highlight java linenos %}
public class MainActivity extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("TabActivity");

        TabHost tabHost = this.getTabHost();
        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Sign In").setContent(new Intent(this, SignIn.class)));
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Sign Up").setContent(new Intent(this, SignUp.class)));
    }
}
{% endhighlight %}


text:
// Variables
$darkBlue: #243139;
$fbBlue: #3563e7;
$lightBlue: #2ebcea;
$snow: #f6f9fa;
$radius: 4px;

/*==Typography=*/
body {font: 16px /*'Montserrat',*/'Source sans pro', sans-serif;}
.sec-main h1,
.sec-main p,
.sec-everywhere h1,
.sec-everywhere p,
.sec-features h1,
.sec-features p,
footer h1,
footer p {
  text-align: center;
  @media screen and (max-width: 768px) {text-align: left;}
}
h1,
h2 {margin: 0;}
h1 {font-size: 2em;}
p {
  font-size: 1.125em;
  font-weight: 300;
  line-height: 1.625em;
}
.sec-main h2 {
  margin: .9em 0;
  font-size: 1.75em;
  font-weight: 200;
  line-height: 1.5em;
  text-align: center;
}
.features-post h1 {font-size: 1.5em;}
.features-post p {font-size: 1em;}
footer h1 {font-size: 2.125em;}
/*==Layout==*/
html,
body,
.wrapper {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
*,
*:before,
*:after {box-sizing: border-box;}
section {
  width: 100%;
  min-height: 480px;
}
.container {
  margin: 0 auto;
  padding: 6.625em 0;
  max-width: 60em;/*960px*/
  height: 100%;
  @media screen and (max-width: 768px) {padding: 3em 0;}
}
.row {width: 100%;}
.col-3,
.col-2 {
  float: left;
  padding: 0 1em;
}
.col-3 {width: 33.3333333%}
.col-2 {width: 50%;}
@media screen and (max-width: 768px) {
  .col-3,
  .col-2{
    float: none;
    margin: auto;
    padding: 0 1.75em;
    width: 90%;
  }
}
ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
.button {
  //padding: 1.0625em;
  width: 148px;
  height: 46px;
  font: 700 1em 'Source sans pro', sans-serif;
  text-align: center;
  background: $lightBlue;
  color: #fff;
  border: 0;
  cursor: pointer;
  outline: 0;
  transition: background .25s;
  &:focus,
  &:hover {background: lighten($lightBlue, 10%);}
  &:active {background: darken($lightBlue, 7%);}
}
/*==Main==*/
.sec-main {
  position: relative;
  height: 100%;
  background: url("../images/travel-map-sailing-ship.jpg") no-repeat;
  background-size: cover;
  color: #fff;
}
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,.5);
}
.center {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  max-width: 465px;
  height: 282px;
}
.logo {
  margin: auto;
  width: 110px;
  height: 121px;
  text-indent: 100%;
  background: url(http://i.imgur.com/f7ZqbJT.png) no-repeat;
  background-size: 100%;
  overflow: hidden;
}
@media screen and (max-width: 768px) {
  .sec-main br {display: none;}
}
form {
  margin: auto;
  max-width: 434px;
  @media screen and (max-width: 560px) {max-width: 90%;}
}
form input[type="email"],
form .button {
  height: 48px;
  font-size: 1em;
  border: 0;
}
form input[type="email"] {
  padding: 1.0625em;
  width: 314px;
  border-top-left-radius: $radius;
  border-bottom-left-radius: $radius;
  @media screen and (max-width: 30em) {width: 251px;}
  @media screen and (max-width: 410px) {width: 70%;}
}
form .button {
  position: relative;
  top: 1px;
  left: -4px;
  width: 116px;
  border-top-right-radius: $radius;
  border-bottom-right-radius: $radius;
  @media screen and (max-width: 410px) {width: 29%;}
}
form .button-full {
  width: 100%;
  background: #1fd589;
  border-top-left-radius: $radius;
  border-bottom-left-radius: $radius;
  cursor: default;
  transition: all .25s;
  &:focus,
  &:hover,
  &:active {background: #1fd589;}
}
header {
  position: absolute;
  bottom: 0;
  width: 100%;
  max-height: 87px;
  background: rgba(0,0,0,.75);
}
.fixed {
  position: fixed;
  top: 0;
}
.nav {
  display: flex;
  justify-content: center;
}
.nav a {
  display: block;
  padding: 1.975em;
  text-decoration: none;
  color: #fff;
  border-bottom: .35em solid transparent;
  transition: border-bottom .25s;
  &:focus,
  &:hover {border-bottom: .35em solid $lightBlue;}
}
/*==About==*/
.sec-about {
  height: 736px;
  background: url(http://i.imgur.com/tkZcvec.png) no-repeat center right;
  background-size: 649px 439px;
  background-position: 111% 52%;
}
@media screen and (max-width:1056px) {
  .sec-about {background-position: 155% 52%;}
}
@media screen and (max-width: 60em) {
  .sec-about {
    margin-bottom: 4em;
    height: 570px;
    text-align: left;
    background-position: bottom center;
    background-size: 55%;
  }
  .sec-about button {display: none;}
}
@media screen and (max-width: 885px) {
  .sec-about {background-size: 65%;}
}
@media screen and (max-width: 700px) {
  .sec-about {background-size: 75%;}
}
@media screen and (max-width: 500px) {
  .sec-about {background-size: 85%;}
}
.sec-about .container {
  padding-top: 185px;
  @media screen and (max-width: 60em) {padding-top: 2em;}
}
.sec-about .col-2:first-child {
  margin: 5% auto;
  padding-right: 1em;
  font-size: 1.125em;/*18px*/
  @media screen and (max-width: 60em) {
    float: none;
    width: 80%;
    text-align: center;
  }
}
.sec-about .col-2:last-child {
  height: 300px;
  //background: url(http://i.imgur.com/tkZcvec.png) no-repeat;
  //background-size: 100%;
}
.sec-about .button {border-radius: $radius;}

/*==Everywhere==*/
.sec-everywhere {
  min-height: 704px;
  background: $lightBlue;
  color: #fff;
  //overflow: hidden;
}
@media screen and (max-width: 768px) {
  .sec-everywhere .container {
    margin: auto;
    width: 90%;
  }
}
.row-list {
  text-align: center;
  @media screen and (max-width: 979px) {overflow-x: auto;}
}
.row-list h2 {
  font-size: 1.25em;
  font-weight: 700;
}
.row-list p {text-align: center;}
.everywhere-list {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  min-width: 960px;
  cursor: default;
}
.everywhere-list li {width: 33.3333333%;}
.everywhere-list li .col-3 {width: 100%;}
.sec-everywhere h2 {margin-top: 3em;}
.sec-everywhere .row:nth-child(2) p {
  padding: 0 10.5em 3em 10.5em;
  @media screen and (max-width: 768px) {padding: 0;}
}
.sec-everywhere .row:nth-child(3) p {line-height: 0;}
.sec-everywhere .img-container {
  position: relative;
  height: 206px;
}
.sec-everywhere img {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
/*==Task Management==*/
.sec-task-mngmt {
  min-height: 581px;
  background: $snow;
}
@media screen and (max-width: 768px) {
  .sec-task-mngmt {text-align: left;}
  .sec-task-mngmt br {display: none;}
}
@media screen and (max-width: 768px) {
  .sec-task-mngmt .row {
    background: #f6f9fa;
    float: left;
  }
}
.sec-task-mngmt .container {padding: 0;}
.sec-task-mngmt .col-2:last-child {
  float: left;
  height: 600px;
  background: url(http://i.imgur.com/w7fqAU2.png) no-repeat top left;/*iPhone*/
  @media screen and (max-width: 30em) {
    float: left;
    width: 100%;
    height: 365px;
    background: url(http://i.imgur.com/YqipjX0.png) no-repeat top center;
    background-size: 70%;
  }
}
.sec-task-mngmt .col-2:first-child {
  float: right;
  margin: 25% 0;
  @media screen and (max-width: 30em) {
    margin: 2em auto;
    padding: 0 3em;
  }
}

/*==Task Management2==*/
.sec-task-mngmt2 {
  min-height: 581px;
  background: $snow;
  //background-size: 50%;
}
@media screen and (max-width: 768px) {
  .sec-task-mngmt {text-align: left;}
  .sec-task-mngmt br {display: none;}
}
@media screen and (max-width: 768px) {
  .sec-task-mngmt .row {
    background: #f6f9fa;
    float: left;
  }
}
.sec-task-mngmt2 .container {padding: 0;}
.sec-task-mngmt2 .col-2:last-child {
  float: left;
  height: 600px;
  background: url(http://i.imgur.com/w7fqAU2.png) no-repeat top left;/*iPhone*/
  @media screen and (max-width: 30em) {
    float: left;
    width: 100%;
    height: 365px;
    background: url(http://i.imgur.com/YqipjX0.png) no-repeat top center;
    background-size: 70%;
  }
}
.sec-task-mngmt2 .col-2:first-child {
  float: left;
  margin: 25% 0;
  @media screen and (max-width: 30em) {
    margin: 2em auto;
    padding: 0 3em;
  }
}

/*==Features==*/
.sec-features {
min-height: 0px;
margin-left: auto;
margin-right: auto;

}
@media screen and (max-width: 30em) {
  .col-3:first-child .features-post {margin-top: 5em;}
}
@media screen and (max-width: 900px) {
  .features-post br {display: none;}
}
.features-post img {

  display: block;
  //margin: 3em auto;
  margin-left: auto;
  margin-right: auto;

  height: 50%;
  width: 50%;
  //@media screen and (max-width: 768px) {margin: 1.5em 0;}
  //@media screen and (max-width: 30em) {width: 70px;}
}
.features-post p {
  padding: 0 2em;
  @media screen and (max-width: 768px) {padding: 0;}
}
.features-post br {@media screen and (max-width: 30em) {display: none;}}
/*==Footer==*/
footer {
  min-height: 320px;
  background: $darkBlue;
  color: #fff;
}
footer .container {padding-bottom: 0;}
footer h1 {margin-bottom: 1em;}
/*footer input[type="mail"],
footer .button {border-radius: 0;}*/
footer p {
  margin: 2.5em auto 4em;
  max-width: 600px;
}
@media screen and (max-width: 768px) {
  footer h1 {
    margin: 0 auto 1em auto;
    width: 80%;
  }
  footer p {width: 80%;}
}
footer .row:last-child p {text-align: center;}
footer a {
  margin-left: .5em;
  padding: 1em 0;
  width: 3.25em;
  text-align: center;
  text-decoration: none;
  color: #fff;
  border: .1em solid;
  border-radius: 50%;
  transition: color .25s;
  &:focus,
  &:hover {color: lighten($darkBlue, 7%);}
  &:active {color: darken($darkBlue, 7%);}
}

/* required styles */

.leaflet-map-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-pane,
.leaflet-tile-container,
.leaflet-overlay-pane,
.leaflet-shadow-pane,
.leaflet-marker-pane,
.leaflet-popup-pane,
.leaflet-overlay-pane svg,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
	position: absolute;
	left: 0;
	top: 0;
	}
.leaflet-container {
	overflow: hidden;
	-ms-touch-action: none;
	}
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow {
	-webkit-user-select: none;
	   -moz-user-select: none;
	        user-select: none;
	-webkit-user-drag: none;
	}
.leaflet-marker-icon,
.leaflet-marker-shadow {
	display: block;
	}
/* map is broken in FF if you have max-width: 100% on tiles */
.leaflet-container img {
	max-width: none !important;
	}
/* stupid Android 2 doesn't understand "max-width: none" properly */
.leaflet-container img.leaflet-image-layer {
	max-width: 15000px !important;
	}
.leaflet-tile {
	filter: inherit;
	visibility: hidden;
	}
.leaflet-tile-loaded {
	visibility: inherit;
	}
.leaflet-zoom-box {
	width: 0;
	height: 0;
	}
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
.leaflet-overlay-pane svg {
	-moz-user-select: none;
	}

.leaflet-tile-pane    { z-index: 2; }
.leaflet-objects-pane { z-index: 3; }
.leaflet-overlay-pane { z-index: 4; }
.leaflet-shadow-pane  { z-index: 5; }
.leaflet-marker-pane  { z-index: 6; }
.leaflet-popup-pane   { z-index: 7; }

.leaflet-vml-shape {
	width: 1px;
	height: 1px;
	}
.lvml {
	behavior: url(#default#VML);
	display: inline-block;
	position: absolute;
	}

/* control positioning */

.leaflet-control {
	position: relative;
	z-index: 7;
	pointer-events: auto;
	}
.leaflet-top,
.leaflet-bottom {
	position: absolute;
	z-index: 1000;
	pointer-events: none;
	}
.leaflet-top {
	top: 0;
	}
.leaflet-right {
	right: 0;
	}
.leaflet-bottom {
	bottom: 0;
	}
.leaflet-left {
	left: 0;
	}
.leaflet-control {
	float: left;
	clear: both;
	}
.leaflet-right .leaflet-control {
	float: right;
	}
.leaflet-top .leaflet-control {
	margin-top: 10px;
	}
.leaflet-bottom .leaflet-control {
	margin-bottom: 10px;
	}
.leaflet-left .leaflet-control {
	margin-left: 10px;
	}
.leaflet-right .leaflet-control {
	margin-right: 10px;
	}

/* zoom and fade animations */

.leaflet-fade-anim .leaflet-tile,
.leaflet-fade-anim .leaflet-popup {
	opacity: 0;
	-webkit-transition: opacity 0.2s linear;
	   -moz-transition: opacity 0.2s linear;
	     -o-transition: opacity 0.2s linear;
	        transition: opacity 0.2s linear;
	}
.leaflet-fade-anim .leaflet-tile-loaded,
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
	opacity: 1;
	}

.leaflet-zoom-anim .leaflet-zoom-animated {
	-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
	   -moz-transition:    -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
	     -o-transition:      -o-transform 0.25s cubic-bezier(0,0,0.25,1);
	        transition:         transform 0.25s cubic-bezier(0,0,0.25,1);
	}
.leaflet-zoom-anim .leaflet-tile,
.leaflet-pan-anim .leaflet-tile,
.leaflet-touching .leaflet-zoom-animated {
	-webkit-transition: none;
	   -moz-transition: none;
	     -o-transition: none;
	        transition: none;
	}

.leaflet-zoom-anim .leaflet-zoom-hide {
	visibility: hidden;
	}

/* cursors */

.leaflet-clickable {
	cursor: pointer;
	}
.leaflet-container {
	cursor: -webkit-grab;
	cursor:    -moz-grab;
	}
.leaflet-popup-pane,
.leaflet-control {
	cursor: auto;
	}
.leaflet-dragging .leaflet-container,
.leaflet-dragging .leaflet-clickable {
	cursor: move;
	cursor: -webkit-grabbing;
	cursor:    -moz-grabbing;
	}

/* visual tweaks */

.leaflet-container {
	background: #ddd;
	outline: 0;
	}
.leaflet-container a {
	color: #0078A8;
	}
.leaflet-container a.leaflet-active {
	outline: 2px solid orange;
	}
.leaflet-zoom-box {
	border: 2px dotted #38f;
	background: rgba(255,255,255,0.5);
	}

/* general typography */
.leaflet-container {
	font: 12px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif;
	}

/* general toolbar styles */

.leaflet-bar {
	box-shadow: 0 1px 5px rgba(0,0,0,0.65);
	border-radius: 4px;
	}
.leaflet-bar a,
.leaflet-bar a:hover {
	background-color: #fff;
	border-bottom: 1px solid #ccc;
	width: 26px;
	height: 26px;
	line-height: 26px;
	display: block;
	text-align: center;
	text-decoration: none;
	color: black;
	}
.leaflet-bar a,
.leaflet-control-layers-toggle {
	background-position: 50% 50%;
	background-repeat: no-repeat;
	display: block;
	}
.leaflet-bar a:hover {
	background-color: #f4f4f4;
	}
.leaflet-bar a:first-child {
	border-top-left-radius: 4px;
	border-top-right-radius: 4px;
	}
.leaflet-bar a:last-child {
	border-bottom-left-radius: 4px;
	border-bottom-right-radius: 4px;
	border-bottom: none;
	}
.leaflet-bar a.leaflet-disabled {
	cursor: default;
	background-color: #f4f4f4;
	color: #bbb;
	}

.leaflet-touch .leaflet-bar a {
	width: 30px;
	height: 30px;
	line-height: 30px;
	}

/* zoom control */

.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
	font: bold 18px 'Lucida Console', Monaco, monospace;
	text-indent: 1px;
	}
.leaflet-control-zoom-out {
	font-size: 20px;
	}

.leaflet-touch .leaflet-control-zoom-in {
	font-size: 22px;
	}
.leaflet-touch .leaflet-control-zoom-out {
	font-size: 24px;
	}

/* layers control */

.leaflet-control-layers {
	box-shadow: 0 1px 5px rgba(0,0,0,0.4);
	background: #fff;
	border-radius: 5px;
	}
.leaflet-control-layers-toggle {
	background-image: url(images/layers.png);
	width: 36px;
	height: 36px;
	}
.leaflet-retina .leaflet-control-layers-toggle {
	background-image: url(images/layers-2x.png);
	background-size: 26px 26px;
	}
.leaflet-touch .leaflet-control-layers-toggle {
	width: 44px;
	height: 44px;
	}
.leaflet-control-layers .leaflet-control-layers-list,
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
	display: none;
	}
.leaflet-control-layers-expanded .leaflet-control-layers-list {
	display: block;
	position: relative;
	}
.leaflet-control-layers-expanded {
	padding: 6px 10px 6px 6px;
	color: #333;
	background: #fff;
	}
.leaflet-control-layers-selector {
	margin-top: 2px;
	position: relative;
	top: 1px;
	}
.leaflet-control-layers label {
	display: block;
	}
.leaflet-control-layers-separator {
	height: 0;
	border-top: 1px solid #ddd;
	margin: 5px -10px 5px -6px;
	}

/* attribution and scale controls */

.leaflet-container .leaflet-control-attribution {
	background: #fff;
	background: rgba(255, 255, 255, 0.7);
	margin: 0;
	}
.leaflet-control-attribution,
.leaflet-control-scale-line {
	padding: 0 5px;
	color: #333;
	}
.leaflet-control-attribution a {
	text-decoration: none;
	}
.leaflet-control-attribution a:hover {
	text-decoration: underline;
	}
.leaflet-container .leaflet-control-attribution,
.leaflet-container .leaflet-control-scale {
	font-size: 11px;
	}
.leaflet-left .leaflet-control-scale {
	margin-left: 5px;
	}
.leaflet-bottom .leaflet-control-scale {
	margin-bottom: 5px;
	}
.leaflet-control-scale-line {
	border: 2px solid #777;
	border-top: none;
	line-height: 1.1;
	padding: 2px 5px 1px;
	font-size: 11px;
	white-space: nowrap;
	overflow: hidden;
	-moz-box-sizing: content-box;
	     box-sizing: content-box;

	background: #fff;
	background: rgba(255, 255, 255, 0.5);
	}
.leaflet-control-scale-line:not(:first-child) {
	border-top: 2px solid #777;
	border-bottom: none;
	margin-top: -2px;
	}
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
	border-bottom: 2px solid #777;
	}

.leaflet-touch .leaflet-control-attribution,
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
	box-shadow: none;
	}
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
	border: 2px solid rgba(0,0,0,0.2);
	background-clip: padding-box;
	}

/* popup */

.leaflet-popup {
	position: absolute;
	text-align: center;
	}
.leaflet-popup-content-wrapper {
	padding: 1px;
	text-align: left;
	border-radius: 12px;
	}
.leaflet-popup-content {
	margin: 13px 19px;
	line-height: 1.4;
	}
.leaflet-popup-content p {
	margin: 18px 0;
	}
.leaflet-popup-tip-container {
	margin: 0 auto;
	width: 40px;
	height: 20px;
	position: relative;
	overflow: hidden;
	}
.leaflet-popup-tip {
	width: 17px;
	height: 17px;
	padding: 1px;

	margin: -10px auto 0;

	-webkit-transform: rotate(45deg);
	   -moz-transform: rotate(45deg);
	    -ms-transform: rotate(45deg);
	     -o-transform: rotate(45deg);
	        transform: rotate(45deg);
	}
.leaflet-popup-content-wrapper,
.leaflet-popup-tip {
	background: white;

	box-shadow: 0 3px 14px rgba(0,0,0,0.4);
	}
.leaflet-container a.leaflet-popup-close-button {
	position: absolute;
	top: 0;
	right: 0;
	padding: 4px 4px 0 0;
	text-align: center;
	width: 18px;
	height: 14px;
	font: 16px/14px Tahoma, Verdana, sans-serif;
	color: #c3c3c3;
	text-decoration: none;
	font-weight: bold;
	background: transparent;
	}
.leaflet-container a.leaflet-popup-close-button:hover {
	color: #999;
	}
.leaflet-popup-scrolled {
	overflow: auto;
	border-bottom: 1px solid #ddd;
	border-top: 1px solid #ddd;
	}

.leaflet-oldie .leaflet-popup-content-wrapper {
	zoom: 1;
	}
.leaflet-oldie .leaflet-popup-tip {
	width: 24px;
	margin: 0 auto;

	-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
	filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
	}
.leaflet-oldie .leaflet-popup-tip-container {
	margin-top: -1px;
	}

.leaflet-oldie .leaflet-control-zoom,
.leaflet-oldie .leaflet-control-layers,
.leaflet-oldie .leaflet-popup-content-wrapper,
.leaflet-oldie .leaflet-popup-tip {
	border: 1px solid #999;
	}

/* div icon */

.leaflet-div-icon {
	background: #fff;
	border: 1px solid #666;
	}


text:
<?xml version="1.0"?>
<zend-config xmlns:zf="http://framework.zend.com/xml/zend-config-xml/1.0/">
    <id>featurette</id>
    <name>Featurette </name>
    <description></description>
    <author>pimcore.org</author>
    <version>1.0</version>
</zend-config>


text:
/*
MODULE     : textloc.h
DESCRIPTION: Header file to be used with textloc.c.
AUTHOR     : Fady Habra, 8715030, fady@cs.mcgill.ca
*/

#ifdef TEXTLOC
#define EXT
#else
#define EXT extern
#endif

#ifdef BOGUS
#define VSPREAD_THRESHOLD	((float) (2.0/100))
/* #define VAR_THRESHOLD		30 */
#define SAME_ROW_THRESHOLD	3
#define SAME_ROW_V		3
#define SAME_ROW_H		30
#define MAX_CHAR_SIZE		50
#define MIN_CHAR_SIZE		5

#define KILL_SMALL_COMP
#define SMALL_THRESHOLD		10
#endif

#define E_FALLING	0
#define E_RISING	1

typedef struct _PixT	PixT, *PixP;

struct _PixT
{
  int x;
  int y;
  PixP prev;
};

typedef struct _CompT	CompT, *CompP, **CompI;

struct _CompT					/* connected component type  */
{
  int id;					/* component id		     */
  int n;					/* number of pixels in comp. */
  int avg_row;					/* average row of pixels     */
  int x_max;					/* maximum x coordinate	     */
  int y_max;					/* maximum y coordinate	     */
  int x_min;					/* minimum x coordinate	     */
  int y_min;					/* minimum y coordinate	     */
  int y_left;					/* left endpoint y coord     */
  int y_right;					/* right endpoint y coord    */
  float sv_above;				/* sum of variances above    */
  float sv_below;				/* sum of variances below    */
  char type;					/* rising/falling edge	     */
  PixP pixels;					/* linked list of pixels     */
  CompP paired;					/* paired opposite comp.     */
  char extended;				/* extension checked flag    */
  CompP prev;					/* previous connected comp   */
};

/* External function prototypes. */

EXT void ConvertToFloat(ImgP);
EXT void HorzVariance(ImgP, int);
EXT CompP BuildConnectedComponents(ImgP, int);
EXT void PrintConnectedComponents(CompP);
EXT void WriteConnectedComponentsToPGM(CompP, ImgP);
EXT void FreeConnectedComponents(CompP);
EXT void EliminateLargeSpreadComponents(CompI, ImgP);
EXT void MergeRowComponents(CompI, ImgP);
EXT void PairComponents(CompI, ImgP);
EXT void ComputeBoundingBoxes(CompP, ImgP);

/* Internal function prototypes. */

void MergeComponents(CompP, CompP, CompP, CompI, ImgP);
void MergeToLeft(CompP, CompI, ImgP);
char Overlap(CompP, CompP);