text:
/*
 *
 *  Somado (System Optymalizacji Małych Dostaw)
 *  Optymalizacja dostaw towarów, dane OSM, problem VRP
 *
 *  Autor: Maciej Kawecki 2016 (praca inż. EE PW)
 *
 */
package gui.dialogs;

import gui.BgPanel;
import gui.SimpleDialog;
import gui.GUI;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import somado.IConf;

/**
 *
 * Ogolny szablon obiektu wywołującego informacyjne okienko dialogowe
 *
 * @author Maciej Kawecki
 * @version 1.0
 *
 */
@SuppressWarnings("serial")
public abstract class SimpleInfoDialog extends SimpleDialog {

   private final String textHeader;
   private final String text;
   private final int height;
   private final Icon icon;
   private final boolean vertScroll;

   /**
    * Konstruktor
    * @param frame Referencja do GUI
    * @param title Tytul okienka
    * @param textHeader
    * @param text Treść komunikatu
    * @param height Wysokość okienka
    * @param icon Ikona okienka
    * @param vertScroll True jezeli pole tekstowe ma byc przewijane
    */
   public SimpleInfoDialog(GUI frame, String title, String textHeader, String text,
                             int height, Icon icon, boolean vertScroll) {

     super(frame, IConf.APP_NAME + (!title.isEmpty() ? " - " : "") + title);
     this.textHeader = textHeader;
     this.text = text.replace("\n", System.getProperty("line.separator"));
     this.height = height;
     this.icon = icon;
     this.vertScroll = vertScroll;

   }

   /**
    * Konstruktor
    * @param frame Referencja do GUI
    * @param title Tytul okienka
    * @param textHeader
    * @param text Treść komunikatu
    * @param height Wysokość okienka
    * @param icon Ikona okienka
    */
   public SimpleInfoDialog(GUI frame, String title, String textHeader, String text,
                             int height, Icon icon) {

    this(frame, title, textHeader, text, height, icon, true);

   }

   /**
    * Konstruktor
    * @param frame Referencja do GUI
    * @param text Treść komunikatu
    * @param height Wysokość okienka
    * @param icon Ikona okienka
    */
   public SimpleInfoDialog(GUI frame, String text, int height, Icon icon) {

     this(frame, "", "", text, height, icon, false);

   }

   /**
    * Wywolanie okienka dialogowego
    */
   protected void showDialog() {

     super.showDialog(350, height);

   }

   /**
    * Dolny panel z przyciskami
    * @return Dolny panel
    */
   protected abstract JPanel buttonPanel();

   /**
    * Metoda wyświetlająca zawartość okienka
    */
   @Override
   protected void getContent()  {

      JPanel mainPanel = new BgPanel("bg_dialog.jpg");

      if (!textHeader.isEmpty()) {
        JLabel head = new JLabel(textHeader, JLabel.LEFT);
        head.setBorder(new EmptyBorder(0, 0, 0, 62));
        mainPanel.add(head);
      }

      JPanel p = new JPanel();
      p.setOpaque(false);
      p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));

      JLabel ico = new JLabel(icon);
      ico.setBorder(new EmptyBorder(0, 15, 0, 25));
      p.add(ico);

      JTextArea tx = new JTextArea(text);
      tx.setLineWrap(true);
      tx.setWrapStyleWord(true);
      tx.setEditable(false);
      tx.setOpaque(false);
      tx.setRows(5);
      tx.setBackground(p.getBackground());
      tx.setBorder(new EmptyBorder(10, 0, 10, 10));
      JScrollPane sc = new JScrollPane(tx);
      sc.setOpaque(false);
      sc.setBorder(null);
      sc.getViewport().setOpaque(false);
      sc.getViewport().setBorder(null);
      sc.setPreferredSize(new Dimension(250, height-95));
      sc.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
      sc.setVerticalScrollBarPolicy(vertScroll ? ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
                                    : ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
      p.add(sc);

      mainPanel.add(p);
      mainPanel.add(buttonPanel());

      add(mainPanel);

   }

}


text:
.class Lcom/google/android/gms/maps/GoogleMap$10;
.super Lcom/google/android/gms/maps/internal/f$a;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/google/android/gms/maps/GoogleMap;->setOnInfoWindowClickListener(Lcom/google/android/gms/maps/GoogleMap$OnInfoWindowClickListener;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic BF:Lcom/google/android/gms/maps/GoogleMap$OnInfoWindowClickListener;

.field final synthetic Bu:Lcom/google/android/gms/maps/GoogleMap;

# direct methods
.method constructor <init>(Lcom/google/android/gms/maps/GoogleMap;Lcom/google/android/gms/maps/GoogleMap$OnInfoWindowClickListener;)V
    .locals 0

    iput-object p1, p0, Lcom/google/android/gms/maps/GoogleMap$10;->Bu:Lcom/google/android/gms/maps/GoogleMap;

    iput-object p2, p0, Lcom/google/android/gms/maps/GoogleMap$10;->BF:Lcom/google/android/gms/maps/GoogleMap$OnInfoWindowClickListener;

    invoke-direct {p0}, Lcom/google/android/gms/maps/internal/f$a;-><init>()V

    return-void
.end method

# virtual methods
.method public e(Lcom/google/android/gms/maps/model/internal/d;)V
    .locals 2

    iget-object v0, p0, Lcom/google/android/gms/maps/GoogleMap$10;->BF:Lcom/google/android/gms/maps/GoogleMap$OnInfoWindowClickListener;

    new-instance v1, Lcom/google/android/gms/maps/model/Marker;

    invoke-direct {v1, p1}, Lcom/google/android/gms/maps/model/Marker;-><init>(Lcom/google/android/gms/maps/model/internal/d;)V

    invoke-interface {v0, v1}, Lcom/google/android/gms/maps/GoogleMap$OnInfoWindowClickListener;->onInfoWindowClick(Lcom/google/android/gms/maps/model/Marker;)V

    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
Chart Tool has several Gulp commands you can use:

* `gulp`: Default command, will build JS and CSS files, watch for changes, and start up both BrowserSync and Meteor.js servers for development. Equivalent to running `gulp lib-serve && gulp meteor-serve`
* `gulp meteor-serve`: Starts up a local Meteor instance of the interface at [localhost:3000](http://localhost:3000) and watches for file changes
* `gulp lib-serve`: Starts up a local BrowserSync instance of the frontend at [localhost:3030](http://localhost:3030) and watches for file changes
* `gulp meteor-build`: Builds the back end into a tarball in the `/dist` folder, ready for deployment to a server
* `gulp lib-build`: Builds the static assets for the front-end library into the `/dist` folder
* `gulp buildver`: Returns the build version variable present in package.json. Optionally, accepts a `set` argument which edits the buildVer value. For instance, `gulp buildver --set=12` will set `buildVer` in package.json to "12". Used for tracking build versions during the deployment process

There are also a few gulp tasks used by _other_ gulp tasks. They are:

* `gulp _browsersync`: Starts up a BrowserSync server
* `gulp _browserSyncWatch`: Watches for file changes and reloads BrowserSync when a change is detected
* `gulp _scss`: Processes SCSS files for the library
* `gulp _scss-build`: Builds minified CSS files from the SCSS source
* `gulp _webpack-build-dev`: Processes JS files for the library
* `gulp _webpack-build`: Builds and minifies JS files for the library
* `gulp _meteor-dev`: Runs a development Meteor environment
* `gulp _set-version`: Propagates the current version in `package.json` to all files that require a version string. Automatically run for all other gulp tasks
* `gulp _clean-lib`: Removes everything from the `dist` folder specific to the project version
* `gulp _clean-meteor`: Removes all built Meteor tarballs from `dist/meteor`
* `gulp _watch`: Watches for file changes and triggers `gulp _webpack-build-dev` and `gulp _scss` when a change is detected


text:
<form class="time-entry-form pure-form pure-form-stacked" name="form" autocomplete="off" novalidate>
    <fieldset>
        <legend>{{ ctrl.formTitle }}</legend>
        <input type="number" min="0" max="99" name="hours" placeholder="Hours" ng-model="ctrl.duration.hours"><!--
        --><input type="number" min="0" max="59" name="minutes" placeholder="Minutes" ng-model="ctrl.duration.minutes" auto-focus><!--
        --><button class="pure-button amount-increment" ng-click="ctrl.duration.increment()">+30</button>
        <textarea name="comment" placeholder="Comment" ng-model="ctrl.timeEntry.comment" auto-size></textarea>
        <button type="submit" class="pure-button pure-button-primary" ng-click="ctrl.submitForm()" ng-disabled="form.$invalid">Save</button>
    </fieldset>
</form>


text:
package org.apache.servicecomb.config.archaius.sources;

public class ConfigSourceMaker {

  public static MicroserviceConfigurationSource yamlConfigSource() {
    MicroserviceConfigLoader loader = new MicroserviceConfigLoader();
    loader.loadAndSort();

    return new MicroserviceConfigurationSource(loader.getConfigModels());
  }
}


text:
"use strict";

var browser = require('./lib/browser');

/**
 *  API
 */
exports.browser = browser.browser;


text:
package com.jamesmorrisstudios.googleplaylibrary.util;

import android.support.annotation.Nullable;

import com.jamesmorrisstudios.appbaselibrary.UtilsVersion;

/**
 * AdUsage Manager.
 * <p/>
 * Created by James on 5/11/2015.
 */
public final class UtilsAds {
    private static String mopubNativeAdId;
    private static String mopubNativeAdIdFull;
    private static String mopubInterstitialAdId;
    private static String mopubRewardAdId;
    private static boolean alreadyRunning = false;
    private static long lastInterstitialShownTimeStamp = 0;

    /**
     * @return True if we are ready to show another full page ad
     */
    public static boolean allowInterstitial() {
        return !UtilsVersion.isPro() && System.currentTimeMillis() - lastInterstitialShownTimeStamp >= 1000 * 60 * 2; //2 minutes
    }

    /**
     * Updates to this being the last time a full page ad was shown
     */
    public static void updateAdShowTimeStamp() {
        lastInterstitialShownTimeStamp = System.currentTimeMillis();
    }

    /**
     * Call this from the activity onCreate function to ensure the ad manager is ready.
     */
    public static void onCreate() {
        if (!alreadyRunning) {
            updateAdShowTimeStamp();
            alreadyRunning = true;
        }
    }

    /**
     * @return The mopub native ad Id. Null if none set.
     */
    @Nullable
    public static String getMopubNativeAdId() {
        return mopubNativeAdId;
    }

    /**
     * @param mopubAdId The mopub native ad id.
     */
    public static void setMopubNativeAdId(@Nullable String mopubAdId) {
        UtilsAds.mopubNativeAdId = mopubAdId;
    }

    /**
     * @return The mopub native ad id for full view. Null if none set.
     */
    @Nullable
    public static String getMopubNativeAdIdFull() {
        return mopubNativeAdIdFull;
    }

    /**
     * @param mopubAdIdFull The mopub native ad id for full view
     */
    public static void setMopubNativeAdIdFull(@Nullable String mopubAdIdFull) {
        UtilsAds.mopubNativeAdIdFull = mopubAdIdFull;
    }

    /**
     * @return The mopub interstitial ad id. Null if none.
     */
    @Nullable
    public static String getMopubInterstitialAdId() {
        return mopubInterstitialAdId;
    }

    /**
     * @param mopubInterstitialAdId The mopub interstitial ad id.
     */
    public static void setMopubInterstitialAdId(@Nullable String mopubInterstitialAdId) {
        UtilsAds.mopubInterstitialAdId = mopubInterstitialAdId;
    }

    /**
     * @return The mopub reward ad id. Null if none.
     */
    @Nullable
    public static String getMopubRewardAdId() {
        return mopubRewardAdId;
    }

    /**
     * @param mopubRewardAdId The mopub reward ad id.
     */
    public static void setMopubRewardAdId(@Nullable String mopubRewardAdId) {
        UtilsAds.mopubRewardAdId = mopubRewardAdId;
    }

    /**
     * @return True if already initialized.
     */
    public static boolean isAlreadyRunning() {
        return alreadyRunning;
    }

}


text:
@interface DetailView : UIView {
    IssueWrapper *issueWrapper;
}

@property (nonatomic, retain) IssueWrapper *issueWrapper;

@end


text:
<!DOCTYPE html>

	<title>Let's Go!</title>
	<link href="style.css" rel="stylesheet" type="text/css">
	<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400|Kaushan+Script' rel='stylesheet' type='text/css'>

				Let's Go!

				<form action="" method="POST">
					<input class="login-field" id="username" type="text" name="username" placeholder="Username">

					<input class="login-field" id="password" type="password" name="password" placeholder="Password">

					<input type="submit" class="button login-button" value="Login">

				</form>


text:
import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import AuthActionCreator from '../../actions/auth'
import SendVerificationCodeForm from './SendVerificationCodeForm'
import ValidateVerificationCode from './ValidateVerificationCodeForm'
import NewPasswordForm from './NewPasswordForm'
import apiOptionsFromState from '../../api/lib/apiOptionsFromState'
import usersApiClient from '../../api/users'
import styles from './ForgotPasswordForm.scss'

class ForgotPasswordForm extends Component {
  constructor (props, context) {
    super(props, context)
    this.nextPage = this.nextPage.bind(this)
    this.validate = this.validate.bind(this)
    this.changePass = this.changePass.bind(this)
    this.onChange = this.onChange.bind(this)
    this.state = {
      page: 1,
      email: '',
      code: '',
      password: '',
      error: ''
    }
  }

  onChange (event) {
    this.setState({ [event.target.name]: event.target.value })
  }

  async nextPage () {
    const apiOptions = apiOptionsFromState()
    const response = await usersApiClient.createCode(apiOptions, this.state.email)
    if (response.status === 200) {
      this.setState({
        page: this.state.page + 1,
        error: ''
      })
    } else {
      this.setState({ error: 'send email failed!' })
    }
  }

  async validate () {
    const { email, code } = this.state
    const apiOptions = apiOptionsFromState()
    const response = await usersApiClient.validateCode(apiOptions, email, code)
    if (response.status === 200) {
      this.setState({
        page: this.state.page + 1,
        error: ''
      })
    } else {
      this.setState({ error: 'Incorrect code, please try again!' })
    }
  }

  changePass () {
    return this.props.changePassword(this.state.email, this.state.password).then(() => {
      this.context.router.history.push('/')
    }).catch(error => {
      this.setState({ error: error.message })
    })
  }

  render () {
    const { page, error } = this.state
    return (
      <Fragment>
        {page === 1 && <SendVerificationCodeForm email={this.state.email} onChangeEmail={this.onChange} nextPage={this.nextPage} />}
        {page === 2 &&

            <ValidateVerificationCode code={this.state.code} onChangeCode={this.onChange} validateCode={this.validate} />

}
        {page === 3 &&

            <NewPasswordForm password={this.state.password} onChangePassword={this.onChange} changePass={this.changePass} />

}

          {error}

      </Fragment>

    )
  }
}

ForgotPasswordForm.contextTypes = {
  router: PropTypes.object
}

ForgotPasswordForm.propTypes = {
  sendValidationCode: PropTypes.func,
  validateCode: PropTypes.func,
  email: PropTypes.string,
  handleSubmit: PropTypes.func,
  error: PropTypes.any,
  changePassword: PropTypes.func
}

const mapDispatchToProps = {
  changePassword: AuthActionCreator.changePassword
}

export default connect(null, mapDispatchToProps)(ForgotPasswordForm)


text:
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using UnityEngine;
using System.Collections.Generic;
using Firebase.Leaderboard;

namespace Hamster.Menus {

  // Interface class for providing code access to the GUI
  // elements in the level complete prefab.  It's the menu
  // that shows up when you finish a level.
  public class LevelFinishedGUI : BaseMenu {

    // These fields are set in the inspector.
    public UnityEngine.UI.Text ElapsedTimeText;
    public UnityEngine.UI.Text NewRecordText;
    public GUIButton SubmitButton;
    public GUIButton RetryButton;
    public GUIButton MainButton;
    public GUIButton LevelsButton;
    public LeaderboardController LeaderboardControllerPrefab;
  }
}


text:
layout: votes
date: June 14, 2017 - June 16, 2017
year: "2017"
month: "06"
rules: 3152013
permalink: meetings/2017/06/votes
registered: 10
attended: 10
ooe: 18
imove: 10
---

Meeting did not meet quorum. No votes were held.


text:
module Fokus

  class Error < StandardError; end

end


text:
package com.github.javaparser.bdd;

import com.github.javaparser.bdd.steps.ComparingSteps;
import com.github.javaparser.bdd.steps.SharedSteps;
import de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.junit.runner.RunWith;

import java.util.HashMap;
import java.util.Map;

@RunWith(JUnitReportingRunner.class)
public class ComparingTest extends BasicJBehaveTest {

    @Override
    public InjectableStepsFactory stepsFactory() {
        Map<String, Object> state = new HashMap<>();

        return new InstanceStepsFactory(configuration(),
                new SharedSteps(state),
                new ComparingSteps(state));
    }

    public ComparingTest() {
        super("**/bdd/comparing*.story");
    }
}


text:
<!-- @TEMPLATE -->
<textarea name="html" data-src="./setting/tab/index.html"></textarea>
<textarea name="html" data-src="./setting/profile/index.html"></textarea>
<textarea name="html" data-src="./setting/permission/index.html"></textarea>
<!-- /@TEMPLATE -->


text:
namespace net {

class IOBuffer;

class UploadDataStream {
 public:
  explicit UploadDataStream(const UploadData* data);
  ~UploadDataStream();

  // Returns the stream's buffer and buffer length.
  IOBuffer* buf() const { return buf_; }
  size_t buf_len() const { return buf_len_; }

  // Call to indicate that a portion of the stream's buffer was consumed.  This
  // call modifies the stream's buffer so that it contains the next segment of
  // the upload data to be consumed.
  void DidConsume(size_t num_bytes);

  // Returns the total size of the data stream and the current position.
  uint64 size() const { return total_size_; }
  uint64 position() const { return current_position_; }

 private:
  void FillBuf();

  const UploadData* data_;

  // This buffer is filled with data to be uploaded.  The data to be sent is
  // always at the front of the buffer.  If we cannot send all of the buffer at
  // once, then we memmove the remaining portion and back-fill the buffer for
  // the next "write" call.  buf_len_ indicates how much data is in the buffer.
  enum { kBufSize = 16384 };
  scoped_refptr<IOBuffer> buf_;
  size_t buf_len_;

  // Iterator to the upload element to be written to the send buffer next.
  std::vector<UploadData::Element>::const_iterator next_element_;

  // The byte offset into next_element_'s data buffer if the next element is
  // a TYPE_BYTES element.
  size_t next_element_offset_;

  // A stream to the currently open file, for next_element_ if the next element
  // is a TYPE_FILE element.
  FileStream next_element_stream_;

  // The number of bytes remaining to be read from the currently open file
  // if the next element is of TYPE_FILE.
  uint64 next_element_remaining_;

  // Size and current read position within the stream.
  uint64 total_size_;
  uint64 current_position_;

  DISALLOW_EVIL_CONSTRUCTORS(UploadDataStream);
};

}  // namespace net

#endif  // NET_BASE_UPLOAD_DATA_STREAM_H_


text:
define([
    'backbone'
    , 'app'
], function (Backbone, App) {
    var GenericModel = Backbone.Model.extend({

	initialize: function(params) {
	    this.url = App.getBaseURL() + "generic/";
	}
    });

    return GenericModel;
});


text:
//
//  ZZPublishView.m
//  百思不得姐
//
//  Created by ZZBelieve on 16/3/29.
//  Copyright © 2016年 ZZBelieve. All rights reserved.
//

#import "ZZPublishView.h"
#import "ZZVerticalButton.h"
#import <POP.h>
#import "ZZPostWordViewController.h"
#import "ZZMainNavgationController.h"
static CGFloat const KAnimatioonDelay = 0.1;
static CGFloat const kSpringFactory = 10;

@interface ZZPublishView ()

@end

@implementation ZZPublishView

static UIWindow *_window;

+ (void)Show{

    _window = [[UIWindow alloc] init];
    _window.frame = [UIScreen mainScreen].bounds;
    _window.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    _window.hidden = NO;

    ZZPublishView *PublishView = [ZZPublishView viewFromXib];
    PublishView.frame = _window.bounds;
    [_window addSubview:PublishView];
}
- (void)awakeFromNib{
    // Do any additional setup after loading the view from its nib.

    // 不能被点击
    self.userInteractionEnabled = NO;

    // 数据
    NSArray *images = @[@"publish-video", @"publish-picture", @"publish-text", @"publish-audio", @"publish-review", @"publish-offline"];
    NSArray *titles = @[@"发视频", @"发图片", @"发段子", @"发声音", @"审帖", @"离线下载"];

    //最大列数
    int maxCols = 3;

    CGFloat buttonW = 72;
    CGFloat buttonH = buttonW + 30;

    CGFloat buttonStartX = 20;
    CGFloat buttonStartY = (ZZScreenHeight - 2 * buttonH) * 0.5;

    CGFloat marginX = (ZZScreenWidth - 2 * buttonStartX - maxCols * buttonW) / (maxCols - 1);

    for (int i = 0; i<images.count; i++) {

        ZZVerticalButton *button = [ZZVerticalButton buttonWithType:UIButtonTypeCustom];

        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
        button.tag = 100 +i;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];

        int row = i / maxCols;
        int col = i % maxCols;

//        button.zz_X = buttonStartX + col * (marginX + buttonW);
//
//
//        button.zz_Y = buttonStartY + row * (buttonH + 10);

        CGFloat buttonX = buttonStartX + col * (marginX + buttonW);

        CGFloat buttonEndY = buttonStartY + row * (buttonH + 10);

        CGFloat buttonBeginY = buttonEndY - ZZScreenHeight;
        [self addSubview:button];

        //按钮动画

        POPSpringAnimation *animation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];

        animation.fromValue = [NSValue valueWithCGRect:CGRectMake(buttonX, buttonBeginY, buttonW, buttonH)];

        animation.toValue = [NSValue valueWithCGRect:CGRectMake(buttonX, buttonEndY, buttonW, buttonH)];

        animation.springBounciness = kSpringFactory;
        animation.springSpeed = kSpringFactory;

        animation.beginTime = CACurrentMediaTime() + KAnimatioonDelay * i;

        [button pop_addAnimation:animation forKey:nil];
    }

    CGFloat app_sloganImageViewX = ZZScreenWidth * 0.5;

    CGFloat app_sloganImageEndY = ZZScreenHeight * 0.2;
    CGFloat app_sloganImageBeginY = app_sloganImageEndY - ZZScreenHeight;

    UIImageView *app_sloganImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"app_slogan"]];
//    app_sloganImageView.zz_Y = ZZScreenHeight * 0.2;
//    app_sloganImageView.zz_CenterX = ZZScreenWidth * 0.5 ;
    [self addSubview:app_sloganImageView];

    //slogan动画

    POPSpringAnimation *animation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewCenter];

    animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(app_sloganImageViewX, app_sloganImageBeginY)];
    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(app_sloganImageViewX, app_sloganImageEndY)];
    animation.springBounciness = kSpringFactory;
    animation.springSpeed = kSpringFactory;
    [animation setCompletionBlock:^(POPAnimation *ani, BOOL finish) {

        // 标语动画执行完毕, 恢复点击事件
        self.userInteractionEnabled = YES;
    }];
    [app_sloganImageView pop_addAnimation:animation forKey:nil];

}

- (void)buttonClick:(UIButton *)button{

    [self cancleBlock:^{

        //发段子

        if (button.tag == 102) {

            ZZLogFunc

            ZZPostWordViewController *vc = [[ZZPostWordViewController alloc] init];
            ZZMainNavgationController *nav = [[ZZMainNavgationController alloc] initWithRootViewController:vc];

            UIViewController *root = [UIApplication sharedApplication].keyWindow.rootViewController;
            [root presentViewController:nav animated:YES completion:nil];
        }

    }];

}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self cancleBlock:nil];

}

- (void)cancleBlock:(void (^)())block{

//    self.userInteractionEnabled = YES;

    // 不能被点击
    self.userInteractionEnabled = NO;

    //    [self cancleButtonClick:];

    int beginIndex = 1;
    for (int i = beginIndex; i<self.subviews.count; i++) {

        UIView *subView = self.subviews[i];

        // 基本动画
        POPBasicAnimation *anim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewCenter];
        CGFloat centerY = subView.zz_CenterY + ZZScreenHeight;
        anim.toValue = [NSValue valueWithCGPoint:CGPointMake(subView.zz_CenterX, centerY)];
        anim.beginTime = CACurrentMediaTime() + (i - beginIndex) * KAnimatioonDelay;
        [subView pop_addAnimation:anim forKey:nil];

        // 监听最后一个动画
        if (i == self.subviews.count - 1) {

            [anim setCompletionBlock:^(POPAnimation *anim, BOOL finished) {
//                [self dismissViewControllerAnimated:NO completion:nil]

                [self removeFromSuperview];

                _window.hidden = YES;
                _window = nil;

                // 执行传进来的completionBlock参数
                //                if (completionBlock) {
                //                    completionBlock();
                //                }
                                !block ? : block();
            }];
        }

    }

}

- (IBAction)cancleButtonClick:(id)sender {

    [self cancleBlock:nil];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
We will install REMI's PHP 5.6 and some of the basic plugins, like memcached,
mbstring etc. In case of conflicting releases with epel, we'll add
yum-plugin-priorities too.


text:
<?php
/**
 *Class for exceptions for member
 *
 *@package Exception
 *@author  Vinicius Pinheiro <viny-pinheiro@hotmail.com>
 *@license MIT License
 *@link    http://eletronjun.com.br/class/exception/memberException.php
 */
namespace exception{

    /**
     * @codeCoverageIgnore
     */
    class MemberException extends \Exception
    {
        public function __construct($message, $code = 0, Exception $previous = null)
        {
            parent::__construct($message, $code, $previous);
        }

        public function __toString()
        {
            return $this->message;
        }
    }
}


text:
using System;
using System.Runtime.InteropServices;
using System.ServiceModel;
using Castle.Facilities.WcfIntegration;
using Castle.MicroKernel;
using Microsoft.SharePoint;

namespace CvrService.Service
{
    [Guid("BFF111CF-CC01-4ABD-9F05-E596B8FCD22D")]
    public class CvrServiceHostFactory : DefaultServiceHostFactory
    {
        public CvrServiceHostFactory()
            : base(GetAndInitializeKernel())
        {
        }

        private static IKernel GetAndInitializeKernel()
        {
            Container.EnsureInitialized();
            return Container.Current.Kernel;
        }

        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            ServiceHostBase serviceHost = base.CreateServiceHost(constructorString, baseAddresses);
            serviceHost.Configure(SPServiceAuthenticationMode.Claims);
            return serviceHost;
        }
    }
}


text:
package fail2ban

import (
	"errors"
	"fmt"
	"os/exec"
	"strings"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/plugins/inputs"
	"strconv"
)

var (
	execCommand = exec.Command // execCommand is used to mock commands in tests.
)

type Fail2ban struct {
	path    string
	UseSudo bool
}

var sampleConfig = `
  ## fail2ban-client require root access.
  ## Setting 'use_sudo' to true will make use of sudo to run fail2ban-client.
  ## Users must configure sudo to allow telegraf user to run fail2ban-client with no password.
  ## This plugin run only "fail2ban-client status".
  use_sudo = false
`

var metricsTargets = []struct {
	target string
	field  string
}{
	{
		target: "Currently failed:",
		field:  "failed",
	},
	{
		target: "Currently banned:",
		field:  "banned",
	},
}

func (f *Fail2ban) Description() string {
	return "Read metrics from fail2ban."
}

func (f *Fail2ban) SampleConfig() string {
	return sampleConfig
}

func (f *Fail2ban) Gather(acc telegraf.Accumulator) error {
	if len(f.path) == 0 {
		return errors.New("fail2ban-client not found: verify that fail2ban is installed and that fail2ban-client is in your PATH")
	}

	name := f.path
	var arg []string

	if f.UseSudo {
		name = "sudo"
		arg = append(arg, f.path)
	}

	args := append(arg, "status")

	cmd := execCommand(name, args...)
	out, err := cmd.Output()
	if err != nil {
		return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out))
	}
	lines := strings.Split(string(out), "\n")
	const targetString = "Jail list:"
	var jails []string
	for _, line := range lines {
		idx := strings.LastIndex(line, targetString)
		if idx < 0 {
			// not target line, skip.
			continue
		}
		jails = strings.Split(strings.TrimSpace(line[idx+len(targetString):]), ", ")
		break
	}

	for _, jail := range jails {
		fields := make(map[string]interface{})
		args := append(arg, "status", jail)
		cmd := execCommand(name, args...)
		out, err := cmd.Output()
		if err != nil {
			return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out))
		}

		lines := strings.Split(string(out), "\n")
		for _, line := range lines {
			key, value := extractCount(line)
			if key != "" {
				fields[key] = value
			}
		}
		acc.AddFields("fail2ban", fields, map[string]string{"jail": jail})
	}
	return nil
}

func extractCount(line string) (string, int) {
	for _, metricsTarget := range metricsTargets {
		idx := strings.LastIndex(line, metricsTarget.target)
		if idx < 0 {
			continue
		}
		ban := strings.TrimSpace(line[idx+len(metricsTarget.target):])
		banCount, err := strconv.Atoi(ban)
		if err != nil {
			return "", -1
		}
		return metricsTarget.field, banCount
	}
	return "", -1
}

func init() {
	f := Fail2ban{}
	path, _ := exec.LookPath("fail2ban-client")
	if len(path) > 0 {
		f.path = path
	}
	inputs.Add("fail2ban", func() telegraf.Input {
		f := f
		return &f
	})
}


text:
package eu.mrico.creole.test;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import eu.mrico.creole.Creole;
import eu.mrico.creole.ast.Document;
import eu.mrico.creole.ast.HorizontalRule;
import eu.mrico.creole.ast.Image;
import eu.mrico.creole.ast.LineBreak;
import eu.mrico.creole.ast.Link;
import eu.mrico.creole.ast.Paragraph;
import eu.mrico.creole.ast.Text;

/**
 * @see http://www.wikicreole.org/wiki/Creole1.0#section-Creole1.0-LineBreaks
 */
public class ImageTest {

    @Test
    public void imageWithAlt() {
        Document is = Creole.parse("{{myimage.png|this is my image}}");

        Document expected = (Document) new Document()
            .add(new Image("myimage.png", "this is my image"));

        assertEquals(expected, is);
    }

    @Test
    public void imageWithoutAlt() {
        Document is = Creole.parse("{{myimage.png}}");

        Document expected = (Document) new Document()
            .add(new Image("myimage.png", "myimage.png"));

        assertEquals(expected, is);
    }
}


text:
            <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

            </button>

                        {% if authed() %}

plused

                        {% endif %}

about

                            <form class=navbar-form action='/'>

<input type='text' name=q placeholder='search tags seperated by ;'>

                            </form>

                        {% if authed() %}
                            logout
                        {% else %}
                            login
                        {% endif %}


text:
static const CGFloat kImagePadding = 16;
static const CGFloat kImageHeight = 40;
static const CGFloat kWithImageRightPadding = 12;
static const CGFloat kTextVerticalPadding = 12;
static const CGFloat kTitleColorOpacity = (CGFloat)0.87;
static const CGFloat kDetailsColorOpacity = (CGFloat)0.6;

static inline UIFont *defaultTitleFont(void) {
  return [UIFont systemFontOfSize:16];
}

static inline UIFont *defaultDetailsFont(void) {
  return [UIFont systemFontOfSize:14];
}

@implementation CollectionViewListCell {
  CGPoint _lastTouch;
  UIView *_contentWrapper;
  NSLayoutConstraint *_cellWidthConstraint;
  NSLayoutConstraint *_imageLeftPaddingConstraint;
  NSLayoutConstraint *_imageRightPaddingConstraint;
  NSLayoutConstraint *_imageWidthConstraint;
  BOOL _mdc_adjustsFontForContentSizeCategory;
  MDCInkView *_inkView;
}

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self commonCollectionViewListCellInit];
  }
  return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
  self = [super initWithCoder:aDecoder];
  if (self) {
    [self commonCollectionViewListCellInit];
  }
  return self;
}

- (void)commonCollectionViewListCellInit {
  _inkView = [[MDCInkView alloc] initWithFrame:self.bounds];
  _inkView.usesLegacyInkRipple = NO;
  [self addSubview:_inkView];

  _contentWrapper = [[UIView alloc] initWithFrame:self.contentView.bounds];
  _contentWrapper.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | MDFTrailingMarginAutoresizingMaskForLayoutDirection(
                                            self.effectiveUserInterfaceLayoutDirection);
  _contentWrapper.clipsToBounds = YES;
  [self.contentView addSubview:_contentWrapper];

  // Text label.
  _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
  _titleLabel.autoresizingMask = MDFTrailingMarginAutoresizingMaskForLayoutDirection(
      self.effectiveUserInterfaceLayoutDirection);

  // Detail text label.
  _detailsTextLabel = [[UILabel alloc] initWithFrame:CGRectZero];
  _detailsTextLabel.autoresizingMask = MDFTrailingMarginAutoresizingMaskForLayoutDirection(
      self.effectiveUserInterfaceLayoutDirection);

  [self resetCollectionViewListCell];

  [_contentWrapper addSubview:_titleLabel];
  [_contentWrapper addSubview:_detailsTextLabel];

  // Image view.
  _imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
  _imageView.autoresizingMask = MDFTrailingMarginAutoresizingMaskForLayoutDirection(
      self.effectiveUserInterfaceLayoutDirection);
  [self.contentView addSubview:_imageView];

  [self setupConstraints];
}

- (void)resetCollectionViewListCell {
  [self updateTitleFont];
  _titleLabel.textColor = [UIColor colorWithWhite:0 alpha:kTitleColorOpacity];
  _titleLabel.textAlignment = NSTextAlignmentNatural;
  _titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
  _titleLabel.numberOfLines = 1;

  [self updateDetailsFont];
  _detailsTextLabel.textColor = [UIColor colorWithWhite:0 alpha:kDetailsColorOpacity];
  _detailsTextLabel.textAlignment = NSTextAlignmentNatural;
  _detailsTextLabel.lineBreakMode = NSLineBreakByTruncatingTail;
  _detailsTextLabel.numberOfLines = 3;
}

- (void)setupConstraints {
  self.contentView.translatesAutoresizingMaskIntoConstraints = NO;

  _cellWidthConstraint = [NSLayoutConstraint constraintWithItem:self.contentView
                                                      attribute:NSLayoutAttributeWidth
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:nil
                                                      attribute:NSLayoutAttributeNotAnAttribute
                                                     multiplier:1
                                                       constant:0];

  _contentWrapper.translatesAutoresizingMaskIntoConstraints = NO;
  _titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
  _detailsTextLabel.translatesAutoresizingMaskIntoConstraints = NO;
  _imageView.translatesAutoresizingMaskIntoConstraints = NO;

  NSDictionary *metrics = @{
    @"kTextVerticalPadding" : @(kTextVerticalPadding),
    @"kImagePadding" : @(kImagePadding),
  };

  NSDictionary *views = @{
    @"contentView" : self.contentView,
    @"contentWrapper" : _contentWrapper,
    @"titleLabel" : _titleLabel,
    @"detailsTextLabel" : _detailsTextLabel,
    @"imageView" : _imageView,
  };

  NSMutableArray *constraints = [[NSMutableArray alloc] init];

  [constraints
      addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[contentView]|"
                                                                  options:0
                                                                  metrics:metrics
                                                                    views:views]];
  [constraints
      addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[contentView]|"
                                                                  options:0
                                                                  metrics:metrics
                                                                    views:views]];

  _imageLeftPaddingConstraint = [NSLayoutConstraint constraintWithItem:_imageView
                                                             attribute:NSLayoutAttributeLeft
                                                             relatedBy:NSLayoutRelationEqual
                                                                toItem:self.contentView
                                                             attribute:NSLayoutAttributeLeft
                                                            multiplier:1
                                                              constant:0];
  _imageLeftPaddingConstraint.active = YES;

  _imageRightPaddingConstraint = [NSLayoutConstraint constraintWithItem:_contentWrapper
                                                              attribute:NSLayoutAttributeLeft
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:_imageView
                                                              attribute:NSLayoutAttributeRight
                                                             multiplier:1
                                                               constant:kImagePadding];
  _imageRightPaddingConstraint.active = YES;

  _imageWidthConstraint = [NSLayoutConstraint constraintWithItem:_imageView
                                                       attribute:NSLayoutAttributeWidth
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:nil
                                                       attribute:NSLayoutAttributeNotAnAttribute
                                                      multiplier:1
                                                        constant:0];
  _imageWidthConstraint.active = YES;

  [constraints
      addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[contentWrapper]|"
                                                                  options:0
                                                                  metrics:metrics
                                                                    views:views]];

  [constraints
      addObjectsFromArray:[NSLayoutConstraint
                              constraintsWithVisualFormat:@"H:[contentWrapper]-(kImagePadding)-|"
                                                  options:0
                                                  metrics:metrics
                                                    views:views]];

  [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|[titleLabel]|"
                                                                           options:0
                                                                           metrics:nil
                                                                             views:views]];

  [constraints
      addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|[detailsTextLabel]|"
                                                                  options:0
                                                                  metrics:nil
                                                                    views:views]];

  [constraints
      addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:
                                                  @"V:|-(kTextVerticalPadding)-[titleLabel]["
                                                  @"detailsTextLabel]-(kTextVerticalPadding)-|"
                                                                  options:0
                                                                  metrics:metrics
                                                                    views:views]];

  [constraints addObject:[NSLayoutConstraint constraintWithItem:_imageView
                                                      attribute:NSLayoutAttributeCenterY
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.contentView
                                                      attribute:NSLayoutAttributeCenterY
                                                     multiplier:1
                                                       constant:0]];

  [constraints addObject:[NSLayoutConstraint constraintWithItem:_imageView
                                                      attribute:NSLayoutAttributeHeight
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:nil
                                                      attribute:NSLayoutAttributeNotAnAttribute
                                                     multiplier:1
                                                       constant:kImageHeight]];

  [NSLayoutConstraint activateConstraints:constraints];
}

- (void)setCellWidth:(CGFloat)width {
  _cellWidthConstraint.constant = width;
  _cellWidthConstraint.active = YES;
}

- (void)setImage:(UIImage *)image {
  _imageView.image = image;
  _imageView.contentMode = UIViewContentModeScaleAspectFit;
  if (image) {
    _imageWidthConstraint.constant = kImageHeight;
    _imageLeftPaddingConstraint.constant = kImagePadding;
    _imageRightPaddingConstraint.constant = kWithImageRightPadding;
  } else {
    _imageWidthConstraint.constant = 0;
    _imageLeftPaddingConstraint.constant = 0;
    _imageRightPaddingConstraint.constant = kImagePadding;
  }
}

- (void)prepareForReuse {
  [self setImage:nil];
  self.titleLabel.text = nil;
  self.detailsTextLabel.text = nil;

  [self resetCollectionViewListCell];
  [_inkView cancelAllAnimationsAnimated:NO];

  [super prepareForReuse];
}

- (void)setHighlighted:(BOOL)highlighted {
  [super setHighlighted:highlighted];
  if (highlighted) {
    [_inkView startTouchBeganAnimationAtPoint:_lastTouch completion:nil];
  } else {
    [_inkView startTouchEndedAnimationAtPoint:_lastTouch completion:nil];
  }
}

- (void)applyTypographyScheme:(id<MDCTypographyScheming>)typographyScheme {
  self.titleFont = typographyScheme.subtitle1;
  self.detailsFont = typographyScheme.body2;
}

#pragma mark - UIResponder

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  UITouch *touch = [touches anyObject];
  CGPoint location = [touch locationInView:self];
  _lastTouch = location;

  [super touchesBegan:touches withEvent:event];
}

#pragma mark - Dynamic Type Support

- (BOOL)mdc_adjustsFontForContentSizeCategory {
  return _mdc_adjustsFontForContentSizeCategory;
}

- (void)mdc_setAdjustsFontForContentSizeCategory:(BOOL)adjusts {
  _mdc_adjustsFontForContentSizeCategory = adjusts;

  if (_mdc_adjustsFontForContentSizeCategory) {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(contentSizeCategoryDidChange:)
                                                 name:UIContentSizeCategoryDidChangeNotification
                                               object:nil];
  } else {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIContentSizeCategoryDidChangeNotification
                                                  object:nil];
  }

  [self updateTitleFont];
  [self updateDetailsFont];
}

// Handles UIContentSizeCategoryDidChangeNotifications
- (void)contentSizeCategoryDidChange:(__unused NSNotification *)notification {
  [self updateTitleFont];
  [self updateDetailsFont];
}

- (void)setTitleFont:(UIFont *)titleFont {
  _titleFont = titleFont;
  [self updateTitleFont];
}

- (void)updateTitleFont {
  if (!_titleFont) {
    _titleFont = defaultTitleFont();
  }
  if (_mdc_adjustsFontForContentSizeCategory) {
    _titleLabel.font =
        [_titleFont mdc_fontSizedForMaterialTextStyle:MDCFontTextStyleSubheadline
                                 scaledForDynamicType:_mdc_adjustsFontForContentSizeCategory];
  } else {
    _titleLabel.font = _titleFont;
  }
  [self setNeedsLayout];
}

- (void)setDetailsFont:(UIFont *)detailsFont {
  _detailsFont = detailsFont;
  [self updateDetailsFont];
}

- (void)updateDetailsFont {
  if (!_detailsFont) {
    _detailsFont = defaultDetailsFont();
  }
  if (_mdc_adjustsFontForContentSizeCategory) {
    _detailsTextLabel.font =
        [_detailsFont mdc_fontSizedForMaterialTextStyle:MDCFontTextStyleBody1
                                   scaledForDynamicType:_mdc_adjustsFontForContentSizeCategory];
  } else {
    _detailsTextLabel.font = _detailsFont;
  }
  [self setNeedsLayout];
}

@end


text:
const int kDefaultDPI = 96;

namespace remoting {

namespace {

// Name of command-line flag to disable use of I444 by default.
const char kDisableI444SwitchName[] = "disable-i444";

scoped_ptr<AudioEncoder> CreateAudioEncoder(
    const protocol::SessionConfig& config) {
  const protocol::ChannelConfig& audio_config = config.audio_config();

  if (audio_config.codec == protocol::ChannelConfig::CODEC_VERBATIM) {
    return make_scoped_ptr(new AudioEncoderVerbatim());
  } else if (audio_config.codec == protocol::ChannelConfig::CODEC_OPUS) {
    return make_scoped_ptr(new AudioEncoderOpus());
  }

  NOTREACHED();
  return nullptr;
}

}  // namespace

ClientSession::ClientSession(
    EventHandler* event_handler,
    scoped_refptr<base::SingleThreadTaskRunner> audio_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> input_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> video_capture_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> video_encode_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
    scoped_ptr<protocol::ConnectionToClient> connection,
    DesktopEnvironmentFactory* desktop_environment_factory,
    const base::TimeDelta& max_duration,
    scoped_refptr<protocol::PairingRegistry> pairing_registry,
    const std::vector<HostExtension*>& extensions)
    : event_handler_(event_handler),
      connection_(connection.Pass()),
      client_jid_(connection_->session()->jid()),
      desktop_environment_factory_(desktop_environment_factory),
      input_tracker_(&host_input_filter_),
      remote_input_filter_(&input_tracker_),
      mouse_clamping_filter_(&remote_input_filter_),
      disable_input_filter_(&mouse_clamping_filter_),
      disable_clipboard_filter_(clipboard_echo_filter_.host_filter()),
      client_clipboard_factory_(clipboard_echo_filter_.client_filter()),
      max_duration_(max_duration),
      audio_task_runner_(audio_task_runner),
      input_task_runner_(input_task_runner),
      video_capture_task_runner_(video_capture_task_runner),
      video_encode_task_runner_(video_encode_task_runner),
      network_task_runner_(network_task_runner),
      ui_task_runner_(ui_task_runner),
      pairing_registry_(pairing_registry),
      is_authenticated_(false),
      pause_video_(false),
      lossless_video_encode_(false),
      // Note that |lossless_video_color_| defaults to true, but actually only
      // controls VP9 video stream color quality.
      lossless_video_color_(!base::CommandLine::ForCurrentProcess()->HasSwitch(
          kDisableI444SwitchName)),
      weak_factory_(this) {
  connection_->SetEventHandler(this);

  // Create a manager for the configured extensions, if any.
  extension_manager_.reset(new HostExtensionSessionManager(extensions, this));

#if defined(OS_WIN)
  // LocalInputMonitorWin filters out an echo of the injected input before it
  // reaches |remote_input_filter_|.
  remote_input_filter_.SetExpectLocalEcho(false);
#endif  // defined(OS_WIN)
}

ClientSession::~ClientSession() {
  DCHECK(CalledOnValidThread());
  DCHECK(!audio_pump_);
  DCHECK(!desktop_environment_);
  DCHECK(!input_injector_);
  DCHECK(!screen_controls_);
  DCHECK(!video_stream_);

  connection_.reset();
}

void ClientSession::NotifyClientResolution(
    const protocol::ClientResolution& resolution) {
  DCHECK(CalledOnValidThread());

  // TODO(sergeyu): Move these checks to protocol layer.
  if (!resolution.has_dips_width() || !resolution.has_dips_height() ||
      resolution.dips_width() < 0 || resolution.dips_height() < 0 ||
      resolution.width() <= 0 || resolution.height() <= 0) {
    LOG(ERROR) << "Received invalid ClientResolution message.";
    return;
  }

  VLOG(1) << "Received ClientResolution (dips_width="
          << resolution.dips_width() << ", dips_height="
          << resolution.dips_height() << ")";

  if (!screen_controls_)
    return;

  ScreenResolution client_resolution(
      webrtc::DesktopSize(resolution.dips_width(), resolution.dips_height()),
      webrtc::DesktopVector(kDefaultDPI, kDefaultDPI));

  // Try to match the client's resolution.
  screen_controls_->SetScreenResolution(client_resolution);
}

void ClientSession::ControlVideo(const protocol::VideoControl& video_control) {
  DCHECK(CalledOnValidThread());

  // Note that |video_stream_| may be null, depending upon whether
  // extensions choose to wrap or "steal" the video capturer or encoder.
  if (video_control.has_enable()) {
    VLOG(1) << "Received VideoControl (enable="
            << video_control.enable() << ")";
    pause_video_ = !video_control.enable();
    if (video_stream_)
      video_stream_->Pause(pause_video_);
  }
  if (video_control.has_lossless_encode()) {
    VLOG(1) << "Received VideoControl (lossless_encode="
            << video_control.lossless_encode() << ")";
    lossless_video_encode_ = video_control.lossless_encode();
    if (video_stream_)
      video_stream_->SetLosslessEncode(lossless_video_encode_);
  }
  if (video_control.has_lossless_color()) {
    VLOG(1) << "Received VideoControl (lossless_color="
            << video_control.lossless_color() << ")";
    lossless_video_color_ = video_control.lossless_color();
    if (video_stream_)
      video_stream_->SetLosslessColor(lossless_video_color_);
  }
}

void ClientSession::ControlAudio(const protocol::AudioControl& audio_control) {
  DCHECK(CalledOnValidThread());

  if (audio_control.has_enable()) {
    VLOG(1) << "Received AudioControl (enable="
            << audio_control.enable() << ")";
    if (audio_pump_)
      audio_pump_->Pause(!audio_control.enable());
  }
}

void ClientSession::SetCapabilities(
    const protocol::Capabilities& capabilities) {
  DCHECK(CalledOnValidThread());

  // Ignore all the messages but the 1st one.
  if (client_capabilities_) {
    LOG(WARNING) << "protocol::Capabilities has been received already.";
    return;
  }

  // Compute the set of capabilities supported by both client and host.
  client_capabilities_ = make_scoped_ptr(new std::string());
  if (capabilities.has_capabilities())
    *client_capabilities_ = capabilities.capabilities();
  capabilities_ = IntersectCapabilities(*client_capabilities_,
                                        host_capabilities_);
  extension_manager_->OnNegotiatedCapabilities(
      connection_->client_stub(), capabilities_);

  VLOG(1) << "Client capabilities: " << *client_capabilities_;

  // Calculate the set of capabilities enabled by both client and host and
  // pass it to the desktop environment if it is available.
  desktop_environment_->SetCapabilities(capabilities_);
}

void ClientSession::RequestPairing(
    const protocol::PairingRequest& pairing_request) {
  if (pairing_registry_.get() && pairing_request.has_client_name()) {
    protocol::PairingRegistry::Pairing pairing =
        pairing_registry_->CreatePairing(pairing_request.client_name());
    protocol::PairingResponse pairing_response;
    pairing_response.set_client_id(pairing.client_id());
    pairing_response.set_shared_secret(pairing.shared_secret());
    connection_->client_stub()->SetPairingResponse(pairing_response);
  }
}

void ClientSession::DeliverClientMessage(
    const protocol::ExtensionMessage& message) {
  if (message.has_type()) {
    if (message.type() == "test-echo") {
      protocol::ExtensionMessage reply;
      reply.set_type("test-echo-reply");
      if (message.has_data())
        reply.set_data(message.data().substr(0, 16));
      connection_->client_stub()->DeliverHostMessage(reply);
      return;
    } else if (message.type() == "gnubby-auth") {
      if (gnubby_auth_handler_) {
        gnubby_auth_handler_->DeliverClientMessage(message.data());
      } else {
        HOST_LOG << "gnubby auth is not enabled";
      }
      return;
    } else {
      if (extension_manager_->OnExtensionMessage(message))
        return;

      DLOG(INFO) << "Unexpected message received: "
                 << message.type() << ": " << message.data();
    }
  }
}

void ClientSession::OnConnectionAuthenticating(
    protocol::ConnectionToClient* connection) {
  event_handler_->OnSessionAuthenticating(this);
}

void ClientSession::OnConnectionAuthenticated(
    protocol::ConnectionToClient* connection) {
  DCHECK(CalledOnValidThread());
  DCHECK_EQ(connection_.get(), connection);
  DCHECK(!audio_pump_);
  DCHECK(!desktop_environment_);
  DCHECK(!input_injector_);
  DCHECK(!screen_controls_);
  DCHECK(!video_stream_);

  is_authenticated_ = true;

  if (max_duration_ > base::TimeDelta()) {
    max_duration_timer_.Start(
        FROM_HERE, max_duration_,
        base::Bind(&ClientSession::DisconnectSession, base::Unretained(this),
                   protocol::MAX_SESSION_LENGTH));
  }

  // Notify EventHandler.
  event_handler_->OnSessionAuthenticated(this);

  // Create the desktop environment. Drop the connection if it could not be
  // created for any reason (for instance the curtain could not initialize).
  desktop_environment_ =
      desktop_environment_factory_->Create(weak_factory_.GetWeakPtr());
  if (!desktop_environment_) {
    DisconnectSession(protocol::HOST_CONFIGURATION_ERROR);
    return;
  }

  // Connect host stub.
  connection_->set_host_stub(this);

  // Collate the set of capabilities to offer the client, if it supports them.
  host_capabilities_ = desktop_environment_->GetCapabilities();
  if (!host_capabilities_.empty())
    host_capabilities_.append(" ");
  host_capabilities_.append(extension_manager_->GetCapabilities());

  // Create the object that controls the screen resolution.
  screen_controls_ = desktop_environment_->CreateScreenControls();

  // Create the event executor.
  input_injector_ = desktop_environment_->CreateInputInjector();

  // Connect the host input stubs.
  connection_->set_input_stub(&disable_input_filter_);
  host_input_filter_.set_input_stub(input_injector_.get());

  // Connect the clipboard stubs.
  connection_->set_clipboard_stub(&disable_clipboard_filter_);
  clipboard_echo_filter_.set_host_stub(input_injector_.get());
  clipboard_echo_filter_.set_client_stub(connection_->client_stub());

  // Create a GnubbyAuthHandler to proxy gnubbyd messages.
  gnubby_auth_handler_ = desktop_environment_->CreateGnubbyAuthHandler(
      connection_->client_stub());
}

void ClientSession::OnConnectionChannelsConnected(
    protocol::ConnectionToClient* connection) {
  DCHECK(CalledOnValidThread());
  DCHECK_EQ(connection_.get(), connection);

  // Negotiate capabilities with the client.
  VLOG(1) << "Host capabilities: " << host_capabilities_;
  protocol::Capabilities capabilities;
  capabilities.set_capabilities(host_capabilities_);
  connection_->client_stub()->SetCapabilities(capabilities);

  // Start the event executor.
  input_injector_->Start(CreateClipboardProxy());
  SetDisableInputs(false);

  // Start recording video.
  ResetVideoPipeline();

  // Create an AudioPump if audio is enabled, to pump audio samples.
  if (connection_->session()->config().is_audio_enabled()) {
    scoped_ptr<AudioEncoder> audio_encoder =
        CreateAudioEncoder(connection_->session()->config());
    audio_pump_.reset(new AudioPump(
        audio_task_runner_, desktop_environment_->CreateAudioCapturer(),
        audio_encoder.Pass(), connection_->audio_stub()));
  }

  // Notify the event handler that all our channels are now connected.
  event_handler_->OnSessionChannelsConnected(this);
}

void ClientSession::OnConnectionClosed(
    protocol::ConnectionToClient* connection,
    protocol::ErrorCode error) {
  DCHECK(CalledOnValidThread());
  DCHECK_EQ(connection_.get(), connection);

  HOST_LOG << "Client disconnected: " << client_jid_ << "; error = " << error;

  // Ignore any further callbacks.
  weak_factory_.InvalidateWeakPtrs();

  // If the client never authenticated then the session failed.
  if (!is_authenticated_)
    event_handler_->OnSessionAuthenticationFailed(this);

  // Ensure that any pressed keys or buttons are released.
  input_tracker_.ReleaseAll();

  // Stop components access the client, audio or video stubs, which are no
  // longer valid once ConnectionToClient calls OnConnectionClosed().
  audio_pump_.reset();
  video_stream_.reset();
  mouse_shape_pump_.reset();
  client_clipboard_factory_.InvalidateWeakPtrs();
  input_injector_.reset();
  screen_controls_.reset();
  desktop_environment_.reset();

  // Notify the ChromotingHost that this client is disconnected.
  event_handler_->OnSessionClosed(this);
}

void ClientSession::OnCreateVideoEncoder(scoped_ptr<VideoEncoder>* encoder) {
  DCHECK(CalledOnValidThread());
  extension_manager_->OnCreateVideoEncoder(encoder);
}

void ClientSession::OnInputEventReceived(
    protocol::ConnectionToClient* connection,
    int64_t event_timestamp) {
  DCHECK(CalledOnValidThread());
  DCHECK_EQ(connection_.get(), connection);

  if (video_stream_.get())
    video_stream_->OnInputEventReceived(event_timestamp);
}

void ClientSession::OnRouteChange(
    protocol::ConnectionToClient* connection,
    const std::string& channel_name,
    const protocol::TransportRoute& route) {
  DCHECK(CalledOnValidThread());
  DCHECK_EQ(connection_.get(), connection);
  event_handler_->OnSessionRouteChange(this, channel_name, route);
}

const std::string& ClientSession::client_jid() const {
  return client_jid_;
}

void ClientSession::DisconnectSession(protocol::ErrorCode error) {
  DCHECK(CalledOnValidThread());
  DCHECK(connection_.get());

  max_duration_timer_.Stop();

  // This triggers OnConnectionClosed(), and the session may be destroyed
  // as the result, so this call must be the last in this method.
  connection_->Disconnect(error);
}

void ClientSession::OnLocalMouseMoved(const webrtc::DesktopVector& position) {
  DCHECK(CalledOnValidThread());
  remote_input_filter_.LocalMouseMoved(position);
}

void ClientSession::SetDisableInputs(bool disable_inputs) {
  DCHECK(CalledOnValidThread());

  if (disable_inputs)
    input_tracker_.ReleaseAll();

  disable_input_filter_.set_enabled(!disable_inputs);
  disable_clipboard_filter_.set_enabled(!disable_inputs);
}

void ClientSession::ResetVideoPipeline() {
  DCHECK(CalledOnValidThread());

  video_stream_.reset();
  mouse_shape_pump_.reset();

  // Create VideoEncoder and DesktopCapturer to match the session's video
  // channel configuration.
  scoped_ptr<webrtc::DesktopCapturer> video_capturer =
      desktop_environment_->CreateVideoCapturer();
  extension_manager_->OnCreateVideoCapturer(&video_capturer);

  // Don't start the video stream if the extension took ownership of the
  // capturer.
  if (!video_capturer)
    return;

  // Create MouseShapePump to send mouse cursor shape.
  mouse_shape_pump_.reset(
      new MouseShapePump(video_capture_task_runner_,
                         desktop_environment_->CreateMouseCursorMonitor(),
                         connection_->client_stub()));

  // Create a VideoStream to pump frames from the capturer to the client.

  // TODO(sergeyu): Move DesktopCapturerProxy creation to DesktopEnvironment.
  // When using IpcDesktopCapturer the capture thread is not useful.
  scoped_ptr<webrtc::DesktopCapturer> capturer_proxy(new DesktopCapturerProxy(
      video_capture_task_runner_, video_capturer.Pass()));

  video_stream_ = connection_->StartVideoStream(capturer_proxy.Pass());
  video_stream_->SetSizeCallback(
      base::Bind(&ClientSession::OnScreenSizeChanged, base::Unretained(this)));

  // Apply video-control parameters to the new stream.
  video_stream_->SetLosslessEncode(lossless_video_encode_);
  video_stream_->SetLosslessColor(lossless_video_color_);

  // Pause capturing if necessary.
  video_stream_->Pause(pause_video_);
}

void ClientSession::SetGnubbyAuthHandlerForTesting(
    GnubbyAuthHandler* gnubby_auth_handler) {
  DCHECK(CalledOnValidThread());
  gnubby_auth_handler_.reset(gnubby_auth_handler);
}

scoped_ptr<protocol::ClipboardStub> ClientSession::CreateClipboardProxy() {
  DCHECK(CalledOnValidThread());

  return make_scoped_ptr(
      new protocol::ClipboardThreadProxy(client_clipboard_factory_.GetWeakPtr(),
                                         base::ThreadTaskRunnerHandle::Get()));
}

void ClientSession::OnScreenSizeChanged(const webrtc::DesktopSize& size) {
  DCHECK(CalledOnValidThread());
  mouse_clamping_filter_.set_input_size(size);
  mouse_clamping_filter_.set_output_size(size);
}

}  // namespace remoting


text:
package main.java.com.github.shiraji.createintentinspection.inspection;

import javax.swing.*;

public class InspectionOptionPanel {
    JPanel panel;
    JTextField methodNameTextField;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>eu.scape-project</groupId>
        <artifactId>arc-unpacker-parent</artifactId>
        <version>0.5.1-SNAPSHOT</version>
    </parent>

    <artifactId>arc-unpacker-mapreduce</artifactId>

    <repositories>
        <!--Is this still nessessary?-->
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>eu.scape-project</groupId>
            <artifactId>arc-unpacker-common</artifactId>
            <version>0.5.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>0.23.6</version>
            <scope>provided</scope>
        </dependency>

<!--
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>0.20.1</version>
            <scope>provided</scope>
        </dependency>
-->

    </dependencies>

</project>


text:
namespace Sitecore.Feature.Blog.CMS.Contexts
{
    using System;
    using Glass.Mapper.Sc;
    using Sitecore.Analytics;
    using Sitecore.Sites;

    public class DefaultContext : SitecoreContext, IContext
    {
        public Guid CurrentItemId
        {
            get { return Context.Item.ID.Guid; }
        }

        public string Language
        {
            get { return Context.Language.Name; }
        }

        public string SiteStartPath
        {
            get { return Context.Site.StartPath; }
        }

    }
}


text:
.. _sec-tutorial:

=========
Tutorials
=========

Here we provide some tutorials on how to use M-LOOP. M-LOOP is flexible and can be customized with a variety of :ref:`options <sec-examples>` and :ref:`interfaces <sec-interfaces>`. Here we provide some basic tutorials to get you up and started as quick as possible.

There are two different approaches to using M-LOOP:

1. You can execute M-LOOP from a command line (or shell) and configure it using a text file.
2. You can use M-LOOP as a :ref:`python API <sec-api>`.

If you have a standard experiment, that is operated by LabVIEW, Simulink or some other method, then you should use option 1 and follow the :ref:`first tutorial <sec-standard-experiment>`. If your experiment is operated using python, you should consider using option 2 as it will give you more flexibility and control, in which case, look at the :ref:`second tutorial <sec-python-experiment>`.

.. _sec-standard-experiment:

Standard experiment
===================

The basic operation of M-LOOP is sketched below.

.. _fig-mloop-diag:

.. figure:: _static/M-LOOP_diagram.png
   :alt: M-LOOP in a loop with an experiment sending parameters and receiving costs.

There are three stages:

1. M-LOOP is started with the command::

      M-LOOP

   M-LOOP first looks for the configuration file *exp_input.txt*, which contains options like the number of parameters and their limits, in the folder it is executed, then starts the optimization process.

2. M-LOOP controls and optimizes the experiment by exchanging files written to disk. M-LOOP produces a file called *exp_input.txt* which contains a variable params with the next parameters to be run by the experiment. The experiment is expected to run an experiment with these parameters and measure the resultant cost. The experiment should then write the file *exp_output.txt* which contains at least the variable cost which quantifies the performance of that experimental run, and optionally, the variables uncer (for uncertainty) and bad (if the run failed). This process is repeated many times until the halting condition is met.

3. Once the optimization process is complete, M-LOOP prints to the console the parameters and cost of the best run performed during the experiment, and a prediction of what the optimal parameters (with the corresponding predicted cost and uncertainty). M-LOOP also produces a set of plots that allow the user to visualize the optimization process and cost landscape. During operation and at the end M-LOOP write three files to disk:

   - *M-LOOP_[datetime].log* a log of the console output and other debugging information during the run.
   - *controller_archive_[datetime].txt* an archive of all the experimental data recorded and the results.
   - *learner_archive_[datetime].txt* an archive of the model created by the machine learner of the experiment.

In what follows we will unpack this process and give details on how to configure and run M-LOOP.

Launching M-LOOP
----------------

Launching M-LOOP is performed by executing the command M-LOOP on the console. You can also provide the name of your configuration file if you do not want to use the default with the command::

   M-LOOP -c [config_filename]

.. _sec-configuration-file:

Configuration File
------------------

The configuration file contains a list of options and settings for the optimization run. Each option must be started on a new line and formatted as::

   [keyword] = [value]

You can add comments to your file using #, everything past # will be ignored. Examples of relevant keywords and syntax for the values is provided in :ref:`sec-examples` and a comprehensive list of options is described in :ref:`sec-examples`. The values should be formatted with python syntax, strings should be surrounded with single or double quotes and arrays of values can be surrounded with square brackets/parentheses with numbers separated with commas. In this tutorial we will examine the example file *tutoral_config.txt*::

   #Tutorial Config
   #---------------

   #Parameter settings
   num_params = 2                #number of parameters
   min_boundary = [-1,-1]        #minimum boundary
   max_boundary = [1,1]          #maximum boundary
   first_params = [0.5,0.5]      #first parameters to try
   trust_region = 0.4         	#maximum % move distance from best params

   #Halting conditions
   max_num_runs = 1000                       #maximum number of runs
   max_num_runs_without_better_params = 50   #maximum number of runs without finding better parameters
   target_cost = 0.01                        #optimization halts when a cost below this target is found

   #Learner options
   cost_has_noise = True      #whether the cost are corrupted by noise or not

   #Timing options
   no_delay = True            #wait for learner to make generate new parameters or use training algorithms

   #File format options
   interface_file_type = 'txt'            #file types of *exp_input.mat* and *exp_output.mat*
   controller_archive_file_type = 'mat'   #file type of the controller archive
   learner_archive_file_type = 'pkl'      #file type of the learner archive

   #Visualizations
   visualizations = True

We will now explain the options in each of their groups. In almost all cases you will only need to the parameters settings and halting conditions, but we have also described a few of the most commonly used extra options.

Parameter settings
~~~~~~~~~~~~~~~~~~

The number of parameters and their limits is defined with three keywords::

   num_params = 2
   min_boundary = [-1,-1]
   max_boundary = [1,1]

num_params defines the number of parameters, min_boundary defines the minimum value each of the parameters can take and max_boundary defines the maximum value each parameter can take. Here there are two value which each must be between -1 and 1.

first_parameters defines the first parameters the learner will try. You only need to set this if you have a safe set of parameters you want the experiment to start with. Just delete this keyword if any set of parameters in the boundaries will work.

trust_region defines the maximum change allowed in the parameters from the best parameters found so far. In the current example the region size is 2 by 2, with a trust region of 40% thus the maximum allowed change for the second run will be [0 +/- 0.8, 0 +/- 0.8]. This is only needed if your experiment produces bad results when the parameters are changes significantly between runs. Simply delete this keyword if your experiment works with any set of parameters within the boundaries.

Halting conditions
~~~~~~~~~~~~~~~~~~

The halting conditions define when the simulation will stop. We present three options here::

   max_num_runs = 100
   max_num_runs_without_better_params = 10
   target_cost = 0.1
   first_params = [0.5,0.5]
   trust_region = 0.4

max_num_runs is the maximum number of runs that the optimization algorithm is allowed to run. max_num_runs_without_better_params is the maximum number of runs allowed before a lower cost and better parameters is found. Finally, when target_cost is set, if a run produces a cost that is less than this value the optimization process will stop.

When multiple halting conditions are set, the optimization process will halt when any one of them is met.

If you do not have any prior knowledge of the problem use only the keyword max_num_runs and set it to the highest value you can wait for. If you have some knowledge about what the minimum attainable cost is or there is some cost threshold you need to achieve, you might want to set the target_cost. max_num_runs_without_better_params is useful if you want to let the optimization algorithm run as long as it needs until there is a good chance the global optimum has been found.

If you do not want one of the halting conditions, simply delete it from your file. For example if you just wanted the algorithm to search as long as it can until it found a global minimum you could set::

   max_num_runs_without_better_params = 10

Learner Options
~~~~~~~~~~~~~~~

There are many learner specific options (and different learner algorithms) described in :ref:`sec-examples`. Here we just present a common one::

   cost_has_noise = True

If the cost you provide has noise in it, meaning your the cost you calculate would fluctuate if you did multiple experiments with the same parameters, then set this flag to True. If the costs your provide have no noise then set this flag to False. M-LOOP will automatically determine if the costs have noise in them or not, so if you are unsure, just delete this keyword and it will use the default value of True.

Timing options
~~~~~~~~~~~~~~

M-LOOP learns how the experiment works by fitting the parameters and costs using a gaussian process. This learning process can take some time. If M-LOOP is asked for new parameters before it has time to generate a new prediction, it will use the training algorithm to provide a new set of parameters to test. This allows for an experiment to be run while the learner is still thinking. The training algorithm by default is differential evolution, this algorithm is also used to do the first initial set of experiments which are then used to train M-LOOP. If you would prefer M-LOOP waits for the learner to come up with its best prediction before running another experiment you can change this behavior with the option::

   no_delay = True

Set no_delay to true to ensure there is no pauses between experiments and set it to false if you to give M-LOOP to have the time to come up with its most informed choice. Sometimes doing fewer more intelligent experiments will lead to an optimal quicker than many quick unintelligent experiments. You can delete the keyword if you are unsure and it will default to True.

File format options
~~~~~~~~~~~~~~~~~~~

You can set the file formats for the archives produced at the end and the files exchanged with the experiment with the options::

   interface_file_type = 'txt'
   controller_archive_file_type = 'mat'
   learner_archive_file_type = 'pkl'

interface_file_type controls the file format for the files exchanged with the experiment. controller_archive_file_type and learner_archive_file_type control the format of the respective archives.

There are three file formats currently available: 'mat' is for MATLAB readable files, 'pkl' if for python binary archives created using the `pickle package <https://docs.python.org/3/library/pickle.html>`_, and 'txt' human readable text files. For more details on these formats see :ref:`sec-data`.

Visualization
~~~~~~~~~~~~~

By default M-LOOP will display a set of plots that allow the user to visualize the optimization process and the cost landscape. To change this behavior use the option::

   visualizations = True

Set it to false to turn the visualizations off. For more details see :ref:`sec-visualizations`.

Interface
---------

There are many options of how to connect M-LOOP to your experiment. We consider the most generic method, writing and reading files to disk. For other options see :ref:`sec-interfaces`. If you design a bespoke interface for your experiment please consider :ref:`sec-contributing` to the project by sharing your method with other users.

The file interface works under the assumption that you experiment follows the following algorithm.

1. Wait for the file *exp_input.txt* to be made on the disk in the same folder M-LOOP is run.
2. Read the parameters for the next experiment from the file (named params).
3. Delete the file  *exp_input.txt*.
4. Run the experiment with the parameters provided and calculate a cost, and optionally the uncertainty.
5. Write the cost to the file *exp_output.txt*. Go back to step 1.

It is important you delete the file *exp_input.txt* after reading it, since it is used to as an indicator for the next experiment to run.

When writing the file *exp_output.txt* there are three keywords and values you can include in your file, for example after the first run your experiment may produce the following::

   cost = 0.5
   uncer = 0.01
   bad = false

cost refers to the cost calculated from the experimental data. uncer, is optional, and refers to the uncertainty in the cost measurement made. Note, M-LOOP by default assumes there is some noise corrupting costs, which is fitted and compensated for. Hence, if there is some noise in your costs which you are unable to predict from a single measurement, do not worry, you do not have to estimate uncer, you can just leave it out. Lastly bad can be used to indicate an experiment failed and was not able to produce a cost. If the experiment worked set bad = false and if it failed set bad = true.

Note you do not have to include all of the keywords, you must provide at least a cost or the bad keyword set to true. For example a successful run can simply be::

   cost = 0.3

and failed experiment can be as simple as::

   bad = True

Once the *exp_output.txt* has been written to disk, M-LOOP will read it and delete it.

Parameters and cost function
----------------------------

Choosing the right parameterization of your experiment and cost function will be an important part of getting great results.

If you have time dependent functions in your experiment you will need to choose a parametrization of these function before interfacing them with M-LOOP. M-LOOP will take more time and experiments to find an optimum, given more parameters. But if you provide too few parameters, you may not be able to achieve your cost target.

Fortunately, the visualizations provided after the optimization will help you determine which parameters contributed the most to the optimization process. Try with whatever parameterization is convenient to start and use the data produced afterwards to guide you on how to better improve the parametrization of your experiment.

Picking the right cost function from experimental observables will also be important. M-LOOP will always find a global optimal as quick as it can, but if you have a poorly chosen cost function, the global optimal may not what you really wanted to optimize. Make sure you pick a cost function that will uniquely produce the result you want. Again, do not be afraid to experiment and use the data produced by the optimization runs to improve the cost function you are using.

Have a look at our `paper <http://www.nature.com/articles/srep25890>`_ on using M-LOOP to create a Bose-Einstein Condensate for an example of choosing a parametrization and cost function for an experiment.

.. _sec-results:

Results
-------

Once M-LOOP has completed the optimization, it will output results in several ways.

M-LOOP will print results to the console. It will give the parameters of the experimental run that produced the lowest cost. It will also provide a set of parameters which are predicted to be produce the lowest average cost. If there is no noise in the costs your experiment produced, then the best parameters and predicted best parameters will be the same. If there was some noise your costs then it is possible that there will be a difference between the two. This is because the noise might have resulted with a set of experimental parameters that produced a lower cost due to a random fluke. The real optimal parameters that correspond to the minimum average cost are the predicted best parameters. In general, use the predicted best parameters (when provided) as the final result of the experiment.

M-LOOP will produce an archive for the controller and machine learner. The controller archive contains all the data gathered during the experimental run and also other configuration details set by the user. By default it will be a 'txt' file which is human readable. If the meaning of a keyword and its associated data in the file is unclear, just :ref:`search` the documentation with the keyword to find a description. The learner archive contains a model of the experiment produced by the machine learner algorithm, which is currently a gaussian process. By default it will also be a 'txt' file. For more detail on these files see :ref:`sec-data`.

M-LOOP, by default, will produce a set of visualizations. These plots show the optimizations process over time and also predictions made by the learner of the cost landscape. For more details on these visualizations and their interpretation see :ref:`sec-visualizations`.

.. _sec-python-experiment:

Python controlled experiment
============================

If you have an experiment that is already under python control you can use M-LOOP as an API. Below we go over the example python script *python_controlled_experiment.py* you should also read over the :ref:`first tutorial <sec-standard-experiment>` to get a general idea of how M-LOOP works.

When integrating M-LOOP into your laboratory remember that it will be controlling you experiment, not vice versa. Hence, at the top level of your python script you will execute M-LOOP which will then call on your experiment when needed. Your experiment will not be making calls of M-LOOP.

An example script for a python controlled experiment is given in the examples folder called *python_controlled_experiment.py*, which is copied below::

	#Imports for python 2 compatibility
	from __future__ import absolute_import, division, print_function
	__metaclass__ = type

	#Imports for M-LOOP
	import mloop.interfaces as mli
	import mloop.controllers as mlc
	import mloop.visualizations as mlv

	#Other imports
	import numpy as np
	import time

	#Declare your custom class that inherits from the Interface class
	class CustomInterface(mli.Interface):

		#Initialization of the interface, including this method is optional
		def __init__(self):
			#You must include the super command to call the parent class, Interface, constructor
			super(CustomInterface,self).__init__()

			#Attributes of the interface can be added here
			#If you want to pre-calculate any variables etc. this is the place to do it
			#In this example we will just define the location of the minimum
			self.minimum_params = np.array([0,0.1,-0.1])

		#You must include the get_next_cost_dict method in your class
		#this method is called whenever M-LOOP wants to run an experiment
		def get_next_cost_dict(self,params_dict):

			#Get parameters from the provided dictionary
			params = params_dict['params']

			#Here you can include the code to run your experiment given a particular set of parameters
			#In this example we will just evaluate a sum of sinc functions
			cost = -np.sum(np.sinc(params - self.minimum_params))
			#There is no uncertainty in our result
			uncer = 0
			#The evaluation will always be a success
			bad = False
			#Add a small time delay to mimic a real experiment
			time.sleep(1)

			#The cost, uncertainty and bad boolean must all be returned as a dictionary
			#You can include other variables you want to record as well if you want
			cost_dict = {'cost':cost, 'uncer':uncer, 'bad':bad}
			return cost_dict

	def main():
		#M-LOOP can be run with three commands

		#First create your interface
		interface = CustomInterface()
		#Next create the controller, provide it with your controller and any options you want to set
		controller = mlc.create_controller(interface, max_num_runs = 1000, target_cost = -2.99, num_params = 3, min_boundary = [-2,-2,-2], max_boundary = [2,2,2])
		#To run M-LOOP and find the optimal parameters just use the controller method optimize
		controller.optimize()

		#The results of the optimization will be saved to files and can also be accessed as attributes of the controller.
		print('Best parameters found:')
		print(controller.best_params)

		#You can also run the default sets of visualizations for the controller with one command
		mlv.show_all_default_visualizations(controller)

	#Ensures main is run when this code is run as a script
	if __name__ == '__main__':
		main()

Each part of the code is explained in the following sections.

Imports
-------

The start of the script imports the libraries that are necessary for M-LOOP to work::

	#Imports for python 2 compatibility
	from __future__ import absolute_import, division, print_function
	__metaclass__ = type

	#Imports for M-LOOP
	import mloop.interfaces as mli
	import mloop.controllers as mlc
	import mloop.visualizations as mlv

	#Other imports
	import numpy as np
	import time

The first group of imports are just for python 2 compatibility. M-LOOP is targeted at python3, but has been designed to be bilingual. These imports ensure backward compatibility.

The second group of imports are the most important modules M-LOOP needs to run. The interfaces and controllers modules are essential, while the visualizations module is only needed if you want to view your data afterwards.

Lastly, you can add any other imports you may need.

Custom Interface
----------------

M-LOOP takes an object oriented approach to controlling the experiment. This is different than the functional approach taken by other optimization packages, like scipy. When using M-LOOP you must make your own class that inherits from the Interface class in M-LOOP. This class must implement a method called *get_next_cost_dict* that takes a set of parameters, runs your experiment and then returns the appropriate cost and uncertainty.

An example of the simplest implementation of a custom interface is provided below ::

	#Declare your custom class that inherits from the Interface class
	class SimpleInterface(mli.Interface):

		#the method that runs the experiment given a set of parameters and returns a cost
		def get_next_cost_dict(self,params_dict):

			#The parameters come in a dictionary and are provided in a numpy array
			params = params_dict['params']pre-calculate

			#Here you can include the code to run your experiment given a particular set of parameters
			#For this example we just evaluate a simple function
			cost = np.sum(params**2)
			uncer = 0
			bad = False

			#The cost, uncertainty and bad boolean must all be returned as a dictionary
			cost_dict = {'cost':cost, 'uncer':uncer, 'bad':bad}
			return cost_dict

The code above defines a new class that inherits from the Interface class in M-LOOP. Note this code is different to the example above, we will consider this later. It is slightly more complicated than just defining a method, however there is a lot more flexibility when taking this approach. You should put the code you use to run your experiment in the *get_next_cost_dict* method. This method is executed by the interface whenever M-LOOP wants a cost corresponding to a set of parameters.

When you actually run M-LOOP you will need to make an instance of your interface. To make an instance of the class above you would use::

	interface = SimpleInterface()

This interface is then provided to the controller, which is discussed in the next section.

Dictionaries are used for both input and output of the method, to give the user flexibility. For example, if you had a bad run, you do not have to return a cost and uncertainty, you can just return a dictionary with bad set to True::

	cost_dict = {'bad':True}
	return cost_dict

By taking an object oriented approach, M-LOOP can provide a lot more flexibility when controlling your experiment. For example if you wish to start up your experiment or perform some initial numerical analysis you can add a customized constructor or __init__ method for the class. We consider this in the main example::

	class CustomInterface(mli.Interface):

		#Initialization of the interface, including this method is optional
		def __init__(self):
			#You must include the super command to call the parent class, Interface, constructor
			super(CustomInterface,self).__init__()

			#Attributes of the interface can be added here
			#If you want to pre-calculate any variables etc. this is the place to do it
			#In this example we will just define the location of the minimum
			self.minimum_params = np.array([0,0.1,-0.1])

		#You must include the get_next_cost_dict method in your class
		#this method is called whenever M-LOOP wants to run an experiment
		def get_next_cost_dict(self,params_dict):

			#Get parameters from the provided dictionary
			params = params_dict['params']

			#Here you can include the code to run your experiment given a particular set of parameters
			#In this example we will just evaluate a sum of sinc functions
			cost = -np.sum(np.sinc(params - self.minimum_params))
			#There is no uncertainty in our result
			uncer = 0
			#The evaluation will always be a success
			bad = False
			#Add a small time delay to mimic a real experiment
			time.sleep(1)

			#The cost, uncertainty and bad boolean must all be returned as a dictionary
			#You can include other variables you want to record as well if you want
			cost_dict = {'cost':cost, 'uncer':uncer, 'bad':bad}
			return cost_dict

In this code snippet we also implement a constructor. Here we just define a numpy array which defines the minimum_parameter values. We can call this variable whenever we need in the *get_next_cost_dict method*. You can also define your own custom methods in your interface or even inherit from other classes.

Once you have implemented your own Interface running M-LOOP can be done in three lines.

Running M-LOOP
--------------

Once you have made your interface class running M-LOOP can be as simple as three lines. In the example script M-LOOP is run in the main method::

	def main():
		#M-LOOP can be run with three commands

		#First create your interface
		interface = CustomInterface()
		#Next create the controller, provide it with your controller and any options you want to set
		controller = mlc.create_controller(interface, max_num_runs = 1000, target_cost = -2.99, num_params = 3, min_boundary = [-2,-2,-2], max_boundary = [2,2,2])
		#To run M-LOOP and find the optimal parameters just use the controller method optimize
		controller.optimize()

In the code snippet we first make an instance of our custom interface class called interface. We then create an instance of a controller. The controller will run the experiment and perform the optimization. You must provide the controller with the interface and any of the M-LOOP options you would normally provide in the configuration file. In this case we give five options, which do the following:

1. *max_num_runs = 1000* sets the maximum number of runs to be 1000.
2. *target_cost = -2.99* sets a cost that M-LOOP will halt at once it has been reached.
3. *num_params = 3* sets the number of parameters to be 3.
4. *min_boundary = [-2,-2,-2]* defines the minimum values of each of the parameters.
5. *max_boundary = [2,2,2]* defines the maximum values of each of the parameters.

There are many other options you can use. Have a look at :ref:`sec-configuration-file` for a detailed introduction into all the important configuration options. Remember you can include any option you would include in a configuration file as keywords for the controller. For more options you should look at all the config files in :ref:`sec-examples`, or for a comprehensive list look at the :ref:`sec-api`.

Once you have created your interface and controller you can run M-LOOP by calling the optimize method of the controller. So in summary M-LOOP is executed in three lines::

	interface = CustomInterface()
	controller = mlc.create_controller(interface, [options])
	controller.optimize()

Results
-------

The results will be displayed on the console and also saved in a set of files. Have a read over :ref:`sec-results` for more details on the results displayed and saved. Also read :ref:`sec-data` for more details on data formats and how it is stored.

Within the python environment you can also access the results as attributes of the controller after it has finished optimization. The example includes a simple demonstration of this::

		#The results of the optimization will be saved to files and can also be accessed as attributes of the controller.
		print('Best parameters found:')
		print(controller.best_params)

All of the results saved in the controller archive can be directly accessed as attributes of the controller object. For a comprehensive list of the attributes of the controller generated after an optimization run see the :ref:`sec-api`.

Visualizations
--------------

For each controller there is normally a default set of visualizations available. The visualizations for the Gaussian Process, the default optimization algorithm, is described in :ref:`sec-visualizations`. Visualizations can be called through the visualization module. The example includes a simple demonstration of this::

		#You can also run the default sets of visualizations for the controller with one command
		mlv.show_all_default_visualizations(controller)

This code snippet will display all the visualizations available for that controller. There are many other visualization methods and options available that let you control which plots are displayed and when, see the :ref:`sec-api` for details.


text:
package com.gamefreezer.galaga.tests;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

import com.gamefreezer.galaga.FixedAnimation;

public class FixedAnimationTest {

    private FixedAnimation fanim;
    private MockGraphics graphics;
    private int[] coords = new int[] { 10, 30 };
    private int frameTime = 100;
    private int[] times = new int[] { frameTime, frameTime };
    private int maxFrames = 5;

    @Before
    public void setUp() throws Exception {
	fanim = FixedAnimation.build(Helper.buildSpriteCache(), maxFrames,
		Helper.buildAnimationSource(times), coords);
	graphics = new MockGraphics();
    }

    @Test
    public void drawUsesFixedCoordinates() {
	fanim.draw(graphics);
	assertThat("x", graphics.x, is(coords[0]));
	assertThat("y", graphics.y, is(coords[1]));
    }

    @Test
    public void resetWorks() {
	fanim.draw(graphics);
	fanim.draw(graphics);
	fanim.reset();
	assertThat("reset", fanim.isFinished(), is(false));
    }

    @Test
    public void animationFinishesAsExpected() {
	fanim.rewindFrameStart(System.currentTimeMillis() - frameTime);
	fanim.draw(graphics);
	fanim.rewindFrameStart(System.currentTimeMillis() - frameTime);
	fanim.draw(graphics);
	assertThat(fanim.isFinished(), is(true));
    }

}