text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

  <title>Flake it till you make it</title>
  <meta property="og:title" content="Flake it till you make it" />
  <meta name="twitter:title" content="Flake it till you make it" />
  <meta name="description" content="Excerpt from Soulshaping by Jeff Brown">
  <meta property="og:description" content="Excerpt from Soulshaping by Jeff Brown">
  <meta name="twitter:description" content="Excerpt from Soulshaping by Jeff Brown">
  <meta name="author" content="Isaac Zhou"/>
  <link href='http://www.primerpy.com/img/favicon.ico' rel='icon' type='image/x-icon'/>
  <meta property="og:image" content="http://www.primerpy.com/img/avatar-icon.png" />
  <meta name="twitter:image" content="http://www.primerpy.com/img/avatar-icon.png" />
  <meta name="twitter:card" content="summary" />
  <meta name="twitter:site" content="@username" />
  <meta name="twitter:creator" content="@username" />
  <meta property="og:url" content="http://www.primerpy.com/post/others/2015-02-26-flake-it-till-you-make-it/" />
  <meta property="og:type" content="website" />
  <meta property="og:site_name" content="PrimerPy" />

  <meta name="generator" content="Hugo 0.30.2" />
  <link rel="canonical" href="http://www.primerpy.com/post/others/2015-02-26-flake-it-till-you-make-it/" />
  <link rel="alternate" href="http://www.primerpy.com/index.xml" type="application/rss+xml" title="PrimerPy">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="http://www.primerpy.com/css/main.css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />
  <link rel="stylesheet" href="http://www.primerpy.com/css/pygment_highlights.css" />
  <link rel="stylesheet" href="http://www.primerpy.com/css/highlight.min.css" />

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar">
        Toggle navigation

      </button>
      PrimerPy

              Python

                  Basic Python

              Javascript

                  Advanced JS

                  D3

              R

                  Basic R

              SQL

                  SELECT

              About

              Tags

              Search

          <button type="button" class="close" data-dismiss="modal">×</button>

Search PrimerPy

          <gcse:search></gcse:search>

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Flake it till you make it

Excerpt from Soulshaping by Jeff Brown

  Posted on February 26, 2015

Flake it till you make it

Excerpt from Soulshaping by Jeff Brown

  Posted on February 26, 2015

Under what circumstances should we step off a path? When is it essential that we finish what we start? If I bought a bag of peanuts and had an allergic reaction, no one would fault me if I threw it out. If I ended a relationship with a woman who hit me, no one would say that I had a commitment problem. But if I walk away from a seemingly secure route because my soul has other ideas, I am a flake?

The truth is that no one else can definitively know the path we are here to walk. It's tempting to listen—many of us long for the omnipotent other—but unless they are genuine psychic intuitives, they can't know. All others can know is their own truth, and if they've actually done the work to excavate it, they will have the good sense to know that they cannot genuinely know anyone else's. Only soul knows the path it is here to walk. Since you are the only one living in your temple, only you can know its scriptures and interpretive structure.

At the heart of the struggle are two very different ideas of success—survival-driven and soul-driven. For survivalists, success is security, pragmatism, power over others. Success is the absence of material suffering, the nourishing of the soul be damned. It is an odd and ironic thing that most of the material power in our world often resides in the hands of younger souls. Still working in the egoic and material realms, they love the sensations of power and focus most of their energy on accumulation. Older souls tend not to be as materially driven. They have already played the worldly game in previous lives and they search for more subtle shades of meaning in this one—authentication rather than accumulation. They are often ignored by the culture at large, although they really are the truest warriors.

A soulful notion of success rests on the actualization of our innate image. Success is simply the completion of a soul step, however unsightly it may be. We have finished what we started when the lesson is learned. What a fear-based culture calls a wonderful opportunity may be fruitless and misguided for the soul. Staying in a passionless relationship may satisfy our need for comfort, but it may stifle the soul. Becoming a famous lawyer is only worthwhile if the soul demands it. It is an essential failure if you are called to be a monastic this time around. If you need to explore and abandon ten careers in order to stretch your soul toward its innate image, then so be it. Flake it till you make it.

            ← Previous Post

            Next Post →

          Isaac Zhou
           •
          2017

             •
            PrimerPy


text:
import { expect } from "chai";
import { createVueField, trigger } from "../util";

import Vue from "vue";
import FieldTextArea from "src/fields/fieldTextArea.vue";

Vue.component("FieldTextArea", FieldTextArea);

let el, vm, field;

function createField(schema = {}, model = null, disabled = false, options) {
	[ el, vm, field ] = createVueField("fieldTextArea", schema, model, disabled, options);
}

describe("fieldTextArea.vue", () => {

	describe("check template", () => {
		let schema = {
			type: "textarea",
			label: "Description",
			model: "desc",
			readonly: false,
			placeholder: "Field placeholder",
			max: 500
		};
		let model = { desc: "Lorem ipsum dolor sit amet, consectetur adipiscing elit." };
		let input;

		before( () => {
			createField(schema, model, false);
			input = el.getElementsByTagName("textarea")[0];
		});

		it("should contain a textarea element", () => {
			expect(field).to.be.exist;
			expect(field.$el).to.be.exist;

			expect(input).to.be.defined;
			expect(input.classList.contains("form-control")).to.be.true;
			expect(input.placeholder).to.be.equal(schema.placeholder);
			expect(input.readOnly).to.be.false;
			expect(input.disabled).to.be.false;
			expect(input.rows).to.be.equal(2);	// default value is 2
			expect(input.maxLength).to.be.equal(500);
		});

		it("should change rows to 4", (done) => {
			field.$set("schema.rows", 4); // To be reactive
			vm.$nextTick( () => {
				expect(input.rows).to.be.equal(4);
				done();
			});
		});

		it("should contain the value", (done) => {
			vm.$nextTick( () => {
				expect(input.value).to.be.equal(model.desc);
				done();
			});
		});

		it("should set readOnly", (done) => {
			schema.readonly = true;
			vm.$nextTick( () => {
				expect(input.readOnly).to.be.true;
				done();
			});
		});

		it("should set disabled", (done) => {
			field.disabled = true;
			vm.$nextTick( () => {
				expect(input.disabled).to.be.true;
				done();
			});
		});

		it("input value should be the model value after changed", (done) => {
			model.desc = "Jane Doe";
			vm.$nextTick( () => {
				expect(input.value).to.be.equal("Jane Doe");
				done();
			});

		});

		it("model value should be the input value if changed", (done) => {
			input.value = "John Smith";
			trigger(input, "input");

			vm.$nextTick( () => {
				expect(model.desc).to.be.equal("John Smith");
				done();
			});

		});

	});

});

redpajama_set_name: RedPajamaGithub


text:
<?php

/* default/index.html.twig */
class __TwigTemplate_147574f69154b7134298183fd04b2ff92d43027be3b8b43c5e56dae212bbcd33 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        $this->env->loadTemplate("base.html.twig")->display($context);
        // line 2
        $this->env->loadTemplate("nav.html.twig")->display($context);
        // line 3
        echo "

";
        // line 5
        $this->displayBlock('body', $context, $blocks);
        // line 10
        $this->env->loadTemplate("end.html.twig")->display($context);
    }

    // line 5
    public function block_body($context, array $blocks = array())
    {
        // line 6
        echo "

";
    }

    public function getTemplateName()
    {
        return "default/index.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  37 => 6,  34 => 5,  30 => 10,  28 => 5,  24 => 3,  22 => 2,  20 => 1,);
    }
}


text:
package software.sitb.react.utils;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import com.facebook.react.bridge.*;
import okhttp3.OkHttpClient;
import software.sitb.react.commons.DefaultReactContextBaseJavaModule;
import software.sitb.react.commons.utils.FileUtils;

/**
 * @author Sean sean.snow@live.com createAt 2017/5/12
 */
public class VersionManager extends DefaultReactContextBaseJavaModule {

  private static final String TAG = "VersionManager";

  private ReactApplicationContext context;

  public VersionManager(ReactApplicationContext reactContext) {
    super(reactContext);
    this.context = reactContext;
  }

  @Override
  public String getName() {
    return "SitbVersionManager";
  }

  @ReactMethod
  public void getPackageInfo(Promise promise) {
    try {
      PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
      WritableMap response = Arguments.createMap();
      response.putString("packageName", info.packageName);
      response.putInt("versionCode", info.versionCode);
      response.putString("versionName", info.versionName);

      promise.resolve(response);
    } catch (PackageManager.NameNotFoundException e) {
      Log.e(TAG, "获取PackageInfo信息失败", e);
      promise.reject(e);
    }

  }

  @ReactMethod
  public void installApk(ReadableMap args, final Promise promise) {
    final DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    String downloadUrl = args.getString("downloadUrl");

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));

    if (args.hasKey("title")) {
      request.setTitle(args.getString("title"));
    }

    if (args.hasKey("description")) {
      request.setDescription(args.getString("description"));
    }

    final long downloadId = downloadManager.enqueue(request);

    Log.d(TAG, "download id = " + downloadId);

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        if (completeDownloadId == downloadId) {
          Log.d(TAG, "app 下载成功");
          Uri uri = downloadManager.getUriForDownloadedFile(downloadId);
          Log.d(TAG, "SDK_INT");

          Uri apkUri;
          if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            apkUri = uri;
          } else {
            String filePath = FileUtils.getFilePathFromContentUri(context.getContentResolver(), uri);
            Log.d(TAG, "file path: " + filePath);
            apkUri = Uri.parse("file://" + filePath);
          }

          Intent installIntent = new Intent(Intent.ACTION_VIEW);
          installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
          installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(installIntent);
          context.unregisterReceiver(this);
        }
      }
    };
    context.registerReceiver(broadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
  }

}


text:
<?php

namespace blackknight467\SmartyStreetsBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SmartyStreetsBundle extends Bundle
{
}


text:
psb_compiler_center pcc;

psb_compiler_center::psb_compiler_center()
{
}

psb_compiler_center::~psb_compiler_center()
{
}
string psb_compiler_center::get_directory(string src_file)
{
	char path[512];
	strcpy_s(path,src_file.c_str());
	char* pos = strrchr(path,'\\');
	if(pos != NULL){
		pos++;
		*pos = 0;
	}else{
		_getcwd(path,sizeof(path));
		strcat_s(path,"\\");
	}
	return path;
}
string psb_compiler_center::get_res_filename(string src_file)
{
	char filename[512];
	strcpy_s(filename,src_file.c_str());

	char* p = strrchr(filename,'.');

	if(p)
	{
		*p = 0;
	}

	strcat_s(p,sizeof(filename) - (p - filename),".res.json");

	return filename;
}
bool psb_compiler_center::can_load_resource()
{
	if (!_resource.is_open())
	{
		return false;
	}
	return true;
}
bool psb_compiler_center::require_compile(string src_file, string output_file)
{
	_src_file = src_file;
	_output_file = output_file;

	_src_dir = get_directory(src_file);
	_source.open(src_file, ios::in);

	_output.open(output_file, ios::binary | ios::out | ios::trunc);

	if (!_source.is_open())
	{
		cout << "source code open failed" << endl;
		return false;
	}

	if (!_output.is_open())
	{
		cout << "output file create failed" << endl;
		return false;
	}

	_resource.open(get_res_filename(src_file), ios::in);

	if(can_load_resource())
	{
		if (!resource_reader.parse(_resource, resource_code))
		{
			cout << "resource script parse failed" << endl;
			return false;
		}
	}
	else{
		resource_code = Json::Value(Json::arrayValue);
	}
	if (!source_reader.parse(_source, source_code))
	{
		cout << "source script parse failed" << endl;
		return false;
	}

	return true;
}

bool psb_compiler_center::compile()
{
	return _compiler.cc(source_code);
}

bool psb_compiler_center::link()
{
	return _link.link(_compiler, resource_code,_src_dir);
}

bool psb_compiler_center::write_file()
{
	_output.write((const char*)_link.data(), _link.length());
	_output.flush();
	_output.close();
	return true;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.qozix.widgets</title>
<meta name="date" content="2014-02-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

com.qozix.widgets

Interfaces

AccordionView.OnAccordionEventListener

Classes

AccordionView

AccordionView.Item


text:
<?php
class Controller_Objects_Admin extends Controller_Objects {

	public function index() {
		if ($this->registry["ui"]["admin"]) {
			$this->view->setTitle("Управление объектами");

			$template = new Model_Template();
			$list = $template->getTemplates();

			$this->view->objects_admin(array("list" => $list));

			$this->view->showPage();
		}
	}
}
?>


text:
package org.jbpm.formModeler.components.editor;

import org.jbpm.formModeler.api.model.Field;
import org.jbpm.formModeler.api.model.Form;
import org.jbpm.formModeler.core.processing.formRendering.FieldI18nResourceObtainer;
import org.jbpm.formModeler.service.bb.mvc.taglib.formatter.Formatter;
import org.jbpm.formModeler.service.bb.mvc.taglib.formatter.FormatterException;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Named("AvailableTemplateElementsFormatter")
public class AvailableTemplateElementsFormatter extends Formatter {
    private static transient org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(AvailableTemplateElementsFormatter.class.getName());

    @Inject
    private FormTemplateEditor formTemplateEditor;

    @Inject
    private FieldI18nResourceObtainer fieldI18nResourceObtainer;

    public FormTemplateEditor getFormTemplateEditor() {
        return formTemplateEditor;
    }

    public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws FormatterException {
        String typeOfItems = (String) getParameter("type"); //Either Field or Label
        try {
            Form form = getFormTemplateEditor().getForm();
            List fieldsToAdd = new ArrayList();
            Set fields = form.getFormFields();
            for (Iterator iterator = fields.iterator(); iterator.hasNext();) {
                Field formularyField = (Field) iterator.next();
                fieldsToAdd.add(formularyField);
            }
            renderItemsToAdd(fieldsToAdd, typeOfItems);
        } catch (Exception e) {
            log.error("Error: ", e);
        }
    }

    protected void renderItemsToAdd(List fieldsToAdd, String type) {
        if (fieldsToAdd != null && !fieldsToAdd.isEmpty()) {
            renderFragment("outputStartItemsToAdd");
            String label="";
            for (int i = 0; i < fieldsToAdd.size(); i++) {
                Field field = (Field) fieldsToAdd.get(i);
                label = fieldI18nResourceObtainer.getFieldLabel(field);
                setAttribute("key", ("Field".equals(type) ? Form.TEMPLATE_FIELD : Form.TEMPLATE_LABEL)
                        + "{" + field.getFieldName() + "}");
                setAttribute("val",
                        field.getFieldName()
                                + (label !=null? " - " + label :"")
                );
                renderFragment("outputItemToAdd");
            }
            renderFragment("outputEndItemsToAdd");
        }
    }

}


text:
<?php
use \Bono\Helper\URL;
?>

    <a href="<?php echo URL::site($_controller->getBaseUri().'/null/create') ?>" class="button">Add

            <?php foreach ($_schema as $field): ?>
            <?php echo $field['label'] ?>
            <?php endforeach ?>

            <?php if (isset($_actions)): ?>

            <?php endif ?>

        <?php if (empty($entries)): ?>

            <td colspan="<?php echo (count($_schema) + 1) ?>" style="text-align: center">No row available

        <?php else: ?>
        <?php foreach ($entries as $key => $entry): ?>

            <?php foreach ($_schema as $field): ?>
            <?php echo $field->cell(@$entry[$field['name']]) ?>
            <?php endforeach ?>
            <?php if (isset($_actions)): ?>

                <?php foreach ($_actions as $name => $action): ?>
                    <?php echo \App\Helper\SCRUD::actionButton($name, $action, $entry) ?>
                <?php endforeach ?>

            <?php endif ?>

        <?php endforeach ?>
        <?php endif ?>


text:
A simple health check for [Supervisor](http://supervisord.org/), uses [XML-RPC API](http://supervisord.org/api.html)

## Configuration

- `SUPERVISOR_HOST` - Supervisor host
- `SUPERVISOR_PORT` - Supervisor port

## Endpoints

Default port is 8080.

- `/` - always returns 200 and "ok"
- `/health/check` opens Supervisor RPC and returns result based on running tasks

## Examples

Normal response
```json
{
  "status": true,
  "supervisor_state": {
    "state_code": 1,
    "state_name": "RUNNING"
  }
}
```

Error response:
```json
{
  "status": false,
  "supervisor_state": {
    "state_code": 1,
    "state_name": "RUNNING"
  },
  "messages": [
    "worker_1"
  ]
}
```


text:
package org.elasticsearch.client.transform.transforms;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester;

public class TransformIndexerPositionTests extends ESTestCase {

    public void testFromXContent() throws IOException {
        xContentTester(this::createParser,
                TransformIndexerPositionTests::randomTransformIndexerPosition,
                TransformIndexerPositionTests::toXContent,
                TransformIndexerPosition::fromXContent)
                .supportsUnknownFields(true)
                .randomFieldsExcludeFilter(field -> field.equals("indexer_position") ||
                    field.equals("bucket_position"))
                .test();
    }

    public static TransformIndexerPosition randomTransformIndexerPosition() {
        return new TransformIndexerPosition(randomPositionMap(), randomPositionMap());
    }

    public static void toXContent(TransformIndexerPosition position, XContentBuilder builder) throws IOException {
        builder.startObject();
        if (position.getIndexerPosition() != null) {
            builder.field("indexer_position", position.getIndexerPosition());
        }
        if (position.getBucketsPosition() != null) {
            builder.field("bucket_position", position.getBucketsPosition());
        }
        builder.endObject();
    }

    private static Map<String, Object> randomPositionMap() {
        if (randomBoolean()) {
            return null;
        }
        int numFields = randomIntBetween(1, 5);
        Map<String, Object> position = new LinkedHashMap<>();
        for (int i = 0; i < numFields; i++) {
            Object value;
            if (randomBoolean()) {
                value = randomLong();
            } else {
                value = randomAlphaOfLengthBetween(1, 10);
            }
            position.put(randomAlphaOfLengthBetween(3, 10), value);
        }
        return position;
    }
}


text:
node-sqlicipher - Asynchronous, non-blocking [SQLite3](http://www.sqlite.org/) + [SQLcipher](http://sqlcipher.net//) bindings for [Node.js](http://nodejs.org/) 0.2-0.4 (versions 2.0.x), **0.6.13+, 0.8.x, and 0.10.x** (versions 2.1.x). it's a fork of [node-sqlite3](https://github.com/mapbox/node-sqlite3) with sqlcipher library

# USAGE

``` js
var sqlite3 = require('sqlcipher').verbose();
var db = new sqlite3.Database('test.db', 'password');

db.serialize(function() {
  db.run("CREATE TABLE lorem (info TEXT)");

  var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
  for (var i = 0; i < 10; i++) {
      stmt.run("Ipsum " + i);
  }
  stmt.finalize();

  db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
      console.log(row.id + ": " + row.info);
  });
});

db.close();
```

This is in early stage but it works !!
-------------------------------------

Currently you need to have libsqlcipher.so.0.8.6 compiled and installed in your system library path !!

Will be fixed soon


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ManagedLzma.LZMA
{
    public sealed class EncoderSettings
    {
        private long mReduceSize;
        private int mDictionarySize;
        private int mLC;
        private int mLP;
        private int mPB;
        private int mFB;
        private int mHashBytes;
        private int mMC;
        private bool mFastMode;
        private bool mBinaryTreeMode;
        private bool mMultiThreaded;
        private bool mWriteEndMark;

        public EncoderSettings()
        {
            mReduceSize = Int64.MaxValue;
            mWriteEndMark = false;
            SetLevel(5);
        }

        public void SetLevel(int level)
        {
            if (level < 0 || level > 9)
                throw new ArgumentOutOfRangeException(nameof(level));

            if (level <= 5)
                mDictionarySize = (1 << (level * 2 + 14));
            else if (level == 6)
                mDictionarySize = (1 << 25);
            else
                mDictionarySize = (1 << 26);

            mLC = 3;
            mLP = 0;
            mPB = 2;
            mFastMode = (level <= 4);
            mFB = (level <= 6) ? 32 : 64;
            mBinaryTreeMode = !mFastMode;
            mHashBytes = 4;

            if (level <= 4)
                mMC = 16;
            else if (level <= 6)
                mMC = 32;
            else
                mMC = 48;

            mMultiThreaded = mBinaryTreeMode && !mFastMode;
        }

        public long ReduceSize
        {
            get { return mReduceSize; }
            set
            {
                if (value < 0)
                    throw new ArgumentOutOfRangeException(nameof(value));

                mReduceSize = value;
            }
        }

        public int DictionarySize
        {
            get { return mDictionarySize; }
            set
            {
                if (value <= 0)
                    throw new ArgumentOutOfRangeException(nameof(value));

                mDictionarySize = value;
            }
        }

        public int LC
        {
            get { return mLC; }
            set
            {
                if (value < 0 || value > 8)
                    throw new ArgumentOutOfRangeException(nameof(value));

                mLC = value;
            }
        }

        public int LP
        {
            get { return mLP; }
            set
            {
                if (value < 0 || value > 4)
                    throw new ArgumentOutOfRangeException(nameof(value));

                mLP = value;
            }
        }

        public int PB
        {
            get { return mPB; }
            set
            {
                if (value < 0 || value > 4)
                    throw new ArgumentOutOfRangeException(nameof(value));

                mPB = value;
            }
        }

        public int FB
        {
            get { return mFB; }
            set
            {
                if (value < 5 || value > 273)
                    throw new ArgumentOutOfRangeException(nameof(value));

                mFB = value;
            }
        }

        public int MC
        {
            get { return mMC; }
            set
            {
                if (value < 1 || value > (1 << 30))
                    throw new ArgumentOutOfRangeException(nameof(value));

                mMC = value;
            }
        }

        public int HashBytes
        {
            get { return mHashBytes; }
            set
            {
                if (value < 2 || value > 4)
                    throw new ArgumentOutOfRangeException(nameof(value));

                mHashBytes = value;
            }
        }

        public bool FastMode
        {
            get { return mFastMode; }
            set { mFastMode = value; }
        }

        public bool BinaryTreeMode
        {
            get { return mBinaryTreeMode; }
            set { mBinaryTreeMode = value; }
        }

        public bool MultiThreaded
        {
            get { return mMultiThreaded; }
            set { mMultiThreaded = value; }
        }

        public bool WriteEndMark
        {
            get { return mWriteEndMark; }
            set { mWriteEndMark = value; ; }
        }

        public DecoderSettings GetDecoderSettings()
        {
            return new DecoderSettings((uint)mDictionarySize, (byte)mLC, (byte)mPB, (byte)mLP);
        }

        internal Master.LZMA.CLzmaEncProps GetInternalSettings()
        {
            var settings = Master.LZMA.CLzmaEncProps.LzmaEncProps_Init();
            settings.mDictSize = (uint)mDictionarySize;
            settings.mReduceSize = mReduceSize > UInt32.MaxValue ? UInt32.MaxValue : (uint)mReduceSize;
            settings.mLC = mLC;
            settings.mLP = mLP;
            settings.mPB = mPB;
            settings.mAlgo = mFastMode ? 0 : 1;
            settings.mFB = mFB;
            settings.mBtMode = mBinaryTreeMode ? 1 : 0;
            settings.mNumHashBytes = mHashBytes;
            settings.mMC = (uint)mMC;
            settings.mWriteEndMark = mWriteEndMark ? 1u : 0u;
            settings.mNumThreads = mMultiThreaded ? 2 : 1;
            return settings;
        }

        private static void LzmaEnc_WriteProperties(Master.LZMA.CLzmaEncProps settings, ImmutableArray<byte>.Builder props)
        {
            settings.LzmaEncProps_Normalize();

            uint dictSize = settings.mDictSize;
            props.Add((byte)((settings.mPB * 5 + settings.mLP) * 9 + settings.mLC));

            for (int i = 11; i <= 30; i++)
            {
                if (dictSize <= (2u << i))
                {
                    dictSize = (2u << i);
                    break;
                }
                if (dictSize <= (3u << i))
                {
                    dictSize = (3u << i);
                    break;
                }
            }

            for (int i = 0; i < 4; i++)
                props.Add((byte)(dictSize >> (8 * i)));
        }

        internal ImmutableArray<byte> GetSerializedSettings()
        {
            var props = ImmutableArray.CreateBuilder<byte>(5);
            LzmaEnc_WriteProperties(GetInternalSettings(), props);
            return props.MoveToImmutable();
        }
    }
}


text:
title: "Event Time"
nav-id: event_time
nav-show_overview: true
nav-parent_id: streaming
nav-pos: 2
---

* toc
{:toc}

# Event Time / Processing Time / Ingestion Time

Flink supports different notions of *time* in streaming programs.

- **Processing time:** Processing time refers to the system time of the machine that is executing the
    respective operation.

    When a streaming program runs on processing time, all time-based operations (like time windows) will
    use the system clock of the machines that run the respective operator. An hourly
    processing time window will include all records that arrived at a specific operator between the
    times when the system clock indicated the full hour. For example, if an application
    begins running at 9:15am, the first hourly processing time window will include events
    processed between 9:15am and 10:00am, the next window will include events processed between 10:00am and 11:00am, and so on.

    Processing time is the simplest notion of time and requires no coordination between streams and machines.
    It provides the best performance and the lowest latency. However, in distributed and asynchronous
    environments processing time does not provide determinism, because it is susceptible to the speed at which
    records arrive in the system (for example from the message queue), to the speed at which the
    records flow between operators inside the system, and to outages (scheduled, or otherwise).

- **Event time:** Event time is the time that each individual event occurred on its producing device.
    This time is typically embedded within the records before they enter Flink, and that *event timestamp*
    can be extracted from each record. In event time, the progress of time depends on the data,
    not on any wall clocks. Event time programs must specify how to generate *Event Time Watermarks*,
    which is the mechanism that signals progress in event time. This watermarking mechanism is
    described in a later section, [below](#event-time-and-watermarks).

    In a perfect world, event time processing would yield completely consistent and deterministic results, regardless of when events arrive, or their ordering.
    However, unless the events are known to arrive in-order (by timestamp), event time processing incurs some latency while waiting for out-of-order events. As it is only possible to wait for a finite period of time, this places a limit on how deterministic event time applications can be.

    Assuming all of the data has arrived, event time operations will behave as expected, and produce correct and consistent results even when working with out-of-order or late events, or when reprocessing historic data. For example, an hourly event time window will contain all records
    that carry an event timestamp that falls into that hour, regardless of the order in which they arrive, or when they are processed. (See the section on [late events](#late-elements) for more information.)

    Note that sometimes when event time programs are processing live data in real-time, they will use some *processing time* operations in order to guarantee that they are progressing in a timely fashion.

- **Ingestion time:** Ingestion time is the time that events enter Flink. At the source operator each
    record gets the source's current time as a timestamp, and time-based operations (like time windows)
    refer to that timestamp.

    *Ingestion time* sits conceptually in between *event time* and *processing time*. Compared to
    *processing time*, it is slightly more expensive, but gives more predictable results. Because
    *ingestion time* uses stable timestamps (assigned once at the source), different window operations
    over the records will refer to the same timestamp, whereas in *processing time* each window operator
    may assign the record to a different window (based on the local system clock and any transport delay).

    Compared to *event time*, *ingestion time* programs cannot handle any out-of-order events or late data,
    but the programs don't have to specify how to generate *watermarks*.

    Internally, *ingestion time* is treated much like *event time*, but with automatic timestamp assignment and
    automatic watermark generation.

### Setting a Time Characteristic

The first part of a Flink DataStream program usually sets the base *time characteristic*. That setting
defines how data stream sources behave (for example, whether they will assign timestamps), and what notion of
time should be used by window operations like `KeyedStream.timeWindow(Time.seconds(30))`.

The following example shows a Flink program that aggregates events in hourly time windows. The behavior of the
windows adapts with the time characteristic.

{% highlight java %}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);

// alternatively:
// env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime);
// env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

DataStream<MyEvent> stream = env.addSource(new FlinkKafkaConsumer010<MyEvent>(topic, schema, props));

stream
    .keyBy( (event) -> event.getUser() )
    .timeWindow(Time.hours(1))
    .reduce( (a, b) -> a.add(b) )
    .addSink(...);
{% endhighlight %}

{% highlight scala %}
val env = StreamExecutionEnvironment.getExecutionEnvironment

env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)

// alternatively:
// env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime)
// env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

val stream: DataStream[MyEvent] = env.addSource(new FlinkKafkaConsumer010[MyEvent](topic, schema, props))

stream
    .keyBy( _.getUser )
    .timeWindow(Time.hours(1))
    .reduce( (a, b) => a.add(b) )
    .addSink(...)
{% endhighlight %}

{% highlight python %}
env = StreamExecutionEnvironment.get_execution_environment()

env.set_stream_time_characteristic(TimeCharacteristic.ProcessingTime)

# alternatively:
# env.set_stream_time_characteristic(TimeCharacteristic.IngestionTime)
# env.set_stream_time_characteristic(TimeCharacteristic.EventTime)
{% endhighlight %}

Note that in order to run this example in *event time*, the program needs to either use sources
that directly define event time for the data and emit watermarks themselves, or the program must
inject a *Timestamp Assigner & Watermark Generator* after the sources. Those functions describe how to access
the event timestamps, and what degree of out-of-orderness the event stream exhibits.

The section below describes the general mechanism behind *timestamps* and *watermarks*. For a guide on how
to use timestamp assignment and watermark generation in the Flink DataStream API, please refer to
[Generating Timestamps / Watermarks]({{ site.baseurl }}/dev/event_timestamps_watermarks.html).

# Event Time and Watermarks

*Note: Flink implements many techniques from the Dataflow Model. For a good introduction to event time and watermarks, have a look at the articles below.*

  - [Streaming 101](https://www.oreilly.com/ideas/the-world-beyond-batch-streaming-101) by Tyler Akidau
  - The [Dataflow Model paper](https://research.google.com/pubs/archive/43864.pdf)

A stream processor that supports *event time* needs a way to measure the progress of event time.
For example, a window operator that builds hourly windows needs to be notified when event time has passed beyond the
end of an hour, so that the operator can close the window in progress.

*Event time* can progress independently of *processing time* (measured by wall clocks).
For example, in one program the current *event time* of an operator may trail slightly behind the *processing time*
(accounting for a delay in receiving the events), while both proceed at the same speed.
On the other hand, another streaming program might progress through weeks of event time with only a few seconds of processing,
by fast-forwarding through some historic data already buffered in a Kafka topic (or another message queue).

------

The mechanism in Flink to measure progress in event time is **watermarks**.
Watermarks flow as part of the data stream and carry a timestamp *t*. A *Watermark(t)* declares that event time has reached time
*t* in that stream, meaning that there should be no more elements from the stream with a timestamp *t' <= t* (i.e. events with timestamps
older or equal to the watermark).

The figure below shows a stream of events with (logical) timestamps, and watermarks flowing inline. In this example the events are in order
(with respect to their timestamps), meaning that the watermarks are simply periodic markers in the stream.

Watermarks are crucial for *out-of-order* streams, as illustrated below, where the events are not ordered by their timestamps.
In general a watermark is a declaration that by that point in the stream, all events up to a certain timestamp should have arrived.
Once a watermark reaches an operator, the operator can advance its internal *event time clock* to the value of the watermark.

Note that event time is inherited by a freshly created stream element (or elements) from either the event that produced them or
from watermark that triggered creation of those elements.

## Watermarks in Parallel Streams

Watermarks are generated at, or directly after, source functions. Each parallel subtask of a source function usually
generates its watermarks independently. These watermarks define the event time at that particular parallel source.

As the watermarks flow through the streaming program, they advance the event time at the operators where they arrive. Whenever an
operator advances its event time, it generates a new watermark downstream for its successor operators.

Some operators consume multiple input streams; a union, for example, or operators following a *keyBy(...)* or *partition(...)* function.
Such an operator's current event time is the minimum of its input streams' event times. As its input streams
update their event times, so does the operator.

The figure below shows an example of events and watermarks flowing through parallel streams, and operators tracking event time.

Note that the Kafka source supports per-partition watermarking, which you can read more about [here]({{ site.baseurl }}/dev/event_timestamps_watermarks.html#timestamps-per-kafka-partition).

## Late Elements

It is possible that certain elements will violate the watermark condition, meaning that even after the *Watermark(t)* has occurred,
more elements with timestamp *t' <= t* will occur. In fact, in many real world setups, certain elements can be arbitrarily
delayed, making it impossible to specify a time by which all elements of a certain event timestamp will have occurred.
Furthermore, even if the lateness can be bounded, delaying the watermarks by too much is often not desirable, because it
causes too much delay in the evaluation of event time windows.

For this reason, streaming programs may explicitly expect some *late* elements. Late elements are elements that
arrive after the system's event time clock (as signaled by the watermarks) has already passed the time of the late element's
timestamp. See [Allowed Lateness]({{ site.baseurl }}/dev/stream/operators/windows.html#allowed-lateness) for more information on how to work
with late elements in event time windows.

## Idling sources

Currently, with pure event time watermarks generators, watermarks can not progress if there are no elements
to be processed. That means in case of gap in the incoming data, event time will not progress and for
example the window operator will not be triggered and thus existing windows will not be able to produce any
output data.

To circumvent this one can use periodic watermark assigners that don't only assign based on
element timestamps. An example solution could be an assigner that switches to using current processing time
as the time basis after not observing new events for a while.

Sources can be marked as idle using `SourceFunction.SourceContext#markAsTemporarilyIdle`. For details please refer to the Javadoc of
this method as well as `StreamStatus`.

## Debugging Watermarks

Please refer to the [Debugging Windows & Event Time]({{ site.baseurl }}/monitoring/debugging_event_time.html) section for debugging
watermarks at runtime.

## How operators are processing watermarks

As a general rule, operators are required to completely process a given watermark before forwarding it downstream. For example,
`WindowOperator` will first evaluate which windows should be fired, and only after producing all of the output triggered by
the watermark will the watermark itself be sent downstream. In other words, all elements produced due to occurrence of a watermark
will be emitted before the watermark.

The same rule applies to `TwoInputStreamOperator`. However, in this case the current watermark of the operator is defined as
the minimum of both of its inputs.

The details of this behavior are defined by the implementations of the `OneInputStreamOperator#processWatermark`,
`TwoInputStreamOperator#processWatermark1` and `TwoInputStreamOperator#processWatermark2` methods.

{% top %}


text:
package com.theo.downloader.util;

import java.io.Closeable;

public class IOUtil {

    /**
     * safe close
     *
     * @param closeable
     */
    public static void safeClose(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
using namespace testing;

namespace Nighthawk {
namespace {

using ::nighthawk::request_source::RequestSpecifier;

// The grpc client itself is tested via the python based integration tests.
// It is convenient to test message translation here.
class ProtoRequestHelperTest : public Test {
public:
  void translateExpectingEqual() {
    auto request = ProtoRequestHelper::messageToRequest(base_header_, response_);
    // We test for equality. If we observe mismatch, we use EXPECT_EQ which is guaranteed
    // to fail -- but will provide much more helpful output.
    if (!Envoy::TestUtility::headerMapEqualIgnoreOrder(expected_header_, *request->header())) {
      EXPECT_EQ(expected_header_, *request->header()) << "expected headers:\n"
                                                      << expected_header_ << "\nactual headers:\n"
                                                      << *request->header() << "\n";
    };
  }

protected:
  nighthawk::request_source::RequestStreamResponse response_;
  Envoy::Http::TestRequestHeaderMapImpl base_header_;
  Envoy::Http::TestRequestHeaderMapImpl expected_header_;
};

TEST_F(ProtoRequestHelperTest, EmptyRequestSpecifier) { translateExpectingEqual(); }

// Test all explicit headers we offer in the proto api.
TEST_F(ProtoRequestHelperTest, ExplicitFields) {
  auto* request_specifier = response_.mutable_request_specifier();
  request_specifier->mutable_authority()->set_value("foohost");
  request_specifier->mutable_path()->set_value("/");
  request_specifier->mutable_method()->set_value("GET");
  request_specifier->mutable_content_length()->set_value(999);
  expected_header_ = Envoy::Http::TestRequestHeaderMapImpl{
      {":method", "GET"}, {"content-length", "999"}, {":path", "/"}, {":authority", "foohost"}};
  translateExpectingEqual();
}

// Test the generic header api we offer in the proto api using Envoy API v2
// primitives.
TEST_F(ProtoRequestHelperTest, GenericHeaderFieldsUsingDeprecatedEnvoyV2Api) {
  RequestSpecifier* request_specifier = response_.mutable_request_specifier();
  envoy::api::v2::core::HeaderMap* headers = request_specifier->mutable_headers();
  envoy::api::v2::core::HeaderValue* header_1 = headers->add_headers();
  header_1->set_key("header1");
  header_1->set_value("value1");
  envoy::api::v2::core::HeaderValue* header_2 = headers->add_headers();
  header_2->set_key("header2");
  header_2->set_value("value2");
  // We re-add the same header, but do not expect that to show up in the translation because we
  // always replace.
  headers->add_headers()->MergeFrom(*header_2);
  expected_header_ =
      Envoy::Http::TestRequestHeaderMapImpl{{"header1", "value1"}, {"header2", "value2"}};
  translateExpectingEqual();
}

// Test the generic header api we offer in the proto api using Envoy API v3
// primitives.
TEST_F(ProtoRequestHelperTest, GenericHeaderFieldsUsingEnvoyV3Api) {
  RequestSpecifier* request_specifier = response_.mutable_request_specifier();
  envoy::config::core::v3::HeaderMap* headers = request_specifier->mutable_v3_headers();
  envoy::config::core::v3::HeaderValue* header_1 = headers->add_headers();
  header_1->set_key("header1");
  header_1->set_value("value1");
  envoy::config::core::v3::HeaderValue* header_2 = headers->add_headers();
  header_2->set_key("header2");
  header_2->set_value("value2");
  // We re-add the same header, but do not expect that to show up in the translation because we
  // always replace.
  headers->add_headers()->MergeFrom(*header_2);
  expected_header_ =
      Envoy::Http::TestRequestHeaderMapImpl{{"header1", "value1"}, {"header2", "value2"}};
  translateExpectingEqual();
}

// Test ambiguous host configuration behavior yields expected results.
TEST_F(ProtoRequestHelperTest, AmbiguousHost) {
  auto* request_specifier = response_.mutable_request_specifier();
  request_specifier->mutable_authority()->set_value("foohost");
  expected_header_ = Envoy::Http::TestRequestHeaderMapImpl{{":authority", "foohost"}};
  // We also set the host via the headers. The explicit field we use above for that
  // should prevail.
  auto* headers = request_specifier->mutable_headers();
  auto* header_1 = headers->add_headers();
  header_1->set_key("host");
  header_1->set_value("foohost2");
  translateExpectingEqual();
}

} // namespace
} // namespace Nighthawk


text:
package forms

import forms.FormValidation._
import play.api.data.Form
import play.api.data.Forms._
import uk.gov.hmrc.play.mappers.StopOnFirstFail

object TurnoverEstimateForm {

  implicit val errorCode: String = "turnoverEstimate"
  val turnoverEstimateKey = "turnoverEstimate"
  val regex = """^[0-9 ,]*\.?[0-9]+$""".r
  val commasNotAllowed = """^[^,]+$""".r
  val moreThanTwoDecimalsNotAllowed = """^[0-9]*\.?[0-9]{1,2}$""".r

  val form: Form[BigDecimal] = Form(
    single(
      turnoverEstimateKey ->
        text
          .verifying(StopOnFirstFail(
            regexPattern(regex),
            matchesRegex(commasNotAllowed, "validation.turnoverEstimate.commasNotAllowed"),
            matchesRegex(moreThanTwoDecimalsNotAllowed, "validation.turnoverEstimate.moreThanTwoDecimalsNotAllowed"),
            mandatoryFullNumericText))
          .transform[BigDecimal](string =>
            BigDecimal(string).setScale(2, BigDecimal.RoundingMode.HALF_UP),
            _.toString
          )
          .verifying(inRange[BigDecimal](0, BigDecimal("999999999999999")))
    )
  )
}


text:
<?php
/**
 * @file
 * Default theme implementation to display a help popup.
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">

  <title><?php print $head_title; ?></title>
  <?php print $head; ?>
  <?php print $styles; ?>
  <?php print $scripts; ?>

      <?php if (!empty($search_box)): ?>

<?php print $search_box; ?>

      <?php endif; ?>

<?php print $breadcrumb; ?>

      <?php if (!empty($title)): ?>
<?php print $title; ?>
<?php endif; ?>
      <?php if (!empty($tabs)): ?>
<?php print $tabs; ?>
<?php endif; ?>
      <?php if (!empty($messages)): print $messages; endif; ?>
      <?php if (!empty($help)): print $help; endif; ?>

        <?php print $content; ?>

    <?php print $closure; ?>


text:
Scroll view subclass inspired by the Instagram Stories cube.

![demonstration](/Resources/ohcubeview-demonstration.gif)

### Requirements
- iOS >= 9.0
- Autolayout

#### N.B.
Only supports portrait mode.

## Installation

### CocoaPods

In your podfile, add `pod 'OHCubeView'` and run `pod install`. Done!

## Usage

- Using interface builder, add a UIScrollView instance to the storyboard and make it a subclass of OHCubeView. Hook the instance up to an `IBOutlet` in the view controller.

![Usage 1](/Resources/usage-1.png)

- In your view controller, programmatically add subviews to the cube view (note that this can be any kind of UIView subclass). Layout constraints are automatically added to the subviews.

```swift
import UIKit
import OHCubeView

class ViewController: UIViewController {

    @IBOutlet weak var cubeView: OHCubeView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 1. Create subviews for our cube view (in this case, five image views)

        let iv1 = UIImageView(image: UIImage(named: "img1"))
        let iv2 = UIImageView(image: UIImage(named: "img2"))
        let iv3 = UIImageView(image: UIImage(named: "img3"))
        let iv4 = UIImageView(image: UIImage(named: "img4"))
        let iv5 = UIImageView(image: UIImage(named: "img5"))

        // 2. Add all subviews to the cube view

        cubeView.addChildViews([iv1, iv2, iv3, iv4, iv5])
    }
}
```

## TODOs
- Support for infinite paging
- Add custom delegate methods


text:
package org.apache.uima.tools;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.prefs.Preferences;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.UIManager;

import org.apache.uima.UIMAException;
import org.apache.uima.UIMAFramework;
import org.apache.uima.UIMARuntimeException;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.cas.CAS;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.metadata.FsIndexDescription;
import org.apache.uima.resource.metadata.TypeSystemDescription;
import org.apache.uima.tools.docanalyzer.AnnotationViewerDialog;
import org.apache.uima.tools.docanalyzer.PrefsMediator;
import org.apache.uima.tools.images.Images;
import org.apache.uima.tools.util.gui.AboutDialog;
import org.apache.uima.tools.util.gui.Caption;
import org.apache.uima.tools.util.gui.FileSelector;
import org.apache.uima.tools.util.gui.SpringUtilities;
import org.apache.uima.tools.util.htmlview.AnnotationViewGenerator;
import org.apache.uima.util.CasCreationUtils;
import org.apache.uima.util.InvalidXMLException;
import org.apache.uima.util.XMLInputSource;

/**
 * Main Annotation Viewer GUI. Allows user to choose directory of XCAS or XMI files, then launches
 * the AnnotationViewerDialog.
 *
 *
 */
public class AnnotationViewerMain extends JFrame {

  /** The Constant serialVersionUID. */
  private static final long serialVersionUID = -3201723535833938833L;

  /** The Constant HELP_MESSAGE. */
  private static final String HELP_MESSAGE = "Instructions for using Annotation Viewer:\n\n"
          + "1) In the \"Input Directory\" field, either type or use the browse\n"
          + "button to select a directory containing the analyzed documents\n "
          + "(in XMI or XCAS format) that you want to view.\n\n"
          + "2) In the \"TypeSystem or AE Descriptor File\" field, either type or use the browse\n"
          + "button to select the TypeSystem or AE descriptor for the AE that generated the\n"
          + "XMI or XCAS files.  (This is needed for type system infornation only.\n"
          + "Analysis will not be redone.)\n\n"
          + "3) Click the \"View\" button at the buttom of the window.\n\n"
          + "A list of the analyzed documents will be displayed.\n\n\n"
          + "4) Select the view type -- either the Java annotation viewer, HTML,\n"
          + "or XML.  The Java annotation viewer is recommended.\n\n"
          + "5) Double-click on a document to view it.\n";

  /** The uima home dir. */
  private File uimaHomeDir;

  /** The input file selector. */
  private FileSelector inputFileSelector;

  /** The tae descriptor file selector. */
  private FileSelector taeDescriptorFileSelector;

  /** The view button. */
  private JButton viewButton;

  /** The about dialog. */
  private JDialog aboutDialog;

  /** Stores user preferences. */
  private Preferences prefs = Preferences.userRoot().node("org/apache/uima/tools/AnnotationViewer");

  /**
   * Constructor. Sets up the GUI.
   */
  public AnnotationViewerMain() {
    super("Annotation Viewer");

    // set UIMA home dir
    uimaHomeDir = new File(System.getProperty("uima.home", "C:/Program Files/apache-uima"));

    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
      // I don't think this should ever happen, but if it does just print error and continue
      // with defalt look and feel
      System.err.println("Could not set look and feel: " + e.getMessage());
    }
    // UIManager.put("Panel.background",Color.WHITE);
    // Need to set other colors as well

    // Set frame icon image
    try {
      this.setIconImage(Images.getImage(Images.MICROSCOPE));
      // new ImageIcon(getClass().getResource(FRAME_ICON_IMAGE)).getImage());
    } catch (IOException e) {
      System.err.println("Image could not be loaded: " + e.getMessage());
    }

    this.getContentPane().setBackground(Color.WHITE);

    // create about dialog
    aboutDialog = new AboutDialog(this, "About Annotation Viewer");

    // Create Menu Bar
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu fileMenu = new JMenu("File");
    JMenu helpMenu = new JMenu("Help");

    // Menu Items
    JMenuItem aboutMenuItem = new JMenuItem("About");
    JMenuItem helpMenuItem = new JMenuItem("Help");
    JMenuItem exitMenuItem = new JMenuItem("Exit");

    fileMenu.add(exitMenuItem);
    helpMenu.add(aboutMenuItem);
    helpMenu.add(helpMenuItem);
    menuBar.add(fileMenu);
    menuBar.add(helpMenu);

    // Labels to identify the text fields
    final Caption labelInputDir = new Caption("Input Directory: ");
    final Caption labelStyleMapFile = new Caption("TypeSystem or AE Descriptor File: ");

    JPanel controlPanel = new JPanel();
    controlPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    controlPanel.setLayout(new SpringLayout());

    // Once we add components to controlPanel, we'll
    // call SpringUtilities::makeCompactGrid on it.

    // controlPanel.setLayout(new GridLayout(4, 2, 8, 4));

    // Set default values for input fields
    File inputDir = new File(uimaHomeDir, "examples/data/processed");
    inputFileSelector = new FileSelector("", "Input Directory", JFileChooser.DIRECTORIES_ONLY,
            inputDir);
    inputFileSelector.setSelected(inputDir.getAbsolutePath());

    taeDescriptorFileSelector = new FileSelector("", "TAE Descriptor File", JFileChooser.FILES_ONLY,
            uimaHomeDir);

    File descriptorFile = new File(uimaHomeDir,
            "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml");
    taeDescriptorFileSelector.setSelected(descriptorFile.getAbsolutePath());

    controlPanel.add(labelInputDir);
    controlPanel.add(inputFileSelector);
    controlPanel.add(labelStyleMapFile);
    controlPanel.add(taeDescriptorFileSelector);

    SpringUtilities.makeCompactGrid(controlPanel, 2, 2, // rows, cols
            4, 4, // initX, initY
            4, 4); // xPad, yPad

    // Event Handlling of "Exit" Menu Item
    exitMenuItem.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent ae) {
        savePreferences();
        System.exit(0);
      }
    });

    // Event Handlling of "About" Menu Item
    aboutMenuItem.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent ae) {
        aboutDialog.setVisible(true);
      }
    });

    // Event Handlling of "Help" Menu Item
    helpMenuItem.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent ae) {
        JOptionPane.showMessageDialog(AnnotationViewerMain.this, HELP_MESSAGE,
                "Annotation Viewer Help", JOptionPane.PLAIN_MESSAGE);
      }
    });

    // Add the panels to the frame
    Container contentPanel = getContentPane();
    contentPanel.add(controlPanel, BorderLayout.CENTER);

    // add banner
    JLabel banner = new JLabel(Images.getImageIcon(Images.BANNER));
    contentPanel.add(banner, BorderLayout.NORTH);

    // Add the view Button to run TAE
    viewButton = new JButton("View");

    // Add the view button to another panel
    JPanel lowerButtonsPanel = new JPanel();
    lowerButtonsPanel.add(viewButton);

    contentPanel.add(lowerButtonsPanel, BorderLayout.SOUTH);
    setContentPane(contentPanel);

    // Event Handling of view Button
    viewButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent ee) {
        try {
          viewDocuments();
        } catch (Exception e) {
          displayError(e);
        }
      }
    });

    // load user preferences
    if (System.getProperty("uima.noprefs") == null) {
      restorePreferences();
    }
  }

  /**
   * View documents.
   *
   * @throws InvalidXMLException
   *           the invalid XML exception
   * @throws IOException
   *           Signals that an I/O exception has occurred.
   * @throws ResourceInitializationException
   *           the resource initialization exception
   */
  public void viewDocuments()
          throws InvalidXMLException, IOException, ResourceInitializationException {
    File descriptorFile = new File(taeDescriptorFileSelector.getSelected());
    if (!descriptorFile.exists() || descriptorFile.isDirectory()) {
      displayError("Descriptor File \"" + descriptorFile.getPath() + "\" does not exist.");
      return;
    }
    File inputDir = new File(inputFileSelector.getSelected());
    if (!inputDir.exists() || !inputDir.isDirectory()) {
      displayError("Input Directory \"" + inputDir.getPath() + "\" does not exist.");
      return;
    }

    // parse descriptor. Could be either AE or TypeSystem descriptor
    Object descriptor = UIMAFramework.getXMLParser().parse(new XMLInputSource(descriptorFile));
    // instantiate CAS to get type system. Also build style map file if there is none.
    CAS cas;
    File styleMapFile;
    if (descriptor instanceof AnalysisEngineDescription) {
      cas = CasCreationUtils.createCas((AnalysisEngineDescription) descriptor);
      styleMapFile = getStyleMapFile((AnalysisEngineDescription) descriptor,
              descriptorFile.getPath());
    } else if (descriptor instanceof TypeSystemDescription) {
      TypeSystemDescription tsDesc = (TypeSystemDescription) descriptor;
      tsDesc.resolveImports();
      cas = CasCreationUtils.createCas(tsDesc, null, new FsIndexDescription[0]);
      styleMapFile = getStyleMapFile((TypeSystemDescription) descriptor, descriptorFile.getPath());
    } else {
      displayError("Invalid Descriptor File \"" + descriptorFile.getPath() + "\""
              + "Must be either an AnalysisEngine or TypeSystem descriptor.");
      return;
    }

    // create Annotation Viewer Main Panel
    PrefsMediator prefsMed = new PrefsMediator();
    // set OUTPUT dir in PrefsMediator, not input dir.
    // PrefsMediator is also used in DocumentAnalyzer, where the
    // output dir is the directory containing XCAS files.
    prefsMed.setOutputDir(inputDir.toString());
    AnnotationViewerDialog viewerDialog = new AnnotationViewerDialog(this, "Analyzed Documents",
            prefsMed, styleMapFile, null, cas.getTypeSystem(), null, false, cas);
    viewerDialog.pack();
    viewerDialog.setModal(true);
    viewerDialog.setVisible(true);
  }

  /**
   * Gets the style map file.
   *
   * @param tad
   *          the tad
   * @param descFileName
   *          the desc file name
   * @return the style map file
   * @throws IOException
   *           -
   */
  private File getStyleMapFile(AnalysisEngineDescription tad, String descFileName)
          throws IOException {
    File styleMapFile = getStyleMapFileName(descFileName);
    if (!styleMapFile.exists()) {
      // generate default style map
      String xml = AnnotationViewGenerator.autoGenerateStyleMap(tad.getAnalysisEngineMetaData());

      PrintWriter writer;
      writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile)));
      writer.println(xml);
      writer.close();
    }
    return styleMapFile;
  }

  /**
   * Gets the style map file.
   *
   * @param tsd
   *          the tsd
   * @param descFileName
   *          the desc file name
   * @return the style map file
   * @throws IOException
   *           -
   */
  private File getStyleMapFile(TypeSystemDescription tsd, String descFileName) throws IOException {
    File styleMapFile = getStyleMapFileName(descFileName);
    if (!styleMapFile.exists()) {
      // generate default style map
      String xml = AnnotationViewGenerator.autoGenerateStyleMap(tsd);

      PrintWriter writer;
      writer = new PrintWriter(new BufferedWriter(new FileWriter(styleMapFile)));
      writer.println(xml);
      writer.close();
    }
    return styleMapFile;
  }

  /**
   * Gets the name of the style map file for the given AE or TypeSystem descriptor filename.
   *
   * @param aDescriptorFileName
   *          the a descriptor file name
   * @return the style map file name
   */
  public File getStyleMapFileName(String aDescriptorFileName) {
    String baseName;
    int index = aDescriptorFileName.lastIndexOf(".");
    if (index > 0) {
      baseName = aDescriptorFileName.substring(0, index);
    } else {
      baseName = aDescriptorFileName;
    }
    return new File(baseName + "StyleMap.xml");
  }

  /**
   * The main method.
   *
   * @param args
   *          the arguments
   */
  public static void main(String[] args) {
    final AnnotationViewerMain frame = new AnnotationViewerMain();

    frame.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent e) {
        frame.savePreferences();
        System.exit(0);
      }
    });
    frame.pack();
    frame.setVisible(true);
  }

  /**
   * Save user's preferences using Java's Preference API.
   */
  public void savePreferences() {
    prefs.put("inDir", inputFileSelector.getSelected());
    prefs.put("taeDescriptorFile", taeDescriptorFileSelector.getSelected());
  }

  /**
   * Reset GUI to preferences last saved via {@link #savePreferences}.
   */
  public void restorePreferences() {
    // figure defaults
    File defaultInputDir = new File(uimaHomeDir, "examples/data/processed");
    File defaultTaeDescriptorFile = new File(uimaHomeDir,
            "examples/descriptors/analysis_engine/PersonTitleAnnotator.xml");

    // restore preferences
    inputFileSelector.setSelected(prefs.get("inDir", defaultInputDir.toString()));
    taeDescriptorFileSelector
            .setSelected(prefs.get("taeDescriptorFile", defaultTaeDescriptorFile.toString()));
  }

  /**
   * Displays an error message to the user.
   *
   * @param aErrorString
   *          error message to display
   */
  public void displayError(String aErrorString) {
    // word-wrap long mesages
    StringBuffer buf = new StringBuffer(aErrorString.length());
    final int CHARS_PER_LINE = 80;
    int charCount = 0;
    StringTokenizer tokenizer = new StringTokenizer(aErrorString, " \n", true);

    while (tokenizer.hasMoreTokens()) {
      String tok = tokenizer.nextToken();

      if (tok.equals("\n")) {
        buf.append("\n");
        charCount = 0;
      } else if ((charCount > 0) && ((charCount + tok.length()) > CHARS_PER_LINE)) {
        buf.append("\n").append(tok);
        charCount = tok.length();
      } else {
        buf.append(tok);
        charCount += tok.length();
      }
    }

    JOptionPane.showMessageDialog(AnnotationViewerMain.this, buf.toString(), "Error",
            JOptionPane.ERROR_MESSAGE);
  }

  /**
   * Displays an error message to the user.
   *
   * @param aThrowable
   *          Throwable whose message is to be displayed.
   */
  public void displayError(Throwable aThrowable) {
    aThrowable.printStackTrace();

    String message = aThrowable.toString();

    // For UIMAExceptions or UIMARuntimeExceptions, add cause info.
    // We have to go through this nonsense to support Java 1.3.
    // In 1.4 all exceptions can have a cause, so this wouldn't involve
    // all of this typecasting.
    while ((aThrowable instanceof UIMAException) || (aThrowable instanceof UIMARuntimeException)) {
      if (aThrowable instanceof UIMAException) {
        aThrowable = ((UIMAException) aThrowable).getCause();
      } else if (aThrowable instanceof UIMARuntimeException) {
        aThrowable = ((UIMARuntimeException) aThrowable).getCause();
      }

      if (aThrowable != null) {
        message += ("\nCausedBy: " + aThrowable.toString());
      }
    }

    displayError(message);
  }

  /*
   * (non-Javadoc)
   *
   * @see java.awt.Component#getPreferredSize()
   */
  @Override
  public Dimension getPreferredSize() {
    return new Dimension(640, 200);
  }
}


text:
//
//  GridViewController.h
//  VTMagicView
//
//  Created by tianzhuo on 14/12/30.
//  Copyright (c) 2014年 tianzhuo. All rights reserved.
//

#import <UIKit/UIKit.h>

@class MenuInfo;
@interface VTGridViewController : UICollectionViewController

/**
 *  菜单信息
 */
@property (nonatomic, strong) MenuInfo *menuInfo;

@end


text:
namespace Microsoft.Azure.Management.CognitiveServices
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// CheckSkuAvailabilityOperations operations.
    /// </summary>
    public partial interface ICheckSkuAvailabilityOperations
    {
        /// <summary>
        /// Check available SKUs.
        /// </summary>
        /// <param name='location'>
        /// Resource location.
        /// </param>
        /// <param name='skus'>
        /// The SKU of the resource.
        /// </param>
        /// <param name='kind'>
        /// The Kind of the resource. Possible values include:
        /// 'Bing.Autosuggest.v7', 'Bing.CustomSearch', 'Bing.Search.v7',
        /// 'Bing.Speech', 'Bing.SpellCheck.v7', 'ComputerVision',
        /// 'ContentModerator', 'CustomSpeech', 'CustomVision.Prediction',
        /// 'CustomVision.Training', 'Emotion', 'Face', 'LUIS', 'QnAMaker',
        /// 'SpeakerRecognition', 'SpeechTranslation', 'TextAnalytics',
        /// 'TextTranslation', 'WebLM'
        /// </param>
        /// <param name='type'>
        /// The Type of the resource.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<CheckSkuAvailabilityResultList>> ListWithHttpMessagesAsync(string location, IList<string> skus, string kind, string type, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
#pragma once

#include "common-hal/alarm/SleepMemory.h"
#include "common-hal/alarm/pin/PinAlarm.h"
#include "common-hal/alarm/time/TimeAlarm.h"

extern const alarm_sleep_memory_obj_t alarm_sleep_memory_obj;

typedef enum {
    STM_WAKEUP_UNDEF,
    STM_WAKEUP_GPIO,
    STM_WAKEUP_RTC
} stm_sleep_source_t;

typedef union {
    alarm_pin_pinalarm_obj_t pin_alarm;
    alarm_time_timealarm_obj_t time_alarm;
} alarm_wake_alarm_union_t;

extern alarm_wake_alarm_union_t alarm_wake_alarm;

#define STM_ALARM_FLAG      (RTC->BKP0R)

extern void alarm_set_wakeup_reason(stm_sleep_source_t reason);
extern stm_sleep_source_t alarm_get_wakeup_cause(void);
extern void alarm_reset(void);


text:
@interface CALogDetailViewController : UIViewController

@property (nonatomic, retain) NSString *detail;
@property (nonatomic, assign) id delegate;

@end


text:
When /^I follow "New Adjustment" custom$/ do
  page.first('#content .toolbar .actions li a').click
end

Given /^an adjustment exists for order R100$/ do
  order = Order.find_by_number('R100')
  Factory(:adjustment, :order => order)
end


text:
package org.elasticsearch.action.admin.indices.flush;

import org.elasticsearch.action.ActionType;

public class SyncedFlushAction extends ActionType<SyncedFlushResponse> {

    public static final SyncedFlushAction INSTANCE = new SyncedFlushAction();
    public static final String NAME = "indices:admin/synced_flush";

    private SyncedFlushAction() {
        super(NAME, SyncedFlushResponse::new);
    }
}


text:
<resources>
    <string name="app_name">ORTM</string>

    <string name="action_settings">À propos</string>
    <string name="required_connexion_body">Vous devez être connecté pour accèder au livestream de l\'ORTM.</string>
    <string name="loading">Chargement en cours ...</string>
    <string name="offlive">Direct TV ORTM indisponible pour le moment</string>
    <string name="share">Partager</string>
    <string name="about_long_description"><![CDATA[

Cette application vous donne accès aux contenus Web de l'Office de Radiodiffusion Télévision du Mali :

 * La télévision ORTM en direct

 * La radio Chaine Nationale en direct

 * La radio Chaine 2 en direct

 * Le site web ORTM.ml

        Pour toute suggestion ou tout commentaire, merci de contacter :]]></string>
    <string name="version_button_label">Version %1$s (vérifier mises à jour)</string>
    <string name="required_connexion_radio"> "Vous devez être connecté pour écouter la radio"</string>
</resources>


text:
require_relative "../spec_helper"

describe FuzzyNinja::Message do
end


text:
  Marlieux est
       un village
       localisé dans le département de l'Ain en Rhône-Alpes. Elle totalisait 759 habitants en 2008.

À proximité de Marlieux sont situées les communes de
Saint-Nizier-le-Désert située à 5 km, 797 habitants,
Sandrans localisée à 7 km, 502 habitants,
La Chapelle-du-Châtelard localisée à 3 km, 276 habitants,
Saint-Germain-sur-Renon à 2 km, 240 habitants,
Saint-Paul-de-Varax située à 5 km, 1 429 habitants,
Le Plantay située à 4 km, 512 habitants,
 entre autres. De plus, Marlieux est située à seulement 19 km de Bourg-en-Bresse.

La localité dispose concernant l'enseignement de un collège.
S'agissant les plus petits d'entre nous, la ville est pourvue de deux écoles primaires.
Marlieux dispose des équipements éducatifs facilitant une bonne prise en charge des jeunes.
Si vous avez un projet de transaction immobilière à Marlieux, il est intéressant d' évaluer la qualité des équipements éducatifs

Si vous envisagez de venir habiter à Marlieux, vous pourrez aisément trouver une maison à vendre.

À Marlieux, la valeur moyenne à la vente d'un appartement se situe à 1 156 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 361 € du m². À la location la valorisation moyenne se situe à 0 € du m² par mois.

La ville offre quelques  équipements, elle propose entre autres un terrain de tennis et un terrain de sport.

Le nombre de logements, à Marlieux, était réparti en 2011 en 105 appartements et 318 maisons soit
 un marché relativement équilibré.


text:
import {
  Component,
  DoCheck,
  EventEmitter,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  Output,
  SimpleChanges,
  ViewChild,
  ViewEncapsulation
} from '@angular/core';
import {
  ActivatedRoute,
  Event as NavigationEvent,
  NavigationEnd,
  NavigationStart,
  Router
} from '@angular/router';

import { Broadcaster, Logger, Notification, Notifications, NotificationType } from 'ngx-base';
import { Space, Spaces } from 'ngx-fabric8-wit';
import { AuthenticationService } from 'ngx-login-client';
import { Dialog } from 'ngx-widgets';
import { Subscription } from 'rxjs/Subscription';

import { IterationUI } from '../../models/iteration.model';
import { FilterService } from '../../services/filter.service';
import { GroupTypesService } from '../../services/group-types.service';

@Component({
  encapsulation: ViewEncapsulation.None,
  selector: 'iteration-list-entry',
  templateUrl: './iteration-list-entry.component.html',
  styleUrls: ['./iteration-list-entry.component.less']
})
export class IterationListEntryComponent implements OnInit, OnDestroy {
  //@Input() listItem: TreeListItemComponent;
  @Input() iteration: IterationUI;
  @Input() selected: boolean = false;
  @Input() collection = [];
  @Input() witGroup: string = '';
  @Input() showTree: string = '';
  @Input() showCompleted: string = '';
  @Input() context: 'list' | 'board'; // 'list' or 'board'

  @Output() readonly onEditIteration = new EventEmitter<IterationUI>();
  @Output() readonly onCloseIteration = new EventEmitter<IterationUI>();
  @Output() readonly onCreateIteration = new EventEmitter<IterationUI>();

  loggedIn: Boolean = false;
  queryParams: Object = {};
  eventListeners: any[] = [];
  selectedItemId: string | number = 0;
  private spaceSubscription: Subscription = null;
  spaceId: string = '';

  constructor(private auth: AuthenticationService,
    private broadcaster: Broadcaster,
    private route: ActivatedRoute,
    private filterService: FilterService,
    private groupTypesService: GroupTypesService,
    private notifications: Notifications,
    private router: Router,
    private spaces: Spaces,
    private logger: Logger) {}

  ngOnInit(): void {
    this.loggedIn = this.auth.isLoggedIn();
    this.spaceSubscription = this.spaces.current.subscribe(space => {
      if (space) {
        this.spaceId = space.id;
      }
    });
  }

  ngOnDestroy() {
    this.eventListeners.forEach(subscriber => subscriber.unsubscribe());
  }

  setGuidedTypeWI(wiCollection) {
    this.groupTypesService.setCurrentGroupType(wiCollection, 'execution');
  }

  constructURL(iterationId: string) {
    //Query for work item type group
    const type_query = this.filterService.queryBuilder('typegroup.name', this.filterService.equal_notation, this.witGroup);
    //Query for space
    const space_query = this.filterService.queryBuilder('space', this.filterService.equal_notation, this.spaceId);
    //Query for iteration
    const iteration_query = this.filterService.queryBuilder('iteration', this.filterService.equal_notation, iterationId);
    //Join type and space query
    const first_join = this.filterService.queryJoiner({}, this.filterService.and_notation, space_query);
    const second_join = this.filterService.queryJoiner(first_join, this.filterService.and_notation, type_query);
    const third_join = this.filterService.queryJoiner(second_join, this.filterService.and_notation, iteration_query);
    //this.setGroupType(witGroup);
    //second_join gives json object
    return this.filterService.jsonToQuery(third_join);
  }

  addRemoveQueryParams(iterationId: string) {
    if (this.showCompleted && this.showTree) {
      return {
        q: this.constructURL(iterationId),
        showTree: this.showTree,
        showCompleted: this.showCompleted
      };
    } else if (this.showTree) {
      return {
        q: this.constructURL(iterationId),
        showTree: this.showTree
      };
    } else if (this.showCompleted) {
      return {
        q: this.constructURL(iterationId),
        showCompleted: this.showCompleted
      };
    } else {
      return {
        q: this.constructURL(iterationId)
      };
    }
  }

  getRouterLink() {
    return this.context === 'board' ? ['..'] : [];
  }

  toggleChildrenDisplay(iteration) {
    // TODO: Dispatch an action to this
    iteration.showChildren = !iteration.showChildren;
  }

  editIteration(iteration) {
    this.onEditIteration.emit(iteration);
  }

  closeIteration(iteration) {
    this.onCloseIteration.emit(iteration);
  }

  createIteration(iteration) {
    this.onCreateIteration.emit(iteration);
  }
  calcDepth(iteration: IterationUI): string {
    let depth = ((iteration.parentPath).split('/')).length - 1;
    return 'depth-' + depth;
  }
}


text:
import { Controller } from 'aurelia-templating';
import { Renderer } from './renderer';
import { NotificationCancelableOperationResult, NotificationCloseResult, NotificationCancelResult } from './notification-result';
import { NotificationSettings } from './notification-settings';
import { invokeLifecycle } from './lifecycle';
import { createNotificationCloseError, NotificationCloseError } from './notification-close-error';
import { createNotificationCancelError } from './notification-cancel-error';

/**
 * A controller object for a notification instance.
 */
export class NotificationController {
    private resolve: (data?: any) => void;
    private reject: (reason: any) => void;

    /**
     * @internal
     */
    public closePromise: Promise<any> | undefined;

    /**
     * The settings used by this controller.
     */
    public settings: NotificationSettings;
    public renderer: Renderer;
    public controller: Controller;

    /**
     * @internal
     */
    public static inject = [Renderer];
    /**
     * Creates an instance of NotificationController.
     */
    constructor(
        renderer: Renderer, settings: NotificationSettings,
        resolve: (data?: any) => void, reject: (reason: any) => void) {
        this.resolve = resolve;
        this.reject = reject;
        this.settings = settings;
        this.renderer = renderer;
    }

    /**
     * @internal
     */
    public releaseResources(result: NotificationCloseResult | NotificationCloseError): Promise<void> {
        return invokeLifecycle(this.controller.viewModel || {}, 'deactivate', result)
            .then(() => this.renderer.hideNotification(this))
            .then(() => { this.controller.unbind(); });
    }

    /**
     * @internal
     */
    public cancelOperation(): NotificationCancelResult {
        if (!this.settings.rejectOnCancel) {
            return { wasCancelled: true };
        }
        throw createNotificationCancelError();
    }

    /**
     * Closes the notification with a successful output.
     * @param output The returned success output.
     */
    public ok(output?: any): Promise<NotificationCancelableOperationResult> {
        return this.close(true, output);
    }

    /**
     * Closes the notification with a cancel output.
     * @param output The returned cancel output.
     */
    public cancel(output?: any): Promise<NotificationCancelableOperationResult> {
        return this.close(false, output);
    }

    /**
     * Closes the notification with an error output.
     * @param output A reason for closing with an error.
     * @returns Promise An empty promise object.
     */
    public error(output: any): Promise<void> {
        const closeError = createNotificationCloseError(output);
        return this.releaseResources(closeError).then(() => { this.reject(closeError); });
    }

    /**
     * Closes the notification.
     * @param ok Whether or not the user input signified success.
     * @param output The specified output.
     * @returns Promise An empty promise object.
     */
    public close(ok: boolean, output?: any): Promise<NotificationCancelableOperationResult> {
        if (this.closePromise) {
            return this.closePromise;
        }

        const notificationResult = { wasCancelled: !ok, output } as NotificationCloseResult;

        return this.closePromise = invokeLifecycle(this.controller.viewModel || {}, 'canDeactivate', notificationResult)
            .catch(reason => {
                this.closePromise = undefined;
                return Promise.reject(reason);
            }).then(canDeactivate => {
                if (!canDeactivate) {
                    this.closePromise = undefined; // we are done, do not block consecutive calls
                    return this.cancelOperation();
                }
                return this.releaseResources(notificationResult).then(() => {
                    if (!this.settings.rejectOnCancel || ok) {
                        this.resolve(notificationResult);
                    } else {
                        this.reject(createNotificationCancelError(output));
                    }
                    return { wasCancelled: false };
                }).catch(reason => {
                    this.closePromise = undefined;
                    return Promise.reject(reason);
                });
            });
    }
}


text:
<?php
namespace ShinyDeploy\Domain\Database;

use RuntimeException;
use ShinyDeploy\Domain\Deployment;
use ShinyDeploy\Exceptions\DatabaseException;
use ShinyDeploy\Traits\CryptableDomain;

class Deployments extends DatabaseDomain
{
    use CryptableDomain;

    /** @var array $rules Validation rules */
    protected array $rules = [
        'required' => [
            ['name'],
            ['repository_id'],
            ['server_id'],
            ['branch'],
            ['target_path'],
        ],
        'integer' => [
            ['repository_id'],
            ['server_id'],
        ],
        'lengthBetween' => [
            ['name', 1, 100],
            ['branch', 1, 100],
            ['target_path', 1, 200],
        ]
    ];

    /** @var array $encryptedFields Fields that are encrypted in database. */
    protected array $encryptedFields = [
        'tasks',
    ];

    /**
     * Get validation rules for insert queries.
     *
     * @return array
     */
    public function getCreateRules(): array
    {
        return $this->rules;
    }

    /**
     * Get validation rules for update queries.
     *
     * @return array
     */
    public function getUpdateRules(): array
    {
        $rules = $this->rules;
        $rules['required'][] = ['id'];
        return $this->rules;
    }

    /**
     * Creates and returns a deployment object.
     *
     * @param int $deploymentId
     * @return Deployment
     * @throws DatabaseException
     * @throws \ShinyDeploy\Exceptions\CryptographyException
     */
    public function getDeployment(int $deploymentId): Deployment
    {
        $data = $this->getDeploymentData($deploymentId);
        if (empty($data)) {
            throw  new RuntimeException('Deployment not found in database.');
        }
        $deployment = new Deployment($this->config, $this->logger);
        $deployment->setEncryptionKey($this->encryptionKey);
        $deployment->init($data);
        return $deployment;
    }

    /**
     * Fetches list of deployments from database.
     *
     * @return array
     * @throws DatabaseException
     * @throws \ShinyDeploy\Exceptions\CryptographyException
     */
    public function getDeployments(): array
    {
        $rows = $this->db->prepare("SELECT * FROM deployments ORDER BY `name`")->getResult(false);
        if (empty($rows)) {
            return $rows;
        }
        foreach ($rows as $i => $row) {
            $rowDecrypted = $this->decryptData($row, $this->encryptedFields);
            if ($rowDecrypted === []) {
                throw new RuntimeException('Data decryption failed.');
            }
            $rows[$i] = $rowDecrypted;
        }
        return $rows;
    }

    /**
     * Stores new server in database.
     *
     * @param array $deploymentData
     * @throws DatabaseException
     * @throws \ShinyDeploy\Exceptions\CryptographyException
     * @return bool
     */
    public function addDeployment(array $deploymentData): bool
    {
        if (!isset($deploymentData['tasks'])) {
            $deploymentData['tasks'] = '';
        }
        $deploymentData = $this->encryptData($deploymentData, $this->encryptedFields);
        if ($deploymentData === false) {
            throw new RuntimeException('Data encryption failed.');
        }
        return $this->db->prepare(
            "INSERT INTO deployments
              (`name`, `repository_id`, `server_id`, `branch`, `target_path`, `tasks`)
              VALUES
                (%s, %i, %i, %s, %s, %s)",
            $deploymentData['name'],
            $deploymentData['repository_id'],
            $deploymentData['server_id'],
            $deploymentData['branch'],
            $deploymentData['target_path'],
            $deploymentData['tasks']
        )->execute();
    }

    /**
     * Updates deployment.
     *
     * @param array $deploymentData
     * @throws DatabaseException
     * @throws \ShinyDeploy\Exceptions\CryptographyException
     * @return bool
     */
    public function updateDeployment(array $deploymentData): bool
    {
        if (!isset($deploymentData['id'])) {
            return false;
        }
        $deploymentData = $this->encryptData($deploymentData, $this->encryptedFields);
        if ($deploymentData === false) {
            throw new RuntimeException('Data encryption failed.');
        }
        return $this->db->prepare(
            "UPDATE deployments
            SET `name` = %s,
              `repository_id` = %i,
              `server_id` = %i,
              `branch` = %s,
              `target_path` = %s,
              `tasks` = %s
            WHERE id = %i",
            $deploymentData['name'],
            $deploymentData['repository_id'],
            $deploymentData['server_id'],
            $deploymentData['branch'],
            $deploymentData['target_path'],
            $deploymentData['tasks'],
            $deploymentData['id']
        )->execute();
    }

    /**
     * Deletes a deployment.
     *
     * @param int $deploymentId
     * @throws DatabaseException
     * @return bool
     */
    public function deleteDeployment(int $deploymentId): bool
    {
        $deploymentId = (int)$deploymentId;
        if ($deploymentId === 0) {
            return false;
        }
        // delete deployment logs:
        $this->db->prepare("DELETE FROM deployment_logs WHERE `deployment_id` = %i", $deploymentId)->execute();

        // delete deployment:
        return $this->db->prepare("DELETE FROM deployments WHERE `id` = %i LIMIT 1", $deploymentId)->execute();
    }

    /**
     * Fetches deployment data.
     *
     * @param int $deploymentId
     * @throws DatabaseException
     * @throws \ShinyDeploy\Exceptions\CryptographyException
     * @return array
     */
    public function getDeploymentData(int $deploymentId): array
    {
        $deploymentId = (int)$deploymentId;
        if ($deploymentId === 0) {
            return [];
        }
        $deploymentData = $this->db->prepare("SELECT * FROM deployments WHERE `id` = %i", $deploymentId)
            ->getResult(true);
        if (empty($deploymentData)) {
            return [];
        }
        $deploymentData = $this->decryptData($deploymentData, $this->encryptedFields);
        if ($deploymentData === []) {
            throw new RuntimeException('Data decryption failed.');
        }
        if (!empty($deploymentData['tasks'])) {
            $deploymentData['tasks'] = json_decode($deploymentData['tasks'], true);
        }
        return $deploymentData;
    }

    /**
     * Checks if another deployment with same server-id and target path exists.
     *
     * @param array $deploymentData
     * @throws DatabaseException
     * @return bool
     */
    public function targetExists(array $deploymentData): bool
    {
        $statement = "SELECT COUNT(id) FROM deployments WHERE `server_id` = %i AND `target_path` = %s";
        $cnt = $this->db->prepare($statement, $deploymentData['server_id'], $deploymentData['target_path'])
            ->getValue();
        return ($cnt > 0);
    }

    /**
     * Adds ids to tasks and returns data as json-encoded string.
     *
     * @param array $tasks
     * @return string
     */
    public function encodeDeploymentTasks(array $tasks): string
    {
        // set task ids:
        foreach ($tasks as $i => $task) {
            if (!isset($task['id'])) {
                $tasks[$i]['id'] = $this->getRandomTaskId();
            }
        }

        // return tasks as json-encoded string:
        return json_encode($tasks);
    }

    /**
     * Generates a random string to use as task-id.
     *
     * @return string
     */
    protected function getRandomTaskId(): string
    {
        $randomId = '';
        $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $max = strlen($characters) - 1;
        for ($i = 0; $i < 6; $i++) {
            $randomId .= $characters[mt_rand(0, $max)];
        }
        return $randomId;
    }
}


text:
package de.invidit.design.structural.bridge.external.commerzbank.v2;

import de.invidit.design.structural.bridge.external.commerzbank.v2.model.AccountData;
import de.invidit.design.structural.bridge.model.Accounting;

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

/**
 * @author Torsten Mingers
 * @since 02.08.2016
 */
public class AccountingConverter {

    List<Accounting> convertToAccounting(List<AccountData> accountDataList) {

        ArrayList<Accounting> convertedAccountings = new ArrayList<>();

        for (AccountData accountData : accountDataList) {
            Accounting accounting = Accounting.builder()
                    .Absender(accountData.Absender)
                    .Empfaenger(accountData.Empfaenger)
                    .SollHabenKennzeichen(accountData.SollHabenKennzeichen)
                    .Betrag(accountData.Betrag)
                    .Text(accountData.Text)
                    .build();

            convertedAccountings.add(accounting);
        }

        return convertedAccountings;
    }
}


text:
require File.expand_path(File.dirname(__FILE__)) + '/../helper'

class LintToolTest < Test::Unit::TestCase

  def test_action_description
    assert_equal "Verify all the exported trackers and check for errors", Tracksperanto::Tool::Lint.action_description
  end

  def test_empty_export_raises
    m = flexmock
    m.should_receive(:start_export).once

    ex = Tracksperanto::Tool::Lint.new(m)
    ex.start_export(100, 100)
    assert_raise(Tracksperanto::Tool::Lint::NoTrackersExportedError) do
      ex.end_export
    end

  end

  def test_exporting_empty_tracker_raises
    m = flexmock
    m.should_receive(:start_export).once
    m.should_receive(:start_tracker_segment).once

    ex = Tracksperanto::Tool::Lint.new(m)
    ex.start_export(100, 100)
    ex.start_tracker_segment("Foo")

    assert_raise(Tracksperanto::Tool::Lint::EmptyTrackerSentError) do
      ex.end_tracker_segment
    end
  end

  def test_exporting_out_of_sequence_raises
    m = flexmock
    m.should_receive(:start_export).once
    m.should_receive(:start_tracker_segment).once
    m.should_receive(:export_point).once

    ex = Tracksperanto::Tool::Lint.new(m)
    ex.start_export(100, 100)
    ex.start_tracker_segment("Foo")
    ex.export_point(2, 123.3, 456.0, 0.0)

    assert_raise(Tracksperanto::Tool::Lint::NonSequentialKeyframes) do
      ex.export_point(1, 123.3, 456.0, 0.0)
    end
  end

  def test_exporting_in_sequence_starting_on_frame_minus_one
    m = flexmock
    m.should_receive(:start_export).once
    m.should_receive(:start_tracker_segment).once
    m.should_receive(:export_point).twice

    ex = Tracksperanto::Tool::Lint.new(m)
    ex.start_export(100, 100)
    ex.start_tracker_segment("Foo")
    ex.export_point(-1, 123.3, 456.0, 0.0)
    ex.export_point(0, 123.3, 456.0, 0.0)
  end

  def test_exporting_with_two_starts_raises
    m = flexmock
    m.should_receive(:start_export).once
    m.should_receive(:start_tracker_segment).once

    ex = Tracksperanto::Tool::Lint.new(m)
    ex.start_export(100, 100)
    ex.start_tracker_segment("Foo")

    assert_raise(Tracksperanto::Tool::Lint::TrackerRestartedError) do
      ex.start_tracker_segment("Bar")
    end
  end

end


text:
require 'rake'
require 'models/mark'
load 'tasks/markable.rake'

module Markable
  mattr_accessor :markers, :markables, :models
  @@markers   = []
  @@markables = []
  @@models    = []
  @@marker_objects   = []
  @@markable_objects = []

protected

  def self.set_models
    @@models = @@models.presence || ActiveRecord::Base.connection.tables.collect{ |t| t.classify rescue nil }.compact
  end

  def self.add_markable(markable)
    @@markable_objects.push markable unless @@markable_objects.include? markable
    @@markables.push markable.name.to_sym unless @@markables.include? markable.name.to_sym
    create_methods @@marker_objects, [ markable ]
  end

  def self.add_marker(marker)
    @@marker_objects.push marker unless @@marker_objects.include? marker
    @@markers.push marker.name.to_sym unless @@markers.include? marker.name.to_sym
    create_methods [ marker ], @@markable_objects
  end

  def self.create_methods(markers, markables)
    markables.try :each do |markable|
      markers.try :each do |marker|
        markable.__markable_marks.each do |mark, options|
          if options[:allowed_markers] == :all || options[:allowed_markers].include?(marker.marker_name)
            markable_name = markable.name.downcase
            method_name = "#{mark}_#{markable_name}".pluralize
            marker.class_eval %(
              def #{method_name}
                #{markable.name}.marked_as :#{mark}, :by => self
              end
              def #{markable_name.pluralize}_marked_as mark
                #{markable.name}.marked_as mark, :by => self
              end
              def #{markable_name.pluralize}_marked_as_#{mark}
                #{markable.name}.marked_as :#{mark}, :by => self
              end
            )
            unless marker.methods.include?("mark_as_#{mark}".to_sym)
              marker.class_eval %(
                def mark_as_#{mark}(objects)
                  self.set_mark :#{mark}, objects
                end
              )
            end
            markable.class_eval %(
              def #{marker.marker_name.to_s.pluralize}_have_marked_as mark
                self.have_marked_as_by(mark, #{marker.name})
              end

              def #{marker.marker_name.to_s.pluralize}_have_marked_as_#{mark}
                self.have_marked_as_by(:#{mark}, #{marker.name})
              end
            )
          end
        end
      end
    end
  end

  def self.can_mark_or_raise?(markers, markables, mark)
    Array.wrap(markers).all? do |marker_object|
      Array.wrap(markables).all? do |markable|
        self.can_mark_object?(marker_object, markable, mark)
      end
    end
  end

  def self.can_mark_object?(marker_object, markable_object, mark)
    marker_name = marker_object.class.name.to_sym
    markable_name = markable_object.class.name.to_sym
    raise Markable::WrongMarkerType.new(marker_name) unless @@markers.include?(marker_name)
    raise Markable::WrongMarkableType.new(markable_name) unless @@markables.include?(markable_name)
    raise Markable::WrongMark.new(marker_object, markable_object, mark) unless markable_object.class.__markable_marks.include?(mark)

    raise Markable::NotAllowedMarker.new(marker_object, markable_object, mark) unless (markable_object.class.__markable_marks[mark][:allowed_markers] == :all ||
                                                                  markable_object.class.__markable_marks[mark][:allowed_markers].include?(marker_name.to_s.downcase.to_sym))

    true
  end
end

require 'markable/exceptions'
require 'markable/acts_as_marker'
require 'markable/acts_as_markable'


text:
<md-toolbar class="md-whiteframe-z3">

        <md-button class="md-icon-button white" aria-label="Takaisin" ng-click="vm.back()">
            <md-icon>arrow_back</md-icon>
        </md-button>

        {{ ::vm.stateParams.serviceType }}t

        <md-button class="md-icon-button white" aria-label="Takaisin" ng-disabled="true">
            <md-icon>filter_list</md-icon>
        </md-button>

        {{ ::vm.stateParams.carBrand }}, {{ ::vm.stateParams.city }}

    <md-tabs md-dynamic-height md-stretch-tabs="always">
        <md-tab label="Etäisyys" data-ng-click="vm.sharedData.order = 'distance'">
        </md-tab>

        <md-tab label="Arviot" data-ng-click="vm.sharedData.order = '-rating'">
        </md-tab>
    </md-tabs>
</md-toolbar>