text:
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Configuration;
using DTcms.Common;

namespace DTcms.Web.UI
{
    public partial class BasePage : System.Web.UI.Page
    {
        protected internal Model.siteconfig config = new BLL.siteconfig().loadConfig();
        protected internal Model.userconfig uconfig = new BLL.userconfig().loadConfig();
        /// <summary>
        /// 父类的构造函数
        /// </summary>
        public BasePage()
        {
            //是否关闭网站
            if (config.webstatus == 0)
            {
                HttpContext.Current.Response.Redirect(config.webpath + "error.aspx?msg=" + Utils.UrlEncode(config.webclosereason));
                return;
            }
            ShowPage();
        }

        /// <summary>
        /// 页面处理虚方法
        /// </summary>
        protected virtual void ShowPage()
        {
            //虚方法代码
        }

        #region 页面通用方法==========================================
        /// <summary>
        /// 返回URL重写统一链接地址
        /// </summary>
        public string linkurl(string _key, params object[] _params)
        {
            Hashtable ht = new BLL.url_rewrite().GetList(); //获得URL配置列表
            Model.url_rewrite model = ht[_key] as Model.url_rewrite; //查找指定的URL配置节点

            //如果不存在该节点则返回空字符串
            if (model == null)
            {
                return string.Empty;
            }

            string requestDomain = HttpContext.Current.Request.Url.Authority.ToLower(); //获得来源域名含端口号
            string requestFirstPath = GetFirstPath();//获得二级目录(不含站点安装目录)
            string linkStartString = string.Empty; //链接前缀

            //检查是否与绑定的域名或者与默认频道分类的目录匹配
            if (SiteDomains.GetSiteDomains().CategoryDirs.ContainsValue(requestDomain))
            {
                linkStartString = "/";
            }

            else if (requestFirstPath == string.Empty || requestFirstPath == SiteDomains.GetSiteDomains().DefaultPath)
            {
                linkStartString = config.webpath;
            }
            else
            {
                linkStartString = config.webpath + requestFirstPath + "/";
            }
            //如果URL字典表达式不需要重写则直接返回
            if (model.url_rewrite_items.Count == 0)
            {
                //检查网站重写状态
                if (config.staticstatus > 0)
                {
                    if (_params.Length > 0)
                    {
                        return linkStartString + GetUrlExtension(model.page, config.staticextension) + string.Format("{0}", _params);
                    }
                    else
                    {
                        return linkStartString + GetUrlExtension(model.page, config.staticextension);
                    }
                }
                else
                {
                    if (_params.Length > 0)
                    {
                        return linkStartString + model.page + string.Format("{0}", _params);
                    }
                    else
                    {
                        return linkStartString + model.page;
                    }
                }
            }
            //否则检查该URL配置节点下的子节点
            foreach (Model.url_rewrite_item item in model.url_rewrite_items)
            {
                //如果参数个数匹配
                if (IsUrlMatch(item, _params))
                {
                    //检查网站重写状态
                    if (config.staticstatus > 0)
                    {
                        return linkStartString + string.Format(GetUrlExtension(item.path, config.staticextension), _params);
                    }
                    else
                    {
                        string queryString = Regex.Replace(string.Format(item.path, _params), item.pattern, item.querystring, RegexOptions.None | RegexOptions.IgnoreCase);
                        if (queryString.Length > 0)
                        {
                            queryString = "?" + queryString;
                        }
                        return linkStartString + model.page + queryString;
                    }
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 返回分页字符串
        /// </summary>
        /// <param name="pagesize">页面大小</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="totalcount">记录总数</param>
        /// <param name="_key">URL映射Name名称</param>
        /// <param name="_params">传输参数</param>
        protected string get_page_link(int pagesize, int pageindex, int totalcount, string _key, params object[] _params)
        {
            return Utils.OutPageList(pagesize, pageindex, totalcount, linkurl(_key, _params), 8);
        }

        /// <summary>
        /// 返回分页字符串
        /// </summary>
        /// <param name="pagesize">页面大小</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="totalcount">记录总数</param>
        /// <param name="linkurl">链接地址</param>
        protected string get_page_link(int pagesize, int pageindex, int totalcount, string linkurl)
        {
            return Utils.OutPageList(pagesize, pageindex, totalcount, linkurl, 8);
        }
        #endregion

        #region 会员用户方法==========================================
        /// <summary>
        /// 判断用户是否已经登录(解决Session超时问题)
        /// </summary>
        public bool IsUserLogin()
        {
            //如果Session为Null
            if (HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] != null)
            {
                return true;
            }
            else
            {
                //检查Cookies
                string username = Utils.GetCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "DTcms");
                string password = Utils.GetCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "DTcms");
                if (username != "" && password != "")
                {
                    BLL.users bll = new BLL.users();
                    Model.users model = bll.GetModel(username, password, 0, 0, false);
                    if (model != null)
                    {
                        HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] = model;
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 取得用户信息
        /// </summary>
        public Model.users GetUserInfo()
        {
            if (IsUserLogin())
            {
                Model.users model = HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] as Model.users;
                if (model != null)
                {
                    //为了能查询到最新的用户信息,必须查询最新的用户资料
                    model = new BLL.users().GetModel(model.id);
                    return model;
                }
            }
            return null;
        }
        #endregion

        #region 辅助方法(私有)========================================
        /// <summary>
        /// 获取访问的频道分类目录(不含安装目录)
        /// </summary>
        private string GetFirstPath()
        {
            //string requestPath = HttpContext.Current.Request.CurrentExecutionFilePath.ToLower();//获得当前页面虚拟路径
            string requestPath = HttpContext.Current.Request.RawUrl.ToLower();
            int indexNum = config.webpath.Length; //安装目录长度
            //如果包含安装目录和aspx目录也要过滤掉
            if (requestPath.StartsWith(config.webpath + DTKeys.DIRECTORY_REWRITE_ASPX + "/"))
            {
                indexNum = (config.webpath + DTKeys.DIRECTORY_REWRITE_ASPX + "/").Length;
            }
            string requestFirstPath = requestPath.Substring(indexNum);
            if (requestFirstPath.IndexOf("/") > 0)
            {
                requestFirstPath = requestFirstPath.Substring(0, requestFirstPath.IndexOf("/"));
            }
            if (requestFirstPath != string.Empty && SiteDomains.GetSiteDomains().CategoryDirs.ContainsKey(requestFirstPath))
            {
                return requestFirstPath;
            }
            return string.Empty;
        }

        /// <summary>
        /// 参数个数是否匹配
        /// </summary>
        private bool IsUrlMatch(Model.url_rewrite_item item, params object[] _params)
        {
            int strLength = 0;
            if (!string.IsNullOrEmpty(item.querystring))
            {
                strLength = item.querystring.Split('&').Length;
            }
            if (strLength == _params.Length)
            {
                //注意__id__代表分页页码,所以须替换成数字才成进行匹配
                if (Regex.IsMatch(string.Format(item.path, _params).Replace("__id__", "1"), item.pattern, RegexOptions.None | RegexOptions.IgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 替换扩展名
        /// </summary>
        private string GetUrlExtension(string urlPage, string staticExtension)
        {
            return Utils.GetUrlExtension(urlPage, staticExtension);
        }

        #endregion
    }
}


text:
layout: post
title: "Assignment 3"
categories: journal
tags: [documentation,sample]
---
As a part of Transaction Management in Microservices, we were interested to venture into the topic of Two Phase Commit. I worked along with Thanmai and Supreeth.

## Architecture:
Consider the same architecture as that of the Event-driven approach. We have an Order Service and a Customer Service with their respective databases. But instead of the Message Broker to communicate the events between the two services, we will talk about the Two-phase commit approach.

***

## Mechanism:
![two-phase-commit](http://www.yusufaytas.com/wp-content/uploads/2012/10/2PhaseCommit.png)

***

## Problem Statement:
In microservices architecture, each microservice has its own private datastore. Different microservices might use different SQL and NoSQL databases. While this database architecture has significant benefits, it creates some distributed data management challenges. The challenge of decentralized data management is how to implement business transactions that maintain eventual consistency.

***

## Possible Solutions:

Method | Source
------- | -------
Event-driven Architecture | [EDA](https://en.wikipedia.org/wiki/Event-driven_architecture)
Two-phase Commit Protocol | [2PC Protocol](https://en.wikipedia.org/wiki/Two-phase_commit_protocol)

***

## Solution Evaluation:
Any transaction made has to go through a transaction manager. This manager ensures that a transaction occurs across all the services (resources). As the name suggests, there are two phases in this mechanism - Commit Request Phase and Commit Phase.

1. Commit request phase (also known as voting phase): The manager sends a _query to commit_ message to all the services. The manager then waits for all the services to vote yes or no. Each of the services will perform the transaction up to the point where they would have to commit. The services reply with _yes_ or an agreement if all they are prepared or _no_ if even if one of the services is not prepared.

2. Commit phase (also knows as completion phase): There can be two conditions here. Either the manager received _yes_ from all the services or at least one of the services voted _no_.

  * Manager received _yes_ from all services: The manager sends a commit message to all the services asking them to commit the transaction. After the commit, the services send an acknowledgement to the manager after which the transaction is complete.

  * Manager received _no_ from one or more of the services: The manager sends a rollback message to all the services asking them to rollback to the state before the actions from the previous phase. After the rollback, the services send an acknowledgement to the manager after which the transaction is undone.

***

## Conclusion:

### Advantages:
- In an environment which has many databases that get affected. It is good to treat them as transactions. Global transactions span on one or more transactional resources, and enlist them all in a single transaction.
- Prepare phase can be considered as a dry-run phase to check if the commit is allowed by all the components involved in the system.

### Disadvantages:
- The transaction manager is a single point of failure. If it fails, then the services will never be able to resolve their transactions.
- This protocol is a blocking protocol. The manager will block till it receives the messages from the services which would imply that the locks and resources held by it will not be released till it receives a reply.
- If any of the services vetoes the commit, then all the services are asked to perform a rollback on their databases. This ensures consistency among partitions. But being a blocking protocol, this mechanism does not ensure good availability.

### CAP Theorem:
We know that web services cannot ensure - _consistency_, _availability_ and _partition tolerance_. They can, at most, support only two out of the three. ACID, as we know, provides consistency for partitioned databases. If we have to achieve availability instead, we can think of BASE (basically available, soft state, eventually consistent). This basically argues that it is better to have availability along with eventual consistency rather than compromising on availability on the whole. As previously discussed, we can implement an _event driven architecture_ to fulfill this purpose.

***

## Implementations and Examples:
- Atomikos:  [Link](https://www.atomikos.com)
- Bitronix:  [Link](https://github.com/bitronix/btm)
- JTA Standalone Transaction Manager: [Link](http://simplejta.sourceforge.net)

***

## Associated Github issues:
- [2 Phase Commit Implementation using Microservice data management #2](https://github.com/airavata-courses/spring17-microservice-data-management/issues/2)

***

## Other References:
- [Configuring Spring and JTA without full java IDE](https://spring.io/blog/2011/08/15/configuring-spring-and-jta-without-full-java-ee/)
- [Base: An Acid Alternative](http://queue.acm.org/detail.cfm?id=1394128)
- [Transaction Managers](http://dorel.vaida.co/2006/10/open-source-jta-transaction-managers.html)

redpajama_set_name: RedPajamaGithub


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<parent>
		<groupId>net.canadensys</groupId>
		<artifactId>canadensys-web-core-parent</artifactId>
		<version>0.9-SNAPSHOT</version>
	</parent>

	<modelVersion>4.0.0</modelVersion>

	<groupId>net.canadensys</groupId>
	<artifactId>canadensys-web-core</artifactId>
	<version>0.9-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>Canadensys web core</name>
	<description>The Canadensys web core library</description>
	<url>http://canadensys.net</url>
	<licenses>
		<license>
			<name>MIT License</name>
			<url>https://raw.github.com/Canadensys/canadensys-web-core/master/LICENSE</url>
			<distribution>repo</distribution>
		</license>
	</licenses>
	<scm>
		<url>git@github.com:Canadensys/canadensys-web-core.git</url>
		<connection>scm:git:git@github.com:Canadensys/canadensys-web-core.git</connection>
		<developerConnection>scm:git:git@github.com:Canadensys/canadensys-web-core.git</developerConnection>
	  <tag>HEAD</tag>
  </scm>

	<developers>
		<developer>
			<name>Christian Gendreau</name>
		</developer>
	</developers>

	<properties>
		<servlet-api.version>3.1.0</servlet-api.version>

		<canadensys-core.version>1.8</canadensys-core.version>
		<freemarker.version>2.3.20</freemarker.version>
		<spring.version>4.1.9.RELEASE</spring.version>
		<reflections.version>0.9.9</reflections.version>
	</properties>

	<prerequisites>
		<maven>3.0</maven>
	</prerequisites>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet-api.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>net.canadensys</groupId>
			<artifactId>canadensys-core</artifactId>
			<version>${canadensys-core.version}</version>
		</dependency>
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>${freemarker.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-webmvc</artifactId>
		    <version>${spring.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-context-support</artifactId>
		    <version>${spring.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.reflections</groupId>
		    <artifactId>reflections</artifactId>
		    <version>${reflections.version}</version>
		</dependency>

		<!-- Spring test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
from django.conf.urls.defaults import *

from revcanonical import views

urlpatterns = patterns(
    '',
    url('^(?P<addr>[0-9A-Za-z]+\.[0-9A-Za-z]+)/$', views.canonical_redirect,
        name="revcanonical"),
)


text:
<!DOCTYPE html>

  <title>overflow on body should not propagate to the viewport when root has overflow</title>

There should be scrollbars for this box -- not for the viewport.

This is filler text.

This is filler text.

This is filler text.

This is filler text.


text:
for API 18+

```kotlin
fun applyDim(@NonNull parent: ViewGroup, dimAmount: Float) {
            val dim = ColorDrawable(Color.BLACK)
            dim.setBounds(0, 0, parent.width, parent.height)
            dim.alpha = (255 * dimAmount).toInt()

            val overlay = parent.overlay
            overlay.add(dim)
        }

        fun clearDim(@NonNull parent: ViewGroup) {
            val overlay = parent.overlay
            overlay.clear()
        }
```

## Reference

[https://stackoverflow.com/a/29950606](https://stackoverflow.com/a/29950606)


text:
.. _Data-QA-QC:

Time Series Data QA/QC
======================

ODM2 Admin can be used as a tool for time series data quality assurance and control. Raw time series can be
copied and then modified with time series result annotations. Portions of time series can be selected and
if values are known to be bad they can be set to not a number 'NaN' while the original values are maintained
in an annotation. The annotation can then also indicate the reason why the value was not good, such as the
instrument was out of calibration.

Let's try it out, we are going to visit the data annotation page for a measurement of water temperature
at the Rio Espiritu Santo Stream House (RESSH), from the `map <http://odm2admin.cuahsi.org/Sandbox/mapdata.html>`_
this is a sampling feature of type 'Stream Gage' labeled RESSH.

   .. image:: /images/RioEspirituSantoStreamGage.png

From Here follow the link to the water temperture read by either the pressure transducer or the DO probe, select the
'Annotate Data' link as shown here:

   .. image:: /images/SelectWaterTempToAnnotate.png

http://odm2admin.cuahsi.org/Sandbox/graphfa/samplingfeature=776/resultidu=16657/popup=Anno/

You can select some of the points by dragging a selection box around them, it should look like this:

   .. image:: /images/RESSH-WaterTemperatureReadings.PNG

With the points selected we can select a new data quality code, enter an annotation, generate a L1, QA/QC level from
a level 0 time series. From a time series that are not raw data (something other then L0) we can set values to Not A
Number (NAN).

  .. image:: /images/AnnotatingData.png

Our Annotated data will then look something like this:

  .. image:: /images/AnnotatedData.png

You can also add or subtract an offset value to a set of points or drift correct them. Drift correcting points will
apply a linear correction so that the first or last point (depending if you select forward or backward) will have the
value entered. The remaining values you selected will have an offset added to them. This offset is proportional to the
points position in the set of points selected.

  .. image:: /images/offsetanddriftcorrect.png

:ref:`5) Data visualization and URL parameters <Data-Visualization>`

* :ref:`ODM2 Admin docs home page<ODM2-Admin>`
* :ref:`Search the docs <search>`


text: Observation profile for basic observation/result for Total Cholesterol (LOINC 14647-2)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MVCDashboard.Domain.Entities;

namespace MVCDashboard.Domain.Abstract
{
	public interface ICachedReleaseQueryRepository
	{
		Releases RetrieveCachedReleaseQueries();
		void RemoveCachedReleaseQueries();
	}
}


text:
Get the GitHub repository from a npm package.

## Installation

```bash
$ npm install npm-to-github --save
```

## Usage

```js
const npmToGitHub = require('npm-to-github');
```

### Get repository name

```js
npmToGitHub.getRepositoryName('npm-to-github')
.then((name) => {
    console.log(name);
})
.catch((error) => {
    console.log(error);
});
```

### Get repository data

```js
npmToGitHub.getRepository('npm-to-github')
.then((data) => {
    console.log(data);
})
.catch((error) => {
    console.log(error);
});
```

## GitHub API rate limit

GitHub API is limited to 60 requests, after which you get an error:

`API rate limit exceeded for a.b.c.d. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)`

A work around is to authenticate. npm-to-github supports [token based authentication](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/). The token doesn't need any scope or permission.

```js
const npmToGitHub = require('npm-to-github');
npmToGitHub.setToken('d5ea195..........................4bde396');
```

## Incompatible API changes! (f34r)

In *1.x* errors where not really errors, only a message.
In *2.x* errors are full `Error` objects.

## License

Released under the [MIT license](https://tldrlegal.com/license/mit-license).


text:
'use strict';

/**
 * @ngdoc directive
 * @name ngfbApp.directive:dateTimePicker
 * @description
 * # dateTimePicker
 */
angular.module('ngfbApp')
  .directive('dateTimePicker', function () {
    return {
      scope: {
        ngModel: '=',
        required: '=ngRequired'

      },
      restrict: 'E',

      templateUrl: 'views/date-time-picker.html',
      link: function (scope, element, attrs, form) {
        scope.hours = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
        scope.minutes = ['00', '15', '30', '45'];
        scope.meridiems = ['AM', 'PM'];
        $('.datepicker').pickadate({
          selectMonths: true, // Creates a dropdown to control month
          selectYears: 15 // Creates a dropdown of 15 years to control year
        });

        var updateDateTime = function () {
          if(scope.date && scope.selectedHour && scope.selectedMinute && scope.selectedMeridiem ) {
            var selectedDateTime = new Date((scope.date.getMonth() + 1) + '/' + scope.date.getDate() + '/' + scope.date.getFullYear() + ' ' + scope.selectedHour + ':' + scope.selectedMinute + ' ' + scope.selectedMeridiem);
            scope.ngModel = Math.floor(selectedDateTime.getTime() / 1000);
          }else{
            scope.ngModel = null;
          }

        };
        $('.datepicker').change(function (e) {
          scope.date = new Date($(e.target).val());
        });
        scope.$watch('date', updateDateTime);
        scope.$watch('selectedHour', updateDateTime);
        scope.$watch('selectedMinute', updateDateTime);
        scope.$watch('selectedMeridiem', updateDateTime);

      }
    };
  })
;


text:
<?php
namespace app\controllers;

use yii\rest\Controller;
use yii\filters\ContentNegotiator;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\api\BaseService;
/**
 *
 * @author Yong
 *
 */
class BaseController extends Controller
{
    /**
     * @var BaseService 逻辑处理服务类
     */
    public $service;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                ],
            ],
            'verbFilter' => [
                'class' => VerbFilter::className(),
                'actions' => $this->verbs(),
            ],
        ];
    }

    /**
     * {@inheritDoc}
     * @see \yii\rest\Controller::afterAction()
     */
    public function afterAction($action, $result)
    {
        $result = parent::afterAction($action, $result);
        return ['code' => 0 ,'message' => '请求成功', 'data' => $result];
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Notifications"
             android:textStyle="bold"
            android:layout_alignParentLeft="true"
            android:textSize="25dp"
            />

        <Switch android:id="@+id/switchNotification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:checked="true"/>

    </RelativeLayout>

    <View android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#ccc"/>

</LinearLayout>


text:
import { injectable, inject } from "inversify";
import { JsonRpcServer, JsonRpcProxy } from '@theia/core';

export const fileSystemWatcherPath = '/services/fs-watcher';

export const FileSystemWatcherServer = Symbol('FileSystemWatcherServer');
export interface FileSystemWatcherServer extends JsonRpcServer<FileSystemWatcherClient> {
    /**
     * Start file watching for the given param.
     * Resolve when watching is started.
     * Return a watcher id.
     */
    watchFileChanges(uri: string, options?: WatchOptions): Promise<number>;

    /**
     * Stop file watching for the given id.
     * Resolve when watching is stopped.
     */
    unwatchFileChanges(watcher: number): Promise<void>;
}

export interface FileSystemWatcherClient {
    /**
     * Notify when files under watched uris are changed.
     */
    onDidFilesChanged(event: DidFilesChangedParams): void;
}

export interface WatchOptions {
    ignored: string[];
}

export interface DidFilesChangedParams {
    changes: FileChange[];
}

export interface FileChange {
    uri: string;
    type: FileChangeType;
}

export enum FileChangeType {
    UPDATED = 0,
    ADDED = 1,
    DELETED = 2
}

export const FileSystemWatcherServerProxy = Symbol('FileSystemWatcherServerProxy')
export type FileSystemWatcherServerProxy = JsonRpcProxy<FileSystemWatcherServer>;

@injectable()
export class ReconnectingFileSystemWatcherServer implements FileSystemWatcherServer {

    protected watcherSequence = 1;
    protected readonly watchParams = new Map<number, {
        uri: string;
        options?: WatchOptions
    }>();
    protected readonly localToRemoteWatcher = new Map<number, number>();

    constructor(
        @inject(FileSystemWatcherServerProxy) protected readonly proxy: FileSystemWatcherServerProxy
    ) {
        this.proxy.onDidOpenConnection(() => this.reconnect());
    }

    protected reconnect(): void {
        for (const [watcher, { uri, options }] of this.watchParams.entries()) {
            this.doWatchFileChanges(watcher, uri, options);
        }
    }

    dispose(): void {
        this.proxy.dispose();
    }

    watchFileChanges(uri: string, options?: WatchOptions): Promise<number> {
        const watcher = this.watcherSequence++;
        this.watchParams.set(watcher, { uri, options });
        return this.doWatchFileChanges(watcher, uri, options);
    }

    protected doWatchFileChanges(watcher: number, uri: string, options?: WatchOptions): Promise<number> {
        return this.proxy.watchFileChanges(uri, options).then(remote => {
            this.localToRemoteWatcher.set(watcher, remote)
            return watcher;
        });
    }

    unwatchFileChanges(watcher: number): Promise<void> {
        this.watchParams.delete(watcher);
        const remote = this.localToRemoteWatcher.get(watcher);
        if (remote) {
            this.localToRemoteWatcher.delete(watcher);
            return this.proxy.unwatchFileChanges(remote);
        }
        return Promise.resolve();
    }

    setClient(client: FileSystemWatcherClient): void {
        this.proxy.setClient(client);
    }

}


text:
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;

--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -
--

CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;

--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -
--

COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';

--
-- Name: unaccent; Type: EXTENSION; Schema: -; Owner: -
--

CREATE EXTENSION IF NOT EXISTS unaccent WITH SCHEMA public;

--
-- Name: EXTENSION unaccent; Type: COMMENT; Schema: -; Owner: -
--

COMMENT ON EXTENSION unaccent IS 'text search dictionary that removes accents';

SET search_path = public, pg_catalog;

SET default_tablespace = '';

SET default_with_oids = false;

--
-- Name: companies; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE companies (
    id integer NOT NULL,
    name character varying(255) NOT NULL,
    description text,
    website character varying(255),
    linkedin character varying(255),
    status character varying(255),
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL,
    slug character varying(255)
);

--
-- Name: companies_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE companies_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

--
-- Name: companies_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE companies_id_seq OWNED BY companies.id;

--
-- Name: companies_locations; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE companies_locations (
    company_id integer,
    location_id integer
);

--
-- Name: companies_markets; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE companies_markets (
    company_id integer,
    market_id integer
);

--
-- Name: dealings; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE dealings (
    id integer NOT NULL,
    deal_id integer,
    buyer_id integer,
    buyer_type character varying(255),
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL
);

--
-- Name: dealings_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE dealings_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

--
-- Name: dealings_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE dealings_id_seq OWNED BY dealings.id;

--
-- Name: deals; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE deals (
    id integer NOT NULL,
    close_date date NOT NULL,
    category character varying(255),
    round character varying(255),
    currency character varying(255),
    amount integer,
    pre_valuation integer,
    source_url text,
    company_id integer,
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL,
    verified boolean
);

--
-- Name: deals_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE deals_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

--
-- Name: deals_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE deals_id_seq OWNED BY deals.id;

--
-- Name: investors; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE investors (
    id integer NOT NULL,
    name character varying(255) NOT NULL,
    description text,
    website character varying(255),
    linkedin character varying(255),
    status character varying(255),
    category character varying(255),
    stage character varying(255),
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL,
    slug character varying(255)
);

--
-- Name: investors_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE investors_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

--
-- Name: investors_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE investors_id_seq OWNED BY investors.id;

--
-- Name: investors_locations; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE investors_locations (
    investor_id integer,
    location_id integer
);

--
-- Name: investors_markets; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE investors_markets (
    investor_id integer,
    market_id integer
);

--
-- Name: locations; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE locations (
    id integer NOT NULL,
    country character varying(255) NOT NULL,
    region character varying(255) NOT NULL,
    city character varying(255) NOT NULL,
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL
);

--
-- Name: locations_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE locations_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

--
-- Name: locations_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE locations_id_seq OWNED BY locations.id;

--
-- Name: markets; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE markets (
    id integer NOT NULL,
    name character varying(255) NOT NULL,
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL
);

--
-- Name: markets_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE markets_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

--
-- Name: markets_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE markets_id_seq OWNED BY markets.id;

--
-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE schema_migrations (
    version character varying(255) NOT NULL
);

--
-- Name: searches; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE searches (
    id integer NOT NULL,
    keywords character varying(255),
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL,
    slug character varying(255)
);

--
-- Name: searches_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE searches_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

--
-- Name: searches_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE searches_id_seq OWNED BY searches.id;

--
-- Name: users; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE users (
    id integer NOT NULL,
    email character varying(255) DEFAULT ''::character varying NOT NULL,
    encrypted_password character varying(255) DEFAULT ''::character varying NOT NULL,
    reset_password_token character varying(255),
    reset_password_sent_at timestamp without time zone,
    remember_created_at timestamp without time zone,
    sign_in_count integer DEFAULT 0,
    current_sign_in_at timestamp without time zone,
    last_sign_in_at timestamp without time zone,
    current_sign_in_ip character varying(255),
    last_sign_in_ip character varying(255),
    full_name character varying(255) NOT NULL,
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL,
    role character varying(255),
    provider character varying(255),
    uid character varying(255)
);

--
-- Name: users_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE users_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

--
-- Name: users_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE users_id_seq OWNED BY users.id;

--
-- Name: versions; Type: TABLE; Schema: public; Owner: -; Tablespace:
--

CREATE TABLE versions (
    id integer NOT NULL,
    item_type character varying(255) NOT NULL,
    item_id integer NOT NULL,
    event character varying(255) NOT NULL,
    whodunnit character varying(255),
    object text,
    created_at timestamp without time zone
);

--
-- Name: versions_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE versions_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

--
-- Name: versions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE versions_id_seq OWNED BY versions.id;

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY companies ALTER COLUMN id SET DEFAULT nextval('companies_id_seq'::regclass);

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY dealings ALTER COLUMN id SET DEFAULT nextval('dealings_id_seq'::regclass);

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY deals ALTER COLUMN id SET DEFAULT nextval('deals_id_seq'::regclass);

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY investors ALTER COLUMN id SET DEFAULT nextval('investors_id_seq'::regclass);

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY locations ALTER COLUMN id SET DEFAULT nextval('locations_id_seq'::regclass);

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY markets ALTER COLUMN id SET DEFAULT nextval('markets_id_seq'::regclass);

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY searches ALTER COLUMN id SET DEFAULT nextval('searches_id_seq'::regclass);

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY users ALTER COLUMN id SET DEFAULT nextval('users_id_seq'::regclass);

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY versions ALTER COLUMN id SET DEFAULT nextval('versions_id_seq'::regclass);

--
-- Name: companies_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY companies
    ADD CONSTRAINT companies_pkey PRIMARY KEY (id);

--
-- Name: dealings_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY dealings
    ADD CONSTRAINT dealings_pkey PRIMARY KEY (id);

--
-- Name: deals_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY deals
    ADD CONSTRAINT deals_pkey PRIMARY KEY (id);

--
-- Name: investors_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY investors
    ADD CONSTRAINT investors_pkey PRIMARY KEY (id);

--
-- Name: locations_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY locations
    ADD CONSTRAINT locations_pkey PRIMARY KEY (id);

--
-- Name: markets_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY markets
    ADD CONSTRAINT markets_pkey PRIMARY KEY (id);

--
-- Name: searches_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY searches
    ADD CONSTRAINT searches_pkey PRIMARY KEY (id);

--
-- Name: users_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY users
    ADD CONSTRAINT users_pkey PRIMARY KEY (id);

--
-- Name: versions_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY versions
    ADD CONSTRAINT versions_pkey PRIMARY KEY (id);

--
-- Name: index_companies_locations_on_company_id_and_location_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_companies_locations_on_company_id_and_location_id ON companies_locations USING btree (company_id, location_id);

--
-- Name: index_companies_locations_on_location_id_and_company_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_companies_locations_on_location_id_and_company_id ON companies_locations USING btree (location_id, company_id);

--
-- Name: index_companies_markets_on_company_id_and_market_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_companies_markets_on_company_id_and_market_id ON companies_markets USING btree (company_id, market_id);

--
-- Name: index_companies_markets_on_market_id_and_company_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_companies_markets_on_market_id_and_company_id ON companies_markets USING btree (market_id, company_id);

--
-- Name: index_companies_on_slug; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE UNIQUE INDEX index_companies_on_slug ON companies USING btree (slug);

--
-- Name: index_dealings_on_buyer_id_and_buyer_type; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_dealings_on_buyer_id_and_buyer_type ON dealings USING btree (buyer_id, buyer_type);

--
-- Name: index_dealings_on_deal_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_dealings_on_deal_id ON dealings USING btree (deal_id);

--
-- Name: index_dealings_on_deal_id_and_buyer_id_and_buyer_type; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE UNIQUE INDEX index_dealings_on_deal_id_and_buyer_id_and_buyer_type ON dealings USING btree (deal_id, buyer_id, buyer_type);

--
-- Name: index_deals_on_company_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_deals_on_company_id ON deals USING btree (company_id);

--
-- Name: index_investors_locations_on_investor_id_and_location_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_investors_locations_on_investor_id_and_location_id ON investors_locations USING btree (investor_id, location_id);

--
-- Name: index_investors_locations_on_location_id_and_investor_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_investors_locations_on_location_id_and_investor_id ON investors_locations USING btree (location_id, investor_id);

--
-- Name: index_investors_markets_on_investor_id_and_market_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_investors_markets_on_investor_id_and_market_id ON investors_markets USING btree (investor_id, market_id);

--
-- Name: index_investors_markets_on_market_id_and_investor_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_investors_markets_on_market_id_and_investor_id ON investors_markets USING btree (market_id, investor_id);

--
-- Name: index_investors_on_slug; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE UNIQUE INDEX index_investors_on_slug ON investors USING btree (slug);

--
-- Name: index_searches_on_slug; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE UNIQUE INDEX index_searches_on_slug ON searches USING btree (slug);

--
-- Name: index_users_on_email; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE UNIQUE INDEX index_users_on_email ON users USING btree (email);

--
-- Name: index_users_on_reset_password_token; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE UNIQUE INDEX index_users_on_reset_password_token ON users USING btree (reset_password_token);

--
-- Name: index_versions_on_item_type_and_item_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE INDEX index_versions_on_item_type_and_item_id ON versions USING btree (item_type, item_id);

--
-- Name: unique_schema_migrations; Type: INDEX; Schema: public; Owner: -; Tablespace:
--

CREATE UNIQUE INDEX unique_schema_migrations ON schema_migrations USING btree (version);

--
-- PostgreSQL database dump complete
--

INSERT INTO schema_migrations (version) VALUES ('20120524190909');

INSERT INTO schema_migrations (version) VALUES ('20120527185513');

INSERT INTO schema_migrations (version) VALUES ('20120527214058');

INSERT INTO schema_migrations (version) VALUES ('20120528033836');

INSERT INTO schema_migrations (version) VALUES ('20120528034729');

INSERT INTO schema_migrations (version) VALUES ('20120528141021');

INSERT INTO schema_migrations (version) VALUES ('20120528182725');

INSERT INTO schema_migrations (version) VALUES ('20120528184644');

INSERT INTO schema_migrations (version) VALUES ('20120528184828');

INSERT INTO schema_migrations (version) VALUES ('20120529161207');

INSERT INTO schema_migrations (version) VALUES ('20120530232227');

INSERT INTO schema_migrations (version) VALUES ('20120602223848');

INSERT INTO schema_migrations (version) VALUES ('20120609233658');

INSERT INTO schema_migrations (version) VALUES ('20120616182949');

INSERT INTO schema_migrations (version) VALUES ('20120709161613');

INSERT INTO schema_migrations (version) VALUES ('20120709212003');

INSERT INTO schema_migrations (version) VALUES ('20120722143007');

INSERT INTO schema_migrations (version) VALUES ('20120722155830');

INSERT INTO schema_migrations (version) VALUES ('20120726130457');

INSERT INTO schema_migrations (version) VALUES ('20120915201401');


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Non-overlapping Layout</title>

Disconnected graph with non-overlap constraints

Since node 'e' is not connected to the rest of the graph, it does not influence the layout of the connected component
        except through constraints.  In this case, we generate constraints to prevent node boxes from overlapping.  Try dragging 'e'
        so that it collides with the other nodes.


text:
/*
 * Globalcode - "The Developers Company"
 *
 * Academia do Java
 *
 */
package br.com.globalcode.aj3.beans;

public class Cliente implements Comparable{

	private String nome;
	private String telefone;
	private String cpf;
	private int id;

	/**
	 * @param nome
	 *            Nome do cliente
	 * @param telefone
	 *            Telefone do cliente
	 * @param cpf
	 *            CPF do cliente
	 * @param id
	 *            ID do cliente
	 */
	public Cliente(String nome, String telefone, String cpf, int id) {
		this(nome, telefone, cpf);
		this.id = id;
	}

	/**
	 * Este construtor podera ser utilizado quando o id do cliente precisar ser
	 * atribuido depois, como por exemplo quando e necessario criar o cliente
	 * para salvar no banco de dados, onde o id e gerado automaticamente.
	 *
	 * @param nome
	 *            Nome do cliente
	 * @param telefone
	 *            Telefone do cliente
	 * @param cpf
	 *            CPF do cliente
	 *
	 */
	public Cliente(String nome, String telefone, String cpf) {
		this.nome = nome;
		this.telefone = telefone;
		this.cpf = cpf;
	}

	/**
	 * @return CPF do Cliente
	 */
	public String getCpf() {
		return cpf;
	}

	/**
	 * @return ID do cliente
	 */
	public int getId() {
		return id;
	}

	/**
	 * @return Nome do cliente
	 */
	public String getNome() {
		return nome;
	}

	/**
	 * @return Telefone do cliente
	 */
	public String getTelefone() {
		return telefone;
	}

	/**
	 * @param cpf
	 *            CPF do cliente
	 */
	public void setCpf(String cpf) {
		this.cpf = cpf;
	}

	/**
	 * @param id
	 *            ID do cliente
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @param nome
	 *            Nome do cliente
	 */
	public void setNome(String nome) {
		this.nome = nome;
	}

	/**
	 * @param telefone
	 *            Telefone do cliente
	 */
	public void setTelefone(String telefone) {
		this.telefone = telefone;
	}

	/**
	 * toString para impressao dos dados do cliente.
	 */
	public String toString() {
		String cliente = " ID [" + this.id + "]";
		cliente += this.nome + "\t CPF (" + this.cpf + " ) \t";
		cliente += "- Tel: {" + this.telefone + "}";
		return cliente;
	}

	/*
	 * Para verificar que elementos repetidos nao podem ser inseridos no TreeSet
	 * descomente o metodo hashCode e o metodo equals
	 */

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((cpf == null) ? 0 : cpf.hashCode());
		return result;
	}

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Cliente other = (Cliente) obj;
		if (cpf == null) {
			if (other.cpf != null)
				return false;
		} else if (!cpf.equals(other.cpf))
			return false;
		return true;
	}
	public int compareTo(Object p){
		if(p instanceof Cliente){
			Cliente i = (Cliente) p;
			return this.cpf.compareTo(i.getCpf());
		}
		return 1;
	}

}


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module("dekorateApp", ['nvd3', 'ngMaterial']).controller("expensesController", function ($scope, $http) {
    /*
     Sample data picked if database collection of expenses is empty
     */
    var sampleData = [
        {
            'name': 'Rent',
            'type': 'cash',
            'price': '500',
            'date': '2016-04-11'
        },
        {
            'name': 'Insurance',
            'type': 'credit',
            'price': '100',
            'date': '2016-04-11'
        },
        {
            'name': 'Automobile',
            'type': 'credit',
            'price': '100',
            'date': '2016-04-11'
        },
        {
            'name': 'Utilities',
            'type': 'cash',
            'price': '100',
            'date': '2016-03-11'
        },
        {
            'name': 'Insurance',
            'type': 'credit',
            'price': '100',
            'date': '2016-01-11'
        }
    ];
    //variable to store the expenses
    $scope.expensesTable = [];
    //Get request for fetching the past expenses from database
    $http({
        url: 'http://localhost:8080/expenses',
        method: 'GET',
    }).then(function (expenses) {
        if (expenses.data.length != 0) {
            $scope.expensesTable = expenses.data;
            drawExpenseCharts();
        }
        else {
            $scope.expensesTable = sampleData;
            drawExpenseCharts();
        }
    }, function (err) {
        $scope.expensesTable = sampleData;
        drawExpenseCharts();
        console.log(err);
    });

    //For adding new expenses
    $scope.addRow = function () {
        if ($scope.name != null && $scope.type != null && $scope.price != null && $scope.date != null) {
            $scope.expensesTable.push({
                'name': $scope.name,
                'type': $scope.type,
                'price': $scope.price,
                'date': $scope.date
            });
            //Post request sent to expenses api for adding
            $http({
                url: 'http://localhost:8080/expenses',
                method: 'POST',
                data: {
                    'name': $scope.name,
                    'type': $scope.type,
                    'price': $scope.price,
                    'date': $scope.date
                }
            }).then(function (expenses) {

            }, function (err) {
                console.log(err);
            });
            var form = document.getElementsByName('expense-form')[0];
            form.reset();  // Reset
        }
        drawExpenseCharts();
    };
    //Deletes expense
    $scope.removeRow = function (index) {
        $http({
            url: 'http://localhost:8080/expenses',
            method: 'DELETE',
            headers: {
                Accept: "application/x-www-form-urlencoded; charset=utf-8",
                "Content-Type": "application/json; charset=utf-8"
            },
            data: {'id': $scope.expensesTable[index]._id}
        }).then(function (expenses) {
        }, function (err) {
            console.log(err);
        });
        $scope.expensesTable.splice(index, 1);
        drawExpenseCharts();
    };
    //Piechart Configurations
    $scope.pieChartOptions = {
        "chart": {
            "type": "pieChart",
            "height": 500,
            "showLabels": true,
            "duration": 500,
            x: function (d) {
                return d.name;
            },
            y: function (d) {
                return d.amount;
            },
            "labelThreshold": 0.01,
            "labelSunbeamLayout": true,
            "legend": {
                "margin": {
                    "top": 5,
                    "right": 35,
                    "bottom": 5,
                    "left": 0
                }
            },
            labelType: 'percent',
            valueFormat: function (d) {
                return d3.format(',.5f')(d);
            }
        },
        title: {
            enable: true,
            text: 'Expense Summary'
        }
    };

    //Bar chart configurations
    $scope.barChartOptions = {
        chart: {
            type: 'multiBarChart',
            height: 450,
            margin: {
                top: 20,
                right: 20,
                bottom: 45,
                left: 45
            },
            clipEdge: true,
            //staggerLabels: true,
            duration: 500,
            grouped: true,
            xAxis: {
                axisLabel: 'Month-Year',
                showMaxMin: false,
                tickFormat: function (d) {
                    return $scope.dateData[d].key;
                }
            },
            yAxis: {
                axisLabel: 'Price',
                axisLabelDistance: -20,
                tickFormat: function (d) {
                    return d3.format(',.1f')(d);
                }
            }
        },
        title: {
            enable: true,
            text: 'Expenses by Month'
        }
    };

    //To sort expense data
    function custom_sort(a, b) {
        return new Date(a.date).getTime() - new Date(b.date).getTime();
    }

    //Data for pie chart
    function pieChartDataGenerator() {
        var categoryData = d3.nest()
            .key(function (d) {
                return d.name;
            }).entries($scope.expensesTable);
        $scope.cummulativeCategoryData = [];
        for (var i = 0; i < categoryData.length; i++) {
            var amount = 0;
            for (var j = 0; j < categoryData[i].values.length; j++) {
                amount += parseInt(categoryData[i].values[j].price);
            }
            var element = {};
            element.name = categoryData[i].key;
            element.amount = amount;
            $scope.cummulativeCategoryData.push(element);
        }
    };
    //Data for bar chart
    var barChartDataGenerator = function () {
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
        //categorising the data for each month in a year(Month-year as key)
        $scope.dateData = d3.nest()
            .key(function (d) {
                return months[(new Date(d.date)).getUTCMonth()] + '-' + new Date(d.date).getUTCFullYear();
            }).entries($scope.expensesTable);
        //Converting the expenses table data to be based on expense type as keys and corresponding aggregated values to each month and year
        var finalData = [];
        var element = {};
        element.key = 'cash';
        element.values = [];
        finalData.push(element);
        var element = {};
        element.key = 'credit';
        element.values = [];
        finalData.push(element);
        for (var i = 0; i < $scope.dateData.length; i++) {
            var cash = 0;
            var credit = 0;
            for (var j = 0; j < $scope.dateData[i].values.length; j++) {
                if ($scope.dateData[i].values[j].type == "cash") {
                    cash += parseInt($scope.dateData[i].values[j].price);
                }
                else {
                    credit += parseInt($scope.dateData[i].values[j].price);
                }
            }
            var element = {};
            element.date = $scope.dateData[i].key;
            element.price = cash;
            finalData[0].values.push(element);
            var element = {};
            element.date = $scope.dateData[i].key;
            element.price = credit;
            finalData[1].values.push(element);
        }
        var k = 0;
        var type = ['cash', 'credit'];
        //Converting the data fetched based on types to corresponding axis values
        $scope.barData = d3.range(2).map(function () {
            var a = finalData[k];
            k++;
            return a.values.map(stream_index);
        }).map(function (data, i) {
            return {
                key: type[i],
                values: data
            };
        });
    };

    // Converts bar chart data points to X,Y co-ordinates
    function stream_index(d, i) {
        return {x: i, y: d.price};
    }

    // Common function to draw bar and pie charts
    function drawExpenseCharts() {
        $scope.expensesTable.sort(custom_sort);
        barChartDataGenerator();
        pieChartDataGenerator();
    };
});


text:
package br.org.sae.model;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "tbdisciplina")
public class Disciplina extends Entidade {

	private static final long serialVersionUID = 1L;

	@NotNull
	private String nome;
	private String sigla;
	private double cargaSemanal;

	@ManyToOne
	@JoinColumn(name="modulo")
	private Modulo modulo;

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public String getSigla() {
		return sigla;
	}

	public void setSigla(String sigla) {
		this.sigla = sigla;
	}

	public double getCargaSemanal() {
		return cargaSemanal;
	}

	public void setCargaSemanal(double cargaSemanal) {
		this.cargaSemanal = cargaSemanal;
	}

	public Modulo getModulo() {
		return modulo;
	}

	public void setModulo(Modulo modulo) {
		this.modulo = modulo;
	}

}


text:
genRandStr(){
    cat /dev/urandom | tr -dc [:alnum:] | head -c $1
}
#Set some vars
_database_password_=root
_judger_socket_port_=2333
_judger_socket_password_=$(genRandStr 32)
_main_judger_password_=$(genRandStr 32)

getAptPackage(){
    printf "\n\n==> Getting environment packages\n"
    #Set MySQL root password
    export DEBIAN_FRONTEND=noninteractive
    (echo "mysql-server mysql-server/root_password password $_database_password_";echo "mysql-server mysql-server/root_password_again password $_database_password_") | debconf-set-selections
    #Update apt sources and install
    dpkg -s gnupg 2>/dev/null || (apt-get update && apt-get install -y gnupg)
    echo "deb http://ppa.launchpad.net/stesie/libv8/ubuntu bionic main" | tee /etc/apt/sources.list.d/stesie-libv8.list && apt-key adv --keyserver keyserver.ubuntu.com --recv-keys D858A0DF
    apt-get update && apt-get install -y vim ntp zip unzip curl wget apache2 libapache2-mod-xsendfile libapache2-mod-php php php-dev php-pear php-zip php-mysql php-mbstring mysql-server cmake fp-compiler re2c libv8-7.5-dev libyaml-dev python python3 python3-requests openjdk-8-jdk openjdk-11-jdk
    #Install PHP extensions
    yes | pecl install yaml
    git clone https://github.com/phpv8/v8js.git --depth=1 /tmp/pear/download/v8js-master && cd /tmp/pear/download/v8js-master
    phpize && ./configure --with-php-config=/usr/bin/php-config --with-v8js=/opt/libv8-7.5 && make install && cd -
}

setLAMPConf(){
    printf "\n\n==> Setting LAMP configs\n"
    #Set Apache UOJ site conf
    cat >/etc/apache2/sites-available/000-uoj.conf <<UOJEOF
<VirtualHost *:80>
    #ServerName local_uoj.ac
    ServerAdmin opensource@uoj.ac
    DocumentRoot /var/www/uoj

    SetEnvIf Request_URI "^/judge/.*$" judgelog
    #LogLevel info ssl:warn
    ErrorLog \${APACHE_LOG_DIR}/uoj_error.log
    CustomLog \${APACHE_LOG_DIR}/uoj_judge.log common env=judgelog
    CustomLog \${APACHE_LOG_DIR}/uoj_access.log combined env=!judgelog

    XSendFile On
    XSendFilePath /var/uoj_data
    XSendFilePath /var/www/uoj/app/storage
    XSendFilePath /opt/uoj/judger/uoj_judger/include
</VirtualHost>
UOJEOF
    #Enable modules and make UOJ site conf enabled
    a2ensite 000-uoj.conf && a2dissite 000-default.conf
    a2enmod rewrite headers && sed -i -e '172s/AllowOverride None/AllowOverride All/' /etc/apache2/apache2.conf
    #Create UOJ session save dir and make PHP extensions available
    mkdir --mode=733 /var/lib/php/uoj_sessions && chmod +t /var/lib/php/uoj_sessions
    sed -i -e '912a\extension=v8js.so\nextension=yaml.so' /etc/php/7.4/apache2/php.ini
    #Set MySQL user directory and connection config
    usermod -d /var/lib/mysql/ mysql
    cat >/etc/mysql/mysql.conf.d/uoj_mysqld.cnf <<UOJEOF
[mysqld]
default-time-zone='+8:00'
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
init_connect='SET NAMES utf8mb4'
init_connect='SET collation_connection = utf8mb4_unicode_ci'
skip-character-set-client-handshake
sql-mode=ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
UOJEOF
}

setWebConf(){
    printf "\n\n==> Setting web files\n"
    #Set webroot path
    ln -sf /opt/uoj/web /var/www/uoj
    chown -R www-data /var/www/uoj/app/storage
    #Set web config file
    php -a <<UOJEOF
\$config = include '/var/www/uoj/app/.default-config.php';
\$config['database']['password']='$_database_password_';
\$config['judger']['socket']['port']='$_judger_socket_port_';
file_put_contents('/var/www/uoj/app/.config.php', "<?php\nreturn ".str_replace('\'_httpHost_\'','UOJContext::httpHost()',var_export(\$config, true)).";\n");
UOJEOF
    #Import MySQL database
    service mysql restart
    mysql -u root --password=$_database_password_ <../db/app_uoj233.sql
    echo "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$_database_password_';" | mysql -u root --password=$_database_password_
}

setJudgeConf(){
    printf "\n\n==> Setting judger files\n"
    #Add local_main_judger user
    useradd -m local_main_judger && usermod -a -G www-data local_main_judger
    #Set uoj_data path
    mkdir -p /var/uoj_data/upload
    chown -R www-data:www-data /var/uoj_data
    #Compile uoj_judger and set runtime
    chown -R local_main_judger:local_main_judger /opt/uoj/judger
    su local_main_judger <<EOD
ln -s /var/uoj_data /opt/uoj/judger/uoj_judger/data
cd /opt/uoj/judger && chmod +x judge_client
cat >uoj_judger/include/uoj_work_path.h <<UOJEOF
#define UOJ_WORK_PATH "/opt/uoj/judger/uoj_judger"
#define UOJ_JUDGER_BASESYSTEM_UBUNTU1804
#define UOJ_JUDGER_PYTHON3_VERSION "3.8"
#define UOJ_JUDGER_FPC_VERSION "3.0.4"
UOJEOF
cd uoj_judger && make -j$(($(nproc) + 1))
EOD
    #Set judge_client config file
    cat >../../judger/.conf.json <<UOJEOF
{
    "uoj_protocol": "http",
    "uoj_host": "127.0.0.1",
    "judger_name": "main_judger",
    "judger_password": "_main_judger_password_",
    "socket_port": $_judger_socket_port_,
    "socket_password": "_judger_socket_password_"
}
UOJEOF
    chmod 600 ../../judger/.conf.json && chown local_main_judger ../../judger/.conf.json
}

initProgress(){
    printf "\n\n==> Doing initial config and start service\n"
    #Replace password placeholders
    sed -i -e "s/_main_judger_password_/$_main_judger_password_/g" -e "s/_judger_socket_password_/$_judger_socket_password_/g" /opt/uoj/judger/.conf.json
    sed -i -e "s/salt0/$(genRandStr 32)/g" -e "s/salt1/$(genRandStr 16)/g" -e "s/salt2/$(genRandStr 16)/g" -e "s/salt3/$(genRandStr 16)/g" -e "s/_judger_socket_password_/$_judger_socket_password_/g" /var/www/uoj/app/.config.php
    #Import judge_client to MySQL database
    service mysql start
    echo "insert into judger_info (judger_name, password) values (\"main_judger\", \"$_main_judger_password_\")" | mysql app_uoj233 -u root --password=$_database_password_
    #Using cli upgrade to latest
    php /var/www/uoj/app/cli.php upgrade:latest
    #Start services
    service ntp restart
    service mysql restart
    service apache2 restart
    su local_main_judger -c '/opt/uoj/judger/judge_client start'
    #Touch SetupDone flag file
    touch /var/uoj_data/.UOJSetupDone
    printf "\n\n***Installation complete. Enjoy!***\n"
}

prepProgress(){
    getAptPackage;setLAMPConf;setWebConf;setJudgeConf
}

if [ $# -le 0 ]; then
    echo 'Installing UOJ System bundle...'
    prepProgress;initProgress
fi
while [ $# -gt 0 ]; do
    case "$1" in
        -p | --prep)
            echo 'Preparing UOJ System bundle environment...'
            prepProgress
        ;;
        -i | --init)
            echo 'Initing UOJ System bundle...'
            initProgress
        ;;
        -? | --*)
            echo "Illegal option $1"
        ;;
    esac
    shift $(( $#>0?1:0 ))
done


text:
({
PickerCheckBox_OK: "OK",
PickerCheckBox_Cancel: "Annuler",
PickerList_OK: "OK",
PickerList_Cancel: "Annuler",
PickerListSearch_Search: "Recherche",
PickerListSearch_OK: "OK",
PickerListSearch_Cancel: "Annuler",
PickerListSearch_Value: "Valeur",
PickerListSearch_Values: "Valeurs",
PickerName_Search: "Recherche",
PickerName_Add: "Ajouter",
PickerName_Remove: "Retirer",
PickerName_RemoveAll: "Tout retirer",
PickerName_OK: "OK",
PickerName_Cancel: "Annuler",
PickerName_SearchIn: "Rechercher dans",
PickerName_SearchFor: "Rechercher",
PickerName_unSelectedListLabel: "Liste des valeurs \u00e0 s\u00e9lectionner",
PickerName_selectedListLabel: "Liste de valeurs s\u00e9lectionn\u00e9es"
})


text:
from sprox.viewbase import ViewBase
from sprox.test.base import setup_database, widget_children, widget_is_type
from sprox.test.model import User
from sprox.sa.widgetselector import SAWidgetSelector
from nose.tools import raises, eq_

try:
    from tw2.core import Widget
    from tw2.forms import TextField, HiddenField
except:
    from tw.forms import TextField, HiddenField, Widget

session = None
engine  = None
connection = None
trans = None
def setup():
    global session, engine, metadata, trans
    session, engine, metadata = setup_database()

class DummyWidgetSelector(object):
    def select(self, *args, **kw):
        return TextField

class DummyMetadata(object):

    def __init__(self, provider, entity):
        self.entity = entity
        self.provider = provider

    def keys(self):
        return self.provider.get_fields(self.entity)

    def __getitem__(self, name):
        return self.provider.get_field(self.entity, name)

class DummyWidget(Widget):
    params = ['test_param']

class UserView(ViewBase):
    __entity__ = User
    __metadata_type__ = DummyMetadata
    __widget_selector__ = SAWidgetSelector()

class TestViewBase:
    def setup(self):
        self.base = UserView()

    def test_create(self):
        pass

    def test__fields__(self):
        eq_(['_password', 'created', 'display_name', 'email_address', 'groups', 'password', 'town', 'town_id', 'user_id', 'user_name'],
            sorted(self.base.__fields__))

    def test__widget__(self):
        if not hasattr(Widget, 'req'):
            eq_(None, self.base.__widget__())
        else:
            assert widget_is_type(self.base.__widget__(), Widget)

    def test_widget_with_attrs(self):
        class UserView(ViewBase):
            __entity__ = User
            __metadata_type__ = DummyMetadata
            __field_attrs__ = {'password':{'class':'mypassclass'}}
            __widget_selector_type__ = DummyWidgetSelector

        user_view = UserView()

        widget = user_view.__widget__
        child = widget_children(widget)['password']

        assert 'class' in child.attrs
        eq_(child.attrs['class'], 'mypassclass')

    def test_hidden_fields(self):
        class UserView(ViewBase):
            __entity__ = User
            __metadata_type__ = DummyMetadata
            __hide_fields__ = ['password']

        user_view = UserView()
        widget = user_view.__widget__
        child = widget_children(widget)['password']
        assert widget_is_type(child, HiddenField), child.__class__

    def test_custom_field(self):
        class UserView(ViewBase):
            __entity__ = User
            __metadata_type__ = DummyMetadata
            __field_widgets__ = {'password':TextField(id='password')}

        user_view = UserView()
        widget = user_view.__widget__
        child =  widget_children(widget)['password']
        assert widget_is_type(child, TextField), child.__class__

    def test_custom_with_none(self):
        class UserView(ViewBase):
            __entity__ = User
            __metadata_type__ = DummyMetadata
            __add_fields__ = {'password':None}

        user_view = UserView()
        widget = user_view.__widget__
        child = widget_children(widget)['password']
        assert widget_is_type(child, Widget), str(child.__class__)

    def test_omit_fields(self):
        class UserView(ViewBase):
            __entity__ = User
            __metadata_type__ = DummyMetadata
            __omit_fields__ = ['password']

        user_view = UserView()
        widget = user_view.__widget__
        assert 'password' not in  list(widget_children(widget).keys())

    def test_bad_fieldname_in_limit(self):
        class UserView(ViewBase):
            __entity__ = User
            __metadata_type__ = DummyMetadata
            __limit_fields__ = ['junk']

        user_view = UserView()
        widget = user_view.__widget__
        assert 'junk' not in  list(widget_children(widget).keys())

    def test_widget_attrs(self):
        class UserView(ViewBase):
            __entity__ = User
            __metadata_type__ = DummyMetadata
            __field_widget_args__ = {'password':{'test_param':'crazy_param'}}
            password = DummyWidget

        user_view = UserView()
        widget = user_view.__widget__
        assert  widget_children(widget)['password'].test_param == 'crazy_param'

    def test_widget_attrs_hidden_field(self):
        class UserView(ViewBase):
            __entity__ = User
            __metadata_type__ = DummyMetadata
            __field_widget_args__ = {'password':{'css_classes':['crazy_param']}}
            __hide_fields__ = ['password']

        user_view = UserView()
        widget = user_view.__widget__
        assert  widget_children(widget)['password'].css_classes == ['crazy_param'], widget.children['password'].css_classes

    def _test_enum_field(self):
        class EnumView(ViewBase):
            __entity__ = ModelWithEnum
            __metadata_type__ = DummyMetadata

        enum_view = EnumView()
        widget = enum_view.__widget__
        #assert widget.children['password'].css_classes == ['crazy_param'], widget.children['password'].css_classes


text:
I am hungry and I want to eat pizza. I take my car and go to the nearest pizzeria. After a couple of minutes looking at the menu, I do not find what I want. So I finally ask for a custom pizza that will be prepared on the fly. I am not quite sure of the ingredients I want, but let's try to make a tasty pizza!

# Problem

A custom pizza could be anything. Ingredients will be added one by one to produce something unique, depending on my choices.
Here a pizza is an object that is built at runtime, which means that we cannot have an exhaustive constructor with all possible ingredients as parameters.

# Solution

The idea is to "augment" a basic product (such as a Margherita) with some extras (bacon, peppers, ...) using the Decorator design pattern. To make this working, we need:

  * An object literal to represent a basic pizza (Margherita)
  * Two factory functions that take a (basic or already decorated) pizza as parameter and return a new decorated pizza (with bacon or peppers)

![Decorator (idiomatic)](Decorator.png)

N.B. In JavaScript, there are many ways to add new functionalities to an object. This implementation of the Decorator pattern is only one solution among an infinity of possibilities. Moreover, this pattern should not be confused with function decorators which are a bit different and serve another purpose.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include layout="@layout/titlebar_base" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="20dp" >

        <EditText
            android:id="@+id/etPhoneNum_f"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/phone_number"
            android:inputType="phone"
            android:singleLine="true" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <EditText
                android:id="@+id/etValidate_f"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:hint="@string/input_validate_code"
                android:inputType="number"
                android:singleLine="true" />

            <Button
                android:id="@+id/btnGetCode_f"
                style="@style/base_btn"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text="@string/get_code"
                android:textSize="14sp" />
        </LinearLayout>

        <EditText
            android:id="@+id/etNewPass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/your_new_pass"
            android:inputType="textPassword"
            android:singleLine="true" />

        <EditText
            android:id="@+id/etNewPassAgain"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/input_new_pass_again"
            android:inputType="textPassword"
            android:singleLine="true" />

        <Button
            android:id="@+id/btnSubmit_f"
            style="@style/base_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/submit" />
    </LinearLayout>

</LinearLayout>


text:
![Screenshot of the add-on](doc/travis-lite-screenshot.png)

When I get linked to a [travis-ci.org](https://travis-ci.org) page, my computer
sometimes isn't able to handle the awesomeness of the JS on the page. I'll
often want to just hit [travis-lite.com](http://travis-lite.com) instead. I got
lazy to change the URL and wrote this add-on.

If you find it helpful, I'm glad to be of help. Please file bugs.


text:
require 'seth/resource/package'
require 'seth/provider/package/windows'
require 'seth/win32/error' if RUBY_PLATFORM =~ /mswin|mingw|windows/

class Seth
  class Resource
    class WindowsPackage < Seth::Resource::Package

      provides :package, :on_platforms => ["windows"]

      def initialize(name, run_context=nil)
        super
        @allowed_actions = [ :install, :remove ]
        @provider = Seth::Provider::Package::Windows
        @resource_name = :windows_package
        @source ||= source(@package_name)

        # Unique to this resource
        @installer_type = nil
        @timeout = 600
        # In the past we accepted return code 127 for an unknown reason and 42 because of a bug
        @returns = [ 0 ]
      end

      def installer_type(arg=nil)
        set_or_return(
          :installer_type,
          arg,
          :kind_of => [ String ]
        )
      end

      def timeout(arg=nil)
        set_or_return(
          :timeout,
          arg,
          :kind_of => [ String, Integer ]
        )
      end

      def returns(arg=nil)
        set_or_return(
          :returns,
          arg,
          :kind_of => [ String, Integer, Array ]
        )
      end

      def source(arg=nil)
        if arg == nil && self.instance_variable_defined?(:@source) == true
          @source
        else
          raise ArgumentError, "Bad type for WindowsPackage resource, use a String" unless arg.is_a?(String)
          Seth::Log.debug("#{package_name}: sanitizing source path '#{arg}'")
          @source = ::File.absolute_path(arg).gsub(::File::SEPARATOR, ::File::ALT_SEPARATOR)
        end
      end
    end
  end
end


text:
<?xml version='1.0' encoding='UTF-8'?>
<!--
 Copyright 2016 - 2021 Acosix GmbH

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="${moduleId}.basePropertyOrderedNodeBatchWorkProvider"
        class="${javaPackageName}.batch.PropertyOrderedTransactionalNodeBatchWorkProvider" abstract="true">
        <property name="namespaceService" ref="NamespaceService" />
        <property name="dictionaryService" ref="DictionaryService" />
        <property name="searchService" ref="SearchService" />
    </bean>

    <bean id="${moduleId}.baseBulkQueryNodeBatchWorkProvider" class="${javaPackageName}.batch.BulkQueryNodeBatchWorkProvider"
        abstract="true">
        <property name="searchService" ref="SearchService" />
    </bean>

    <import resource="classpath:alfresco/module/${moduleId}/context/bootstrap-context.xml" />
    <import resource="classpath:alfresco/module/${moduleId}/context/action-context.xml" />
    <import resource="classpath:alfresco/module/${moduleId}/context/job-context.xml" />
    <import resource="classpath:alfresco/module/${moduleId}/context/webscripts-context.xml" />
</beans>


text:
https://github.com/Marly1995/beta-game

Swords of Turing is a two player sword fighting combat game created by a group of university
students. This game features a simple yet intuitive control system in which the attacks and the defences
can have directional inputs as well, meaning it takes more skill to block an attack or to land an attack correctly
onto your opponent.

    Name
    Student ID

    Marlon Gilliam
    14471455

    Benjamin Stock
    13457465

    Emmanuel Uanseru
    13454941

    Stefano Rinaldi
    14480397

    Benjamin Rogers
    14470874

    Matthew Webster
    13466955

###Changelog

#####April 29th
	Additional AI features
		Decay of blocking chance
#####April 17th
	Implemtation of  base AI
#####April 7th
	Completion of Animations
	Bug Fixing Animation Issues
#####April 6th
	Implemented Health and Stamina Bars
	Started Implementation of Animations
	Combined Source Files
	Fixed Stamina Bug (Stefano sole bug fixer)
	Implemented Background Image
#####March 16th
	Updated Blocking Mechanic
	Now drains additional stamina when attacked
	Implemented all Basic States
	Updated Graphics Dependency Libraries for Main Branch
	Added Multiple Player Input (2 Player)
	Simultaneous Attacks can now be Handled
#####March 9th
	Updated ReadMe (x76)
	Initial Animation Testing
	Initial Branch Created

###News
	A basic changelog, intended for users

###Bugs
	Animations dont always reset. - 01/04/16

###Future Updates
	Custom Music and Sound Effects
	Character Movement
	Ducking and Jumping
	Victory Animations/Taunts and Dances
	Different Characters
	Character Customisation

###Installation
No installation needed, just run the SwordsOfTuring.exe file.

###Copying/License
Swords of Turing is Open Sourced and licensed under the GPL GNU

##Gameplay Video


text:
package org.outerj.daisy.diff.html.ancestor;

public class ChangeText {

    private int maxNbCharsPerLine;

    private StringBuilder txt = new StringBuilder();

    public final static String newLine = "
";

    private int charsThisLine = 0;

    public ChangeText(int maxNbCharsPerLine) {
        this.maxNbCharsPerLine = maxNbCharsPerLine;
    }

    public synchronized void addText(String s) {
        s = clean(s);

        if (s.length() + charsThisLine > maxNbCharsPerLine) {
            addTextCarefully(s);
        } else {
            addToLine(s);
        }
    }

    private void addToLine(String s) {
      txt.append(s);
      charsThisLine += s.length();
    }

    public synchronized void addHtml(String s) {
        txt.append(s);
        if (s.contains("
") || s.contains("
") || s.contains("
")) {
            charsThisLine = 0;
        }
    }

    private synchronized void addTextCarefully(String s) {

        int firstSpace = s.indexOf(" ");
        if (firstSpace < 0) { //  Next word is the whole string.
            if (s.length() < maxNbCharsPerLine) {
              //  If the word will fit on a standard output line, by itself, get a new line and put it out.
              if (charsThisLine > 0)
                addNewLine();
              addText(s);
            } else {
              addNewLine();
              addTextBrokenAcrossLines(s);
            }
        } else if (firstSpace + 1 >= maxNbCharsPerLine){
          //  The first word in s won't fit on a line, break it across several lines
          if (charsThisLine > 0)
            addNewLine();
          addTextBrokenAcrossLines(s.substring(0, firstSpace + 1));
          if (firstSpace + 1 < s.length())
            addText(s.substring(firstSpace + 1, s.length()));
        } else if (firstSpace + 1 + charsThisLine > maxNbCharsPerLine) {
          //  The new word won't fit on the current line.
          addNewLine();
          addText(s);
        } else {
            addText(s.substring(0, firstSpace + 1));
            if (firstSpace + 1 < s.length())
                addTextCarefully(s.substring(firstSpace + 1, s.length()));
        }
    }

    private void addTextBrokenAcrossLines(String s) {
      assert (s.indexOf(' ') >= 0 && s.length() > maxNbCharsPerLine);
      int firstPart = Math.min(s.length(), maxNbCharsPerLine
              - charsThisLine);

      addText(s.substring(0, firstPart));

      addNewLine();
      addText(s.substring(firstPart, s.length()));
    }

    public synchronized void addNewLine() {
        addHtml(newLine);
        charsThisLine = 0;
    }

    @Override
    public String toString() {
        return txt.toString();
    }

    private String clean(String s) {
        return s.replaceAll("\n", "").replaceAll("\r", "").replaceAll("<",
                "<").replaceAll(">", ">").replaceAll("'", "'")
                .replaceAll("\"", """);
    }
}


text:
'use strict';

import _ from 'underscore';
import { combineReducers } from 'redux';
import { LOGOUT } from 'app/actions/auth';
import {
  SHOW_DROPDOWN,
  HIDE_DROPDOWN
} from 'app/actions/dropdowns';
import { API_GET_TRIP_REQUEST } from 'app/actions/trips';
import {
  dropdownComponents,
  initialDropdownState
} from 'app/constants';
const { addTripIdeas, filterTripIdeas } = dropdownComponents;

function createDropdownReducer(id) {
  return function reducer(state = initialDropdownState, action) {
    if (action.dropdownId && action.dropdownId !== id) {
      return state;
    }

    switch (action.type) {
      case SHOW_DROPDOWN:
        return {
          ...state,
          showDropdown: true
        };
      case HIDE_DROPDOWN:
        return {
          ...state,
          showDropdown: false
        };
      case API_GET_TRIP_REQUEST:
      case LOGOUT:
        return initialDropdownState;
    }

    return state;
  }
}

const dropdownsState = combineReducers({
  [addTripIdeas]: createDropdownReducer(addTripIdeas),
  [filterTripIdeas]: createDropdownReducer(filterTripIdeas)
});

export default dropdownsState;


text:
package com.greensnow25.geometry;

/**
 * public class RunPaint.
 * @author greensnow25.
 * @since 18/01/17.
 * @version 2.7.
 */
public class RunPaint {
    /**
     * main.
     * @param args string.
     */
    public static void main(String[] args) {

        Shape tr = new Triangle(5);
        Shape sq = new Square(5);

        Paint paint = new Paint();

        System.out.println(paint.draw(tr));
        System.out.println(paint.draw(sq));

    }
}


text:
package org.eclipse.bpel.model.reordering;

import java.util.List;

import org.eclipse.wst.wsdl.ExtensibleElement;

public interface IExtensibilityElementListHandler {

	void orderList(ExtensibleElement parent, List tempList);

}


text:
# TURN - MiniTest Reporters [![Build status](https://api.travis-ci.org/turn-project/turn.png)](https://travis-ci.org/turn-project/turn)
    by Tim Pease & Trans
    http://rubygems.org/gems/turn

## TURN is no longer being maintained!

Ruby's built-in test framework has changed so frequently (and rather poorly)
over the last few years that it has been a relative nightmare to try keep Turn
working. From the deprecation of Test::Unit and the switch to MiniTest and thru
all the many API changes made to MiniTest itself (we're at major version 5 now!),
it is simply not conducive to a coder's productivity to have to rewrite a program
every year while explaining to gracious bug reporters that it's broken
because the underlying API has changed yet again.

The most recent major change finally added something of a real reporter API.
That's a good thing! Although it should have been there from day one. Yet
the new version also removed the runner API. That means Turn would have
revert back to old subclassing and monkey patching tricks in order support
certain features such as the solo and cross runners.

As any programmer can well understand, I have no interest in playing these
musical chairs any longer. I have endeavored to provide preliminary support
for Minitest v5+, which is now in the master branch. For the most part,
the reporter part, it is working. But there are plenty of loose ends that
have to be tied up if everything is to work as it should.

If someone else would like to take up the mantle of this project please
have at it. I'm available to answer any questions. Until then, consider
this entire project **deprecated**.

Sincerely,

  **trans**

## DESCRIPTION

TURN is a new way to view test results. With longer running tests, it
can be very frustrating to see a failure (....F...) and then have to wait till
all the tests finish before you can see what the exact failure was. TURN
displays each test on a separate line with failures being displayed
immediately instead of at the end of the tests.

If you have the 'ansi' gem installed, then TURN output will be displayed in
wonderful technicolor (but only if your terminal supports ANSI color codes).
Well, the only colors are green and red, but that is still color.

## FEATURES

General usage provides better test output. Here is some sample output:

    TestMyClass
        test_alt                                                            PASS
        test_alt_eq                                                         PASS
        test_bad                                                            FAIL
            ./test/test_my_class.rb:64:in `test_bad'
            <false> is not true.
        test_foo                                                            PASS
        test_foo_eq                                                         PASS
    TestYourClass
        test_method_a                                                       PASS
        test_method_b                                                       PASS
        test_method_c                                                       PASS
    ============================================================================
      pass: 7,  fail: 1,  error: 0
      total: 15 tests with 42 assertions in 0.018 seconds
    ============================================================================

Turn also provides solo and cross test modes when run from the *turn* commandline
application.

## INSTRUCTION

Turn can be used from the command-line or via require. The command-line tool
offers additional options for how one runs tests.

### Command Line

You can use the *turn* executable in place of the *ruby* interpreter.

    $ turn -Ilib test/test_all.rb

This will invoke the ruby interpreter and automatically require the turn
formatting library. All command line arguments are passed "as is" to the
ruby interpreter.

To use the solo runner.

    $ turn --solo -Ilib test/

This will run all tests in the test/ directory in a separate process.
Likewise for the cross runner.

    $ turn --cross -Ilib test/

This will run every pairing of tests in a separate process.

### Via Require

Simply require the TURN package from within your test suite.

    $ require 'turn/autorun'

This will configure MiniTest to use TURN formatting for displaying test
results. A better line to use, though, is the following:

    begin; require 'turn/autorun'; rescue LoadError; end

When you distribute your code, the test suite can be run without requiring
the end user to install the TURN package.

For a Rails application, put the require line into the 'test/test_helper.rb'
script. Now your Rails tests will use TURN formatting.

Note: This changed in version 0.9. It used to be just `require 'turn'`,
but because of how `bundle exec` works, it was better to require a subdirectory
file.

### Configuration

You can use `Turn.config` to adjust turn configuration.

Options are following:

    tests           List of file names or glob patterns of tests to run. Default: ["test/**/{test,}*{,test}.rb"]
    exclude         List of file names or globs to exclude from tests list. Default: []
    pattern         Regexp pattern that all test names must match to be eligible to run. Default: /.*/ (all)
    matchcase       Regexp pattern that all test cases must match to be eligible to run. Default: nil (all)
    loadpath        Add these folders to the $LOAD_PATH. Default: ['lib']
    requires        Libs to require when running tests. Default: []
    format          Reporter type (:pretty, :dot, :cue, :marshal, :outline, :progress). Default: :pretty
    live            Test against live install (i.e. Don't use loadpath option). Default: false
    verbose         Verbose output? Default: false
    trace           Number of backtrace lines to display. Default: set from ENV or nil (all)
    natural         Use natural language case names.  Default: false
    ansi            Force colorized output (requires 'ansi' gem). Default: set from ENV or nil (auto)

To set option just call the desired method:

    Turn.config.format = :progress

Also, you can use following environment variables to adjust settings:

    backtrace       Number of backtrace lines to display. Default: set from ENV or nil
    ansi            Force colorize output (requires 'ansi' gem).

Finally, you can include your own custom Reporter type (aka format). Turn will search for reporters in the `.turn/reporters/`
directory of your local project and then in your user home directory. So for example, if you specified the following:

    Turn.config.format = :cool

Then Turn will look first for `./.turn/reporters/cool_reporter.rb`, then `~/.turn/reporters/cool_reporter.rb`.

See source code for examples of how to write your own reporters.

## REQUIREMENTS

* ansi 1.1+ (for colorized output and progress bar output mode)

## INSTALLATION

Follow the usual procedure:

    $ gem install turn

## TODO

* Support MiniTest v5.0
* General code cleanup

# CONTRIBUTING

1. Fork it
2. Create your feature branch (`git checkout -b my_new_feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my_new_feature`)
5. Create a new Pull Request

If you are a project member please follow the same process (minus the forking). For significant changes please wait for another developer to review and merge them, whereas small contributions/fixes can be merged without review.

## Building

To build the gem simply run:

    gem build .gemspec

## Solo and Cross Runners

An important aspect of Turn's design that needs be kept in mind, is the way
_solo_ and _cross_ testing features are implemented. This is some really
neat code actually (IMO), but it might be difficult to grasp with out some
explanation. What turn does when using the `--solo` or `--cross` options,
is shell out to itself using the YAML reporter. It does this repeatedly
for each test, or each pair of tests, respectively, and then collates all the
resulting YAML reports into a single report, which it then feeds back into the
selected reporter.

## LICENSE

MIT License

Copyright (c) 2006 Tim Pease
Copyright (c) 2009 Thomas Sawyer

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.