text:
package com.intellij.openapi.module.impl.scopes;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.UnloadedModuleDescription;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.DirectoryIndex;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.containers.Queue;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.Set;

/**
 * @author max
 */
class ModuleWithDependentsScope extends GlobalSearchScope {
  private final Module myModule;

  private final ProjectFileIndex myProjectFileIndex;
  private final Set<Module> myModules;
  private final GlobalSearchScope myProjectScope;

  ModuleWithDependentsScope(@NotNull Module module) {
    super(module.getProject());
    myModule = module;

    myProjectFileIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex();
    myProjectScope = ProjectScope.getProjectScope(module.getProject());

    myModules = buildDependents(myModule);
  }

  @NotNull
  private static Set<Module> buildDependents(Module module) {
    Set<Module> result = new THashSet<>();
    result.add(module);

    ModuleIndex index = getModuleIndex(module.getProject());

    Queue<Module> walkingQueue = new Queue<>(10);
    walkingQueue.addLast(module);

    Set<Module> processedExporting = new THashSet<>();
    while (!walkingQueue.isEmpty()) {
      Module current = walkingQueue.pullFirst();
      processedExporting.add(current);
      result.addAll(index.plainUsages.get(current));
      for (Module dependent : index.exportingUsages.get(current)) {
        result.add(dependent);
        if (processedExporting.add(dependent)) {
          walkingQueue.addLast(dependent);
        }
      }
    }
    return result;
  }

  private static class ModuleIndex {
    final MultiMap<Module, Module> plainUsages = MultiMap.create();
    final MultiMap<Module, Module> exportingUsages = MultiMap.create();
  }

  private static ModuleIndex getModuleIndex(final Project project) {
    return CachedValuesManager.getManager(project).getCachedValue(project, () -> {
      ModuleIndex index = new ModuleIndex();
      for (Module module : ModuleManager.getInstance(project).getModules()) {
        for (OrderEntry orderEntry : ModuleRootManager.getInstance(module).getOrderEntries()) {
          if (orderEntry instanceof ModuleOrderEntry) {
            Module referenced = ((ModuleOrderEntry)orderEntry).getModule();
            if (referenced != null) {
              MultiMap<Module, Module> map = ((ModuleOrderEntry)orderEntry).isExported() ? index.exportingUsages : index.plainUsages;
              map.putValue(referenced, module);
            }
          }
        }
      }
      return CachedValueProvider.Result.create(index, ProjectRootManager.getInstance(project));
    });
  }

  @Override
  public boolean contains(@NotNull VirtualFile file) {
    return contains(file, false);
  }

  boolean contains(@NotNull VirtualFile file, boolean myOnlyTests) {
    Module moduleOfFile = myProjectFileIndex.getModuleForFile(file);
    if (moduleOfFile == null || !myModules.contains(moduleOfFile)) return false;
    if (myOnlyTests && !TestSourcesFilter.isTestSources(file, moduleOfFile.getProject())) return false;
    return myProjectScope.contains(file);
  }

  @Override
  public boolean isSearchInModuleContent(@NotNull Module aModule) {
    return myModules.contains(aModule);
  }

  @Override
  public boolean isSearchInLibraries() {
    return false;
  }

  @NotNull
  @Override
  public Collection<UnloadedModuleDescription> getUnloadedModulesBelongingToScope() {
    ModuleManager moduleManager = ModuleManager.getInstance(myModule.getProject());
    return ContainerUtil.mapNotNull(DirectoryIndex.getInstance(myModule.getProject()).getDependentUnloadedModules(myModule),
                                    moduleManager::getUnloadedModuleDescription);
  }

  @Override
  @NonNls
  public String toString() {
    return "Module with dependents:" + myModule.getName();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof ModuleWithDependentsScope)) return false;

    final ModuleWithDependentsScope moduleWithDependentsScope = (ModuleWithDependentsScope)o;

    return myModule.equals(moduleWithDependentsScope.myModule);
  }

  @Override
  public int hashCode() {
    return myModule.hashCode();
  }
}


text:
module Cloner::MongoDB
  extend ActiveSupport::Concern

  def mongodb_conf
    @conf ||= begin
      yml = YAML.load_file(Rails.root.join('config', 'mongoid.yml'))[Rails.env]
      if yml.key?('sessions')
        yml['sessions']['default']
      else
        yml['clients']['default']
      end
    end
  end

  def mongodb_to
    mongodb_conf['database']
  end

  def mongodb_r_conf
    @r_conf ||= begin
      do_ssh do |ssh|
        ret = ssh_exec!(ssh, "cat #{e(remote_app_path + '/config/mongoid.yml')}")
        check_ssh_err(ret)

        begin
          yml = YAML.load(ret[0])[env_from]
          raise 'no data' if yml.blank?
        rescue Exception => e
          puts "unable to read remote database.yml for env #{env_from}."
          puts "Remote file contents:"
          puts ret[0]
        end

        if yml.key?('sessions')
          yml['sessions']['default']
        else
          yml['clients']['default']
        end
      end
    end
  end

  def mongodb_local_auth
    if mongodb_conf['options'].present? && mongodb_conf['password'].present?
      "-u #{e mongodb_conf['options']['user']} -p #{e mongodb_conf['options']['password']}"
    elsif mongodb_conf['password'].present?
      "-u #{e mongodb_conf['username']} -p #{e mongodb_conf['password']}"
    else
      ""
    end
  end

  def mongodb_dump_remote
    puts "backup remote DB via ssh"
    do_ssh do |ssh|
      ssh.exec!("rm -R #{remote_dump_path}")
      ret = ssh_exec!(ssh, "mkdir -p #{remote_dump_path}")
      check_ssh_err(ret)
      if mongodb_r_conf['options'].present? && mongodb_r_conf['options']['password'].present?
        username, password = mongodb_r_conf['options']['user'], mongodb_r_conf['options']['password']
      else
        username, password = mongodb_r_conf['username'], mongodb_r_conf['password']
      end
      dump = "mongodump -u #{e username} -p #{e password} -d #{e mongodb_r_conf['database']} --authenticationDatabase #{e mongodb_r_conf['database']} -o #{e remote_dump_path} #{db_dump_options}"
      puts dump if verbose?
      ret = ssh_exec!(ssh, dump)
      check_ssh_err(ret)
    end
  end

  def mongodb_dump_restore
    puts "restoring DB"
    restore = "mongorestore --drop -d #{e mongodb_to} #{mongodb_local_auth} #{db_restore_options} #{e mongodb_path}"
    puts restore if verbose?
    pipe = IO.popen(restore)
    while (line = pipe.gets)
      print line if verbose?
    end
    ret = $?.to_i
    if ret != 0
      puts "Error: local command exited with #{ret}"
    end
  end

  def mongodb_path
    Rails.root.join("tmp", "dump", mongodb_to).to_s
  end

  def mongodb_dump_copy
    FileUtils.mkdir_p(mongodb_path)
    rsync("#{remote_dump_path}/#{mongodb_r_conf['database']}", mongodb_path)
  end

  def clone_mongodb
    mongodb_dump_remote()
    mongodb_dump_copy()
    mongodb_dump_restore()
  end
end

redpajama_set_name: RedPajamaGithub


text:
module Gitlab
  module HealthChecks
    module Redis
      class QueuesCheck
        extend SimpleAbstractCheck

        class << self
          def check_up
            check
          end

          private

          def metric_prefix
            'redis_queues_ping'
          end

          def successful?(result)
            result == 'PONG'
          end

          # rubocop: disable CodeReuse/ActiveRecord
          def check
            catch_timeout 10.seconds do
              Gitlab::Redis::Queues.with(&:ping)
            end
          end
          # rubocop: enable CodeReuse/ActiveRecord
        end
      end
    end
  end
end


text:
import logging

from dpl.core.listener import Listener
from dpl.core.message_hub import MessageHub
from dpl.core.messages.message import Message, time

logger = logging.getLogger(__name__)

class ListenerCli(Listener):
    def __init__(self, feedback):
        """
        Конструктор. Запускает процесс-слушатель консоли
        """
        if not isinstance(feedback, MessageHub):
            raise ValueError('wrong type of feedback object')

        super().__init__(feedback)

    def get_data(self):
        """
        Считываем очередную строку из консоли
        :return: считанная строка
        """
        return input()

    def process_data(self, raw_data: str):
        """
        Обработчик считанных данных
        :param raw_data: данные, строка
        :return: None
        """
        logger.debug('Data read: %s', raw_data)

        tokenized_data = raw_data.split(" ", maxsplit=3)

        if len(tokenized_data) < 2:
            print('Warning: Unknown command: {0}'.format(raw_data))
            return

        command = tokenized_data[0]
        obj_id = tokenized_data[1]

        if len(tokenized_data) > 2:
            cmd_params = tokenized_data[2]
        else:
            cmd_params = tuple()

        msg = Message(
            "user_request",
            "cli",
            "action_requested",
            time.time(),
            {
                "obj_id": obj_id,
                "action": command,
                "action_params": cmd_params
            }
        )

        self.feedback.accept_msg(msg)

        print('command "{0}" accepted'.format(raw_data))


text:
package org.apereo.cas.ticket;

import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.ticket.proxy.ProxyTicket;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

/**
 * The {@link ProxyTicketImpl} is a concrete implementation of the {@link ProxyTicket}.
 *
 * @author Misagh Moayyed
 * @since 4.2
 */
@Entity
@DiscriminatorValue(ProxyTicket.PROXY_TICKET_PREFIX)
public class ProxyTicketImpl extends ServiceTicketImpl implements ProxyTicket {
    private static final long serialVersionUID = -4469960563289285371L;

    /**
     * Instantiates a new Proxy ticket.
     */
    public ProxyTicketImpl() {
    }

    /**
     * Instantiates a new Proxy ticket.
     *
     * @param id           the id
     * @param ticket       the ticket
     * @param service      the service
     * @param currentAuthentication the authentication that prompted this ticket. Could be null.
     * @param policy       the policy
     */
    public ProxyTicketImpl(final String id, final TicketGrantingTicketImpl ticket, final Service service,
                           final Authentication currentAuthentication, final ExpirationPolicy policy) {
        super(id, ticket, service, currentAuthentication, policy);
    }
}


text:
<form id="mainForm" method="post" action="http://plnkr.co/edit/?p=preview" target="_self"><input type="hidden" name="files[styles.css]" value="/* Master Styles */
h1 {
  color: #369;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 250%;
}
h2, h3 {
  color: #444;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: lighter;
}
body {
  margin: 2em;
}
body, input[text], button {
  color: #888;
  font-family: Cambria, Georgia;
}
a {
  cursor: pointer;
  cursor: hand;
}
button {
  font-family: Arial;
  background-color: #eee;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  cursor: hand;
}
button:hover {
  background-color: #cfd8dc;
}
button:disabled {
  background-color: #eee;
  color: #aaa;
  cursor: auto;
}

/* Navigation link styles */
nav a {
  padding: 5px 10px;
  text-decoration: none;
  margin-right: 10px;
  margin-top: 10px;
  display: inline-block;
  background-color: #eee;
  border-radius: 4px;
}
nav a:visited, a:link {
  color: #607D8B;
}
nav a:hover {
  color: #039be5;
  background-color: #CFD8DC;
}
nav a.active {
  color: #039be5;
}

/* items class */
.items {
  margin: 0 0 2em 0;
  list-style-type: none;
  padding: 0;
  width: 24em;
}
.items li {
  cursor: pointer;
  position: relative;
  left: 0;
  background-color: #EEE;
  margin: .5em;
  padding: .3em 0;
  height: 1.6em;
  border-radius: 4px;
}
.items li:hover {
  color: #607D8B;
  background-color: #DDD;
  left: .1em;
}
.items li.selected {
  background-color: #CFD8DC;
  color: white;
}
.items li.selected:hover {
  background-color: #BBD8DC;
}
.items .text {
  position: relative;
  top: -3px;
}
.items .badge {
  display: inline-block;
  font-size: small;
  color: white;
  padding: 0.8em 0.7em 0 0.7em;
  background-color: #607D8B;
  line-height: 1em;
  position: relative;
  left: -1px;
  top: -4px;
  height: 1.8em;
  margin-right: .8em;
  border-radius: 4px 0 0 4px;
}
/* everywhere else */
* {
  font-family: Arial, Helvetica, sans-serif;
}

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[app/app.component.ts]" value="import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'my-app',
  template: `

Reactive Forms

    <hero-list></hero-list>

`
})
export class AppComponent { }

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[app/app.module.ts]" value="import { NgModule }            from '@angular/core';
import { BrowserModule }       from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';  // <-- #1 import module

import { AppComponent }        from './app.component';
import { HeroDetailComponent } from './hero-detail.component'; // <-- #1 import component
import { HeroListComponent }   from './hero-list.component';

import { HeroService }         from './hero.service'; //  <-- #1 import service

@NgModule({
  imports: [
    BrowserModule,
    ReactiveFormsModule // <-- #2 add to Angular module imports
  ],
  declarations: [
    AppComponent,
    HeroDetailComponent, // <-- #3 declare app component
    HeroListComponent
  ],
  exports: [ // export for the DemoModule
    AppComponent,
    HeroDetailComponent,
    HeroListComponent
  ],
  providers: [ HeroService ], // <-- #4 provide HeroService
  bootstrap: [ AppComponent ]
})
export class AppModule { }

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[app/data-model.ts]" value="export class Hero {
  id = 0;
  name = '';
  addresses: Address[];
}

export class Address {
  street = '';
  city   = '';
  state  = '';
  zip    = '';
}

export const heroes: Hero[] = [
  {
    id: 1,
    name: 'Whirlwind',
    addresses: [
      {street: '123 Main',  city: 'Anywhere', state: 'CA',  zip: '94801'},
      {street: '456 Maple', city: 'Somewhere', state: 'VA', zip: '23226'},
    ]
  },
  {
    id: 2,
    name: 'Bombastic',
    addresses: [
      {street: '789 Elm',  city: 'Smallville', state: 'OH',  zip: '04501'},
    ]
  },
  {
    id: 3,
    name: 'Magneta',
    addresses: [ ]
  },
];

export const states = ['CA', 'MD', 'OH', 'VA'];

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[app/hero.service.ts]" value="import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { of }         from 'rxjs/observable/of';
import 'rxjs/add/operator/delay';

import { Hero, heroes } from './data-model';

@Injectable()
export class HeroService {

  delayMs = 500;

  // Fake server get; assume nothing can go wrong
  getHeroes(): Observable<Hero[]> {
    return of(heroes).delay(this.delayMs); // simulate latency with delay
  }

  // Fake server update; assume nothing can go wrong
  updateHero(hero: Hero): Observable<Hero>  {
    const oldHero = heroes.find(h => h.id === hero.id);
    const newHero = Object.assign(oldHero, hero); // Demo: mutate cached hero
    return of(newHero).delay(this.delayMs); // simulate latency with delay
  }
}

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[app/hero-detail.component.html]" value="<form [formGroup]="heroForm" (ngSubmit)="onSubmit()" novalidate>

    <button type="submit"
            [disabled]="heroForm.pristine" class="btn btn-success">Save</button> &nbsp;
    <button type="reset" (click)="revert()"
            [disabled]="heroForm.pristine" class="btn btn-danger">Revert</button>

      Name:
        <input class="form-control" formControlName="name">

Address #{{i + 1}}

          Street:
            <input class="form-control" formControlName="street">

          City:
            <input class="form-control" formControlName="city">

          State:
            <select class="form-control" formControlName="state">
              <option *ngFor="let state of states" [value]="state">{{state}}</option>
            </select>

          Zip Code:
            <input class="form-control" formControlName="zip">

    <button (click)="addLair()" type="button">Add a Secret Lair</button>

    Super power:
    <input type="radio" formControlName="power" value="flight">Flight
    <input type="radio" formControlName="power" value="x-ray vision">X-ray vision
    <input type="radio" formControlName="power" value="strength">Strength

      <input type="checkbox" formControlName="sidekick">I have a sidekick.

</form>

heroForm value: {{ heroForm.value | json}}

Name change log

{{name}}

"><input type="hidden" name="files[app/hero-detail.component.ts]" value="import { Component, Input, OnChanges }       from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';

import { Address, Hero, states } from './data-model';
import { HeroService }           from './hero.service';

@Component({
  moduleId: module.id,
  selector: 'hero-detail',
  templateUrl: './hero-detail.component.html'
})
export class HeroDetailComponent implements OnChanges {
  @Input() hero: Hero;

  heroForm: FormGroup;
  nameChangeLog: string[] = [];
  states = states;

  constructor(
    private fb: FormBuilder,
    private heroService: HeroService) {

    this.createForm();
    this.logNameChange();
  }

  createForm() {
    this.heroForm = this.fb.group({
      name: '',
      secretLairs: this.fb.array([]),
      power: '',
      sidekick: ''
    });
  }

  ngOnChanges() {
    this.heroForm.reset({
      name: this.hero.name
    });
    this.setAddresses(this.hero.addresses);
  }

  get secretLairs(): FormArray {
    return this.heroForm.get('secretLairs') as FormArray;
  };

  setAddresses(addresses: Address[]) {
    const addressFGs = addresses.map(address => this.fb.group(address));
    const addressFormArray = this.fb.array(addressFGs);
    this.heroForm.setControl('secretLairs', addressFormArray);
  }

  addLair() {
    this.secretLairs.push(this.fb.group(new Address()));
  }

  onSubmit() {
    this.hero = this.prepareSaveHero();
    this.heroService.updateHero(this.hero).subscribe(/* error handling */);
    this.ngOnChanges();
  }

  prepareSaveHero(): Hero {
    const formModel = this.heroForm.value;

    // deep copy of form model lairs
    const secretLairsDeepCopy: Address[] = formModel.secretLairs.map(
      (address: Address) => Object.assign({}, address)
    );

    // return new `Hero` object containing a combination of original hero value(s)
    // and deep copies of changed form model values
    const saveHero: Hero = {
      id: this.hero.id,
      name: formModel.name as string,
      // addresses: formModel.secretLairs // <-- bad!
      addresses: secretLairsDeepCopy
    };
    return saveHero;
  }

  revert() { this.ngOnChanges(); }

  logNameChange() {
    const nameControl = this.heroForm.get('name');
    nameControl.valueChanges.forEach(
      (value: string) => this.nameChangeLog.push(value)
    );
  }
}

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[app/hero-list.component.html]" value="
Loading heroes ...

Select a hero:

  <button (click)="getHeroes()" class="btn btn-primary">Refresh</button>
  {{hero.name}}

Hero Detail

Editing: {{selectedHero.name}}

  <hero-detail [hero]="selectedHero"></hero-detail>

"><input type="hidden" name="files[app/hero-list.component.ts]" value="import { Component, OnInit } from '@angular/core';
import { Observable }        from 'rxjs/Observable';
import 'rxjs/add/operator/finally';

import { Hero }        from './data-model';
import { HeroService } from './hero.service';

@Component({
  moduleId: module.id,
  selector: 'hero-list',
  templateUrl: 'hero-list.component.html'
})
export class HeroListComponent implements OnInit {
  heroes: Observable<Hero[]>;
  isLoading = false;
  selectedHero: Hero;

  constructor(private heroService: HeroService) { }

  ngOnInit() { this.getHeroes(); }

  getHeroes() {
    this.isLoading = true;
    this.heroes = this.heroService.getHeroes()
                      // Todo: error handling
                      .finally(() => this.isLoading = false);
    this.selectedHero = undefined;
  }

  select(hero: Hero) { this.selectedHero = hero; }
}

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[main-final.ts]" value="// tslint:disable:no-unused-variable
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[index.html]" value="<!DOCTYPE html>

    <title>Hero Form</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css">

    <my-app>Loading...</my-app>

"><input type="hidden" name="tags[0]" value="angular"><input type="hidden" name="tags[1]" value="example"><input type="hidden" name="tags[2]" value="reactive"><input type="hidden" name="tags[3]" value="forms"><input type="hidden" name="private" value="true"><input type="hidden" name="description" value="Angular Example - Angular Reactive Forms (final)"></form>


text:
from __future__ import print_function

try:
    from setuptools import setup, find_packages, Extension
except ImportError:
    from distutils.core import setup, Extension

    def find_packages():
        return ['treeCl', 'treeCl.interfacing', 'treeCl.tasks', 'treeCl.utils']

from Cython.Distutils import build_ext
import pkg_resources
import platform
import re
import subprocess

# Facilities to install properly on Mac using clang
def is_clang(bin):
    proc = subprocess.Popen([bin, '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    output = str(b'\n'.join([stdout, stderr]).decode('ascii', 'ignore'))
    return not re.search(r'clang', output) is None

class my_build_ext(build_ext):
    def build_extensions(self):
        binary = self.compiler.compiler[0]
        if is_clang(binary):
            for e in self.extensions:
                e.extra_compile_args.append('-stdlib=libc++')

                if platform.system() == 'Darwin':
                    mac_version, _, _ = platform.mac_ver()
                    major, minor, patch = [int(n) for n in mac_version.split('.')]

                    # libstdc++ is deprecated in recent versions of XCode
                    if minor >= 9:
                        e.extra_compile_args.append('-mmacosx-version-min=10.9')
                        e.extra_compile_args.append('-stdlib=libc++')
                        e.extra_link_args.append('-mmacosx-version-min=10.9')
                        e.extra_link_args.append('-stdlib=libc++')
                    else:
                        e.extra_compile_args.append('-mmacosx-version-min=10.7')
                        e.extra_link_args.append('-mmacosx-version-min=10.7')

        build_ext.build_extensions(self)

compile_args = ['-std=c++11']

extensions = [
    Extension(name='tree_collection',
              sources=[
                  'extensions/tree_collection/cython/py_wrapper.pyx',
                  'extensions/tree_collection/src/ProblemParser.cc',
                  'extensions/tree_collection/src/MinSqTree.cc',
                  'extensions/tree_collection/src/newick.cc',
              ],
              language='c++',
              include_dirs=['extensions/tree_collection/src/eigen3'],
              extra_compile_args=compile_args,
    ),
]

# Install splash
VERSION = '0.1.38'

logo = """
═══════════ ╔═╗┬
┌┬┐┬─┐┌─┐┌─┐║  │
 │ ├┬┘├┤ ├┤ ╚═╝┴─┘
 ┴ ┴└─└─┘└─┘╭─────
┈┈┈┈┈┈┄┄┄┄┄─┤  ╭──
{versionfmt}╰──┤
══════════════ ╰──
""".format(versionfmt=VERSION.center(12))

print(logo)

setup(name="treeCl",
      version=VERSION,
      author='Kevin Gori',
      author_email='kcg25@cam.ac.uk',
      description='Phylogenetic Clustering Package',
      url='https://github.com/kgori/treeCl.git',
      packages=find_packages(),
      include_package_data=True,
      package_data={
          'treeCl': ['logging/logging.yaml']
      },
      scripts=[
          # 'bin/simulator',
          # 'bin/collapse',
          # 'bin/treeCl',
          # 'bin/seqconvert',
          # 'bin/bootstrap',
          # 'bin/npbs.py',
          # 'bin/pre_npbs.py',
      ],
      install_requires=[
          'biopython',
          'cython>=0.19.0',
          'dendropy>=4.0.0',
          'fastcluster',
          'futures',
          'ipython',
          'matplotlib',
          'nose',
          'numpy',
          'pandas',
          'phylo_utils==0.0.5',
          'progressbar-latest==2.4',
          'PyYaml',
          'scipy',
          'scikit-learn',
          'tree_distance>=1.0.6',
      ],
      cmdclass={'build_ext': my_build_ext},
      ext_modules=extensions,
      test_suite='tests',
)


text:
package org.teavm.optimization;

import org.teavm.model.BasicBlock;
import org.teavm.model.MethodReader;
import org.teavm.model.Program;
import org.teavm.model.instructions.JumpInstruction;
import org.teavm.model.util.BasicBlockMapper;

/**
 *
 * @author Alexey Andreev
 */
public class EmptyBlockElimination implements MethodOptimization {
    @Override
    public void optimize(MethodReader method, final Program program) {
        final int[] blockMapping = new int[program.basicBlockCount()];
        for (int i = 0; i < blockMapping.length; ++i) {
            blockMapping[i] = i;
        }
        int lastNonEmpty = program.basicBlockCount() - 1;
        for (int i = program.basicBlockCount() - 2; i > 0; --i) {
            BasicBlock block = program.basicBlockAt(i);
            if (block.getPhis().isEmpty() && block.getInstructions().size() == 1 &&
                    block.getLastInstruction() instanceof JumpInstruction) {
                JumpInstruction insn = (JumpInstruction)block.getLastInstruction();
                if (insn.getTarget().getIndex() == i + 1) {
                    blockMapping[i] = lastNonEmpty;
                }
            }
            lastNonEmpty = blockMapping[i];
        }
        new BasicBlockMapper() {
            @Override protected BasicBlock map(BasicBlock block) {
                return program.basicBlockAt(blockMapping[block.getIndex()]);
            }
        }.transform(program);
        for (int i = 0; i < program.basicBlockCount(); ++i) {
            if (blockMapping[i] != i) {
                program.deleteBasicBlock(i);
            }
        }
        program.pack();
    }
}


text:
import unittest
import numpy as np
import numpy.testing as npt
import os
import shutil

from pymc3.tests import models
from pymc3.backends import base

class ModelBackendSetupTestCase(unittest.TestCase):
    """Set up a backend trace.

    Provides the attributes
    - test_point
    - model
    - strace
    - draws

    Children must define
    - backend
    - name
    - shape
    """

    def setUp(self):
        self.test_point, self.model, _ = models.beta_bernoulli(self.shape)
        with self.model:
            self.strace = self.backend(self.name)
        self.draws, self.chain = 3, 0
        self.strace.setup(self.draws, self.chain)

    def tearDown(self):
        if self.name is not None:
            remove_file_or_directory(self.name)

class ModelBackendSampledTestCase(unittest.TestCase):
    """Setup and sample a backend trace.

    Provides the attributes
    - test_point
    - model
    - mtrace (MultiTrace object)
    - draws
    - expected
        Expected values mapped to chain number and variable name.

    Children must define
    - backend
    - name
    - shape
    """
    @classmethod
    def setUpClass(cls):
        cls.test_point, cls.model, _ = models.beta_bernoulli(cls.shape)
        with cls.model:
            strace0 = cls.backend(cls.name)
            strace1 = cls.backend(cls.name)

        cls.draws = 5
        strace0.setup(cls.draws, chain=0)
        strace1.setup(cls.draws, chain=1)

        varnames = list(cls.test_point.keys())
        shapes = {varname: value.shape
                  for varname, value in cls.test_point.items()}
        dtypes = {varname: value.dtype
                  for varname, value in cls.test_point.items()}

        cls.expected = {0: {}, 1: {}}
        for varname in varnames:
            mcmc_shape = (cls.draws,) + shapes[varname]
            values = np.arange(cls.draws * np.prod(shapes[varname]),
                               dtype=dtypes[varname])
            cls.expected[0][varname] = values.reshape(mcmc_shape)
            cls.expected[1][varname] = values.reshape(mcmc_shape) * 100

        for idx in range(cls.draws):
            point0 = {varname: cls.expected[0][varname][idx, ...]
                      for varname in varnames}
            point1 = {varname: cls.expected[1][varname][idx, ...]
                      for varname in varnames}
            strace0.record(point=point0)
            strace1.record(point=point1)
        strace0.close()
        strace1.close()
        cls.mtrace = base.MultiTrace([strace0, strace1])

    @classmethod
    def tearDownClass(cls):
        if cls.name is not None:
            remove_file_or_directory(cls.name)

    def test_varnames_nonempty(self):
        # Make sure the test_point has variables names because many
        # tests rely on looping through these and would pass silently
        # if the loop is never entered.
        assert list(self.test_point.keys())

class SamplingTestCase(ModelBackendSetupTestCase):
    """Test backend sampling.

    Children must define
    - backend
    - name
    - shape
    """

    def test_standard_close(self):
        for idx in range(self.draws):
            point = {varname: np.tile(idx, value.shape)
                     for varname, value in self.test_point.items()}
            self.strace.record(point=point)
        self.strace.close()

        for varname in self.test_point.keys():
            npt.assert_equal(self.strace.get_values(varname)[0, ...],
                             np.zeros(self.strace.var_shapes[varname]))
            last_idx = self.draws - 1
            npt.assert_equal(self.strace.get_values(varname)[last_idx, ...],
                             np.tile(last_idx, self.strace.var_shapes[varname]))

    def test_clean_interrupt(self):
        self.strace.record(point=self.test_point)
        self.strace.close()
        for varname in self.test_point.keys():
            self.assertEqual(self.strace.get_values(varname).shape[0], 1)

class SelectionTestCase(ModelBackendSampledTestCase):
    """Test backend selection.

    Children must define
    - backend
    - name
    - shape
    """

    def test_get_values_default(self):
        for varname in self.test_point.keys():
            expected = np.concatenate([self.expected[chain][varname]
                                       for chain in [0, 1]])
            result = self.mtrace.get_values(varname)
            npt.assert_equal(result, expected)

    def test_get_values_nocombine_burn_keyword(self):
        burn = 2
        for varname in self.test_point.keys():
            expected = [self.expected[0][varname][burn:],
                        self.expected[1][varname][burn:]]
            result = self.mtrace.get_values(varname, burn=burn, combine=False)
            npt.assert_equal(result, expected)

    def test_len(self):
        self.assertEqual(len(self.mtrace), self.draws)

    def test_dtypes(self):
        for varname in self.test_point.keys():
            self.assertEqual(self.expected[0][varname].dtype,
                             self.mtrace.get_values(varname, chains=0).dtype)

    def test_get_values_nocombine_thin_keyword(self):
        thin = 2
        for varname in self.test_point.keys():
            expected = [self.expected[0][varname][::thin],
                        self.expected[1][varname][::thin]]
            result = self.mtrace.get_values(varname, thin=thin, combine=False)
            npt.assert_equal(result, expected)

    def test_get_point(self):
        idx = 2
        result = self.mtrace.point(idx)
        for varname in self.test_point.keys():
            expected = self.expected[1][varname][idx]
            npt.assert_equal(result[varname], expected)

    def test_get_slice(self):
        expected = []
        for chain in [0, 1]:
            expected.append({varname: self.expected[chain][varname][2:]
                             for varname in self.mtrace.varnames})
        result = self.mtrace[2:]
        for chain in [0, 1]:
            for varname in self.test_point.keys():
                npt.assert_equal(result.get_values(varname, chains=[chain]),
                                 expected[chain][varname])

    def test_get_values_one_chain(self):
        for varname in self.test_point.keys():
            expected = self.expected[0][varname]
            result = self.mtrace.get_values(varname, chains=[0])
            npt.assert_equal(result, expected)

    def test_get_values_nocombine_chains_reversed(self):
        for varname in self.test_point.keys():
            expected = [self.expected[1][varname], self.expected[0][varname]]
            result = self.mtrace.get_values(varname, chains=[1, 0],
                                            combine=False)
            npt.assert_equal(result, expected)

    def test_nchains(self):
        self.mtrace.nchains == 2

    def test_get_values_one_chain_int_arg(self):
        for varname in self.test_point.keys():
            npt.assert_equal(self.mtrace.get_values(varname, chains=[0]),
                             self.mtrace.get_values(varname, chains=0))

    def test_get_values_combine(self):
        for varname in self.test_point.keys():
            expected = np.concatenate([self.expected[chain][varname]
                                       for chain in [0, 1]])
            result = self.mtrace.get_values(varname, combine=True)
            npt.assert_equal(result, expected)

    def test_get_values_combine_burn_arg(self):
        burn = 2
        for varname in self.test_point.keys():
            expected = np.concatenate([self.expected[chain][varname][burn:]
                                       for chain in [0, 1]])
            result = self.mtrace.get_values(varname, combine=True, burn=burn)
            npt.assert_equal(result, expected)

    def test_get_values_combine_thin_arg(self):
        thin = 2
        for varname in self.test_point.keys():
            expected = np.concatenate([self.expected[chain][varname][::thin]
                                       for chain in [0, 1]])
            result = self.mtrace.get_values(varname, combine=True, thin=thin)
            npt.assert_equal(result, expected)

    def test_getitem_equivalence(self):
        mtrace = self.mtrace
        for varname in self.test_point.keys():
            npt.assert_equal(mtrace[varname],
                             mtrace.get_values(varname, combine=True))
            npt.assert_equal(mtrace[varname, 2:],
                             mtrace.get_values(varname, burn=2,
                                               combine=True))
            npt.assert_equal(mtrace[varname, 2::2],
                             mtrace.get_values(varname, burn=2, thin=2,
                                               combine=True))

    def test_selection_method_equivalence(self):
        varname = self.mtrace.varnames[0]
        mtrace = self.mtrace
        npt.assert_equal(mtrace.get_values(varname),
                         mtrace[varname])
        npt.assert_equal(mtrace[varname],
                         mtrace.__getattr__(varname))

class DumpLoadTestCase(ModelBackendSampledTestCase):
    """Test equality of a dumped and loaded trace with original.

    Children must define
    - backend
    - load_func
        Function to load dumped backend
    - name
    - shape
    """
    @classmethod
    def setUpClass(cls):
        super(DumpLoadTestCase, cls).setUpClass()
        try:
            with cls.model:
                cls.dumped = cls.load_func(cls.name)
        except:
            remove_file_or_directory(cls.name)
            raise

    @classmethod
    def tearDownClass(cls):
        remove_file_or_directory(cls.name)

    def test_nchains(self):
        self.assertEqual(self.mtrace.nchains, self.dumped.nchains)

    def test_varnames(self):
        trace_names = list(sorted(self.mtrace.varnames))
        dumped_names = list(sorted(self.dumped.varnames))
        self.assertEqual(trace_names, dumped_names)

    def test_values(self):
        trace = self.mtrace
        dumped = self.dumped
        for chain in trace.chains:
            for varname in self.test_point.keys():
                data = trace.get_values(varname, chains=[chain])
                dumped_data = dumped.get_values(varname, chains=[chain])
                npt.assert_equal(data, dumped_data)

class BackendEqualityTestCase(ModelBackendSampledTestCase):
    """Test equality of attirbutes from two backends.

    Children must define
    - backend0
    - backend1
    - name0
    - name1
    - shape
    """
    @classmethod
    def setUpClass(cls):
        cls.backend = cls.backend0
        cls.name = cls.name0
        super(BackendEqualityTestCase, cls).setUpClass()
        cls.mtrace0 = cls.mtrace

        cls.backend = cls.backend1
        cls.name = cls.name1
        super(BackendEqualityTestCase, cls).setUpClass()
        cls.mtrace1 = cls.mtrace

    @classmethod
    def tearDownClass(cls):
        for name in [cls.name0, cls.name1]:
            if name is not None:
                remove_file_or_directory(name)

    def test_chain_length(self):
        assert self.mtrace0.nchains == self.mtrace1.nchains
        assert len(self.mtrace0) == len(self.mtrace1)

    def test_dtype(self):
        for varname in self.test_point.keys():
            self.assertEqual(self.mtrace0.get_values(varname, chains=0).dtype,
                             self.mtrace1.get_values(varname, chains=0).dtype)

    def test_number_of_draws(self):
        for varname in self.test_point.keys():
            values0 = self.mtrace0.get_values(varname, combine=False,
                                              squeeze=False)
            values1 = self.mtrace1.get_values(varname, combine=False,
                                              squeeze=False)
            assert values0[0].shape[0] == self.draws
            assert values1[0].shape[0] == self.draws

    def test_get_item(self):
        for varname in self.test_point.keys():
            npt.assert_equal(self.mtrace0[varname], self.mtrace1[varname])

    def test_get_values(self):
        for varname in self.test_point.keys():
            for cf in [False, True]:
                npt.assert_equal(self.mtrace0.get_values(varname, combine=cf),
                                 self.mtrace1.get_values(varname, combine=cf))

    def test_get_values_no_squeeze(self):
        for varname in self.test_point.keys():
            npt.assert_equal(self.mtrace0.get_values(varname, combine=False,
                                                     squeeze=False),
                             self.mtrace1.get_values(varname, combine=False,
                                                     squeeze=False))

    def test_get_values_combine_and_no_squeeze(self):
        for varname in self.test_point.keys():
            npt.assert_equal(self.mtrace0.get_values(varname, combine=True,
                                                     squeeze=False),
                             self.mtrace1.get_values(varname, combine=True,
                                                     squeeze=False))

    def test_get_values_with_burn(self):
        for varname in self.test_point.keys():
            for cf in [False, True]:
                npt.assert_equal(self.mtrace0.get_values(varname, combine=cf,
                                                         burn=3),
                                 self.mtrace1.get_values(varname, combine=cf,
                                                         burn=3))
                # Burn to one value.
                npt.assert_equal(self.mtrace0.get_values(varname, combine=cf,
                                                         burn=self.draws - 1),
                                 self.mtrace1.get_values(varname, combine=cf,
                                                         burn=self.draws - 1))

    def test_get_values_with_thin(self):
        for varname in self.test_point.keys():
            for cf in [False, True]:
                npt.assert_equal(self.mtrace0.get_values(varname, combine=cf,
                                                         thin=2),
                                 self.mtrace1.get_values(varname, combine=cf,
                                                         thin=2))

    def test_get_values_with_burn_and_thin(self):
        for varname in self.test_point.keys():
            for cf in [False, True]:
                npt.assert_equal(self.mtrace0.get_values(varname, combine=cf,
                                                         burn=2, thin=2),
                                 self.mtrace1.get_values(varname, combine=cf,
                                                         burn=2, thin=2))

    def test_get_values_with_chains_arg(self):
        for varname in self.test_point.keys():
            for cf in [False, True]:
                npt.assert_equal(self.mtrace0.get_values(varname, chains=[0],
                                                         combine=cf),
                                 self.mtrace1.get_values(varname, chains=[0],
                                                         combine=cf))

    def test_get_point(self):
        npoint, spoint = self.mtrace0[4], self.mtrace1[4]
        for varname in self.test_point.keys():
            npt.assert_equal(npoint[varname], spoint[varname])

    def test_point_with_chain_arg(self):
        npoint = self.mtrace0.point(4, chain=0)
        spoint = self.mtrace1.point(4, chain=0)
        for varname in self.test_point.keys():
            npt.assert_equal(npoint[varname], spoint[varname])

def remove_file_or_directory(name):
    try:
        os.remove(name)
    except OSError:
        shutil.rmtree(name, ignore_errors=True)


text:
class YogoDataFormBuilder < ActionView::Helpers::FormBuilder

  # Creates the correct form field element for a DataMapper Property Type
  #
  # @example field_for_param(DM_Object_Boolean, {:checked => "checked"})
  #
  # @param [Property] param a DataMapper Property Object
  # @param [Array] *args array of options to be passed to the corresponding rails form builder method.
  #
  # @return [String] A formatted html form element for the DataMapper type
  #
  # @author Robbie Lamb robbie.lamb@gmail.com
  # @author PPooll Lllloovvvettt pol.llovet@gmail.com
  #
  # @api public
  def field_for_param(param, *args)
    if param.kind_of?(Yogo::Collection::Asset)
      options = args.last.is_a?(Hash) ? args.pop : {}
      options.merge!(:size => 15)
      args << options
      file_field(param.name, *args)
    elsif param.kind_of?(Yogo::Collection::Property::Boolean)
      radio_button(param.name, true, *args) + " " + label(param.name, "True", :value => true) << ActiveSupport::SafeBuffer.new('<br>') <<
      radio_button(param.name, false, *args) + " " + label(param.name, "False", :value => false)
    elsif param.kind_of?(Yogo::Collection::Property::Date)
      options = args.last.is_a?(Hash) ? args.pop : {}
      options.merge!(:size => 15)
      args << (options.has_key?(:class) ? options.merge(:class => options[:class]+",date-picker") : options.merge(:class => 'date-picker'))
      text_field(param.name, *args)
    else
      options = args.last.is_a?(Hash) ? args.pop : {}
      options.merge!(:size => 15)
      args << options
      text_field(param.name, *args)
    end
  end

end


text:
var parsers = {
	'dom' : function(value, opts) {
		opts = opts || {};
		// should default to this
		// opts.parser = markdownDOMParser;
		return html2markdown(value, opts);
	},

	'html' : function(value, opts) {
		opts = opts || {};

		if (typeof window == 'undefined') {
			html2markdown = require('../html2markdown');
			markdownHTMLParser = require('../markdown_html_parser');
		}

		opts.parser = markdownHTMLParser;
		return html2markdown(value, opts);
	}
};

for(var key in parsers) {
	// for testing in node env.
	if (key == 'dom' && typeof window == 'undefined') {
		continue;
	}

	var markdown = parsers[key];

	describe("With " + key + " parser", function() {
		it("should be able to convert '
H1
' to '# H1\\n\\n'", function() {
			var md = markdown("
H1
");
			expect(md).toMatch(/\# H1\n\n/);
		});

		it("should be able to convert '
H2
' to '## H2\\n\\n'", function() {
			var md = markdown("
H2
");
			expect(md).toMatch(/\#{2} H2\n\n/);
		});

		it("should be able to convert '
H3
' to '### H3\\n\\n'", function() {
			var md = markdown("
H3
");
			expect(md).toMatch(/\#{3} H3\n\n/);
		});

		it("should be able to convert '
H4
' to '#### H4\\n\\n'", function() {
			var md = markdown("
H4
");
			expect(md).toMatch(/\#{4} H4\n\n/);
		});

		it("should be able to convert '
H5
' to '##### H5\\n\\n'", function() {
			var md = markdown("
H5
");
			expect(md).toMatch(/\#{5} H5\n\n/);
		});

		it("should be able to convert '
H6
' to '###### H6\\n\\n'", function() {
			var md = markdown("
H6
");
			expect(md).toMatch(/\#{6} H6\n\n/);
		});

		it("should be able to convert 'Bold' to '**Bold**'", function() {
			var md = markdown("Bold");
			expect(md).toMatch(/\*{2}Bold\*{2}/);
		});

		it("should be able to convert 'Bold' to '**Bold**'", function() {
			var md = markdown("Bold");
			expect(md).toMatch(/\*{2}Bold\*{2}/);
		});

		it("should be able to convert 'Italic' to '_Italic_'", function() {
			var md = markdown("Italic");
			expect(md).toMatch(/\_Italic\_/);
		});

		it("should be able to convert 'Italic' to '_Italic_'", function() {
			var md = markdown("Italic");
			expect(md).toMatch(/\_Italic\_/);
		});

		it("should be able to convert '<title>This is document Title</title>' to '# This is document Title\\n\\n'", function() {
			var md = markdown("<title>This is document Title</title>");
			expect(md).toMatch(/\# This is document Title\n\n/);
		});

		it("should be able trim text inside inline elements", function() {
			var md = markdown(" String ");
			expect(md).toMatch(/\*{2}String\*{2}/);
		});

		it("should be able to convert 'This has a block word' to 'This has a **block** word'", function() {
			var md = markdown("This has a block word");
			expect(md).toMatch(/This has a \*{2}block\*{2} word/);
		});

		it("should be able to convert '
' to '- - -\\n\\n'", function() {
			var md = markdown("
");
			expect(md).toEqual("- - -\n\n");
		});

		it("should be able to convert '
' to '  \\n'", function() {
			var md = markdown("this is text before break
this is text after break");
			expect(md).toMatch("  \n");
		});

		it("should be able to convert 'This has blocked and italicized texts.' to 'This has **blocked and _italicized_** texts.'", function() {
			var md = markdown("This has blocked and italicized texts.");
			expect(md).toMatch(/This has \*{2}blocked and \_italicized\_\*{2} texts\./);
		});

		it("should be able to convert 'this is text before hr
this is text after hr' to 'this is text before hr  \\nthis is text after hr'", function() {
			var md = markdown("this is text before hr
this is text after hr");
			expect(md).toMatch("this is text before hr\n\n- - -\n\nthis is text after hr");
		});

		it("should be able to convert 'this is text before break
this is text after break' to 'this is text before break  \\nthis is text after break'", function() {
			var md = markdown("this is text before break
this is text after break");
			expect(md).toMatch("this is text before break  \nthis is text after break");
		});

		it("should be able to convert '
This is a paragraph. This is the second sentence.
' to 'This is a paragraph. This is the second sentence.\\n\\n'", function() {
			var md = markdown("
This is a paragraph. This is the second sentence.
");
			expect(md).toEqual("This is a paragraph. This is the second sentence.\n\n");
		});

		it("should be able to convert 'this is text before paragraph
This is a paragraph
this is text after paragraph' to 'this is text before paragraph\nThis is a paragraph\n\nthis is text after paragraph'", function() {
			var md = markdown("this is text before paragraph
This is a paragraph
this is text after paragraph");
			expect(md).toEqual("this is text before paragraph\n\nThis is a paragraph\n\nthis is text after paragraph");
		});

		it("should be able to convert span element", function() {
			var md = markdown("this is span element");
			expect(md).toEqual(" this is span element ");

			md = markdown("beforethis is span elementafter");
			expect(md).toEqual("before this is span element after");

			md = markdown("before this is span element after");
			expect(md).toEqual("before this is span element after");
		});

		it("should be able to convert '
This is blockquoted
' to '> This is blockquoted'", function() {
			var md = markdown("
This is blockquoted
");
			expect(md).toMatch("> This is blockquoted");
		});

		it("should be able to convert nested blockquotes", function() {
			var md = markdown("
This is blockquoted
This is nested blockquoted

");
			expect(md).toMatch("> This is blockquoted\n\n> > This is nested blockquoted");
		});

		//enable when wordwrap ie enabled
	//	var html = "
This is a paragraph. Followed by a blockquote.

This is a blockquote which will be truncated at 75 characters width. It will be somewhere around here.

";
	//	html += "
Some list for you:

item a

item b

So which one do you choose?
";
	//	it("should be able to convert a block of html", function() {
	//		var md = markdown(html);
	//		var md_str = "This is a paragraph\. Followed by a blockquote\.\n\n\> \nThis is a blockquote which will be truncated at 75 characters width\. It \nwill be somewhere around here\.\n\nSome list for you:\n\n\* item a\n\* item b\n\nSo which one do you choose\?\n\n";
	//		expect(md).toEqual(md_str);
	//	});

		it("should be able to convert unordered list", function() {
			var md = markdown("

item a

item b

");
			expect(md).toMatch(/\* item a\n\* item b\n/);
		});

		it("should be able to convert ordered list", function() {
			var md = markdown("

item 1

item 2

");
			expect(md).toMatch(/1\. item 1\n1\. item 2\n/);
		});

		it("should be able to convert nested lists", function() {
			var md = markdown("

item a

item aa

item bb

item b

");
			expect(md).toMatch(/\* item a\n  \* item aa\n  \* item bb\n\* item b\n/);
		});

		it("should not convert empty list items", function() {
			var md = markdown("

item 1

");
			expect(md).toMatch(/1\. item 1\n/);

			md = markdown("

item 1

");
			expect(md).toMatch(/\* item 1\n/);
		});

		it("should be able to convert images inline style", function() {
			var md = markdown("", {"inlineStyle": true});
			var expected = "![Example Image](/img/62838.jpg \"Free example image\")\n\n";
			expect(md).toEqual(expected);
		});

		it("should be able to convert images reference style", function() {
			var md = markdown("");
			var expected = "![Example Image][0]\n\n[0]: /img/62838.jpg";
			expect(md).toEqual(expected);

			//if alt is empty then title should be used
			md = markdown("");
			var expected = "![Free example image title][0]\n\n[0]: /img/62838.jpg";
			expect(md).toEqual(expected);

		});

		it("should be able to convert images as block elements", function() {
			var md = markdown("beforeafter");
			var expected = "before\n\n![Example Image][0]\n\nafter\n\n[0]: /img/62838.jpg";
			expect(md).toEqual(expected);

			var md = markdown("beforeafter", {"inlineStyle": true});
			var expected = "before\n\n![Example Image](/img/62838.jpg \"Free example image\")\n\nafter";
			expect(md).toEqual(expected);
		});

		it("should not convert images if url is empty", function() {
			var md = markdown("");
			expect(md).toEqual("");
		});

		it("should be able to properly convert links reference style", function() {
			var html = "Visit Example";
			html += "text1";
			html += "Visit Example1";
			html += "text2";
			html += "Visit Example";

			//urls should not be duplicated in reference style
			var expected = "[Visit Example][0]text1[Visit Example1][1]text2[Visit Example][0]";
			expected += "\n\n";
			expected += "[0]: http://www.example.com\n";
			expected += "[1]: http://www.example1.com";

			var md = markdown(html);
			expect(md).toEqual(expected);
		});

		it("should be able to convert links inline style", function() {
			var md = markdown("Visit Example", {"inlineStyle": true});
			expect(md).toEqual("[Visit Example](http://www.example.com \"Example\")");
		});

		it("should not convert if link has no text to display", function() {
			var html = "";
			md = markdown(html);
			expect(md).toEqual("");

			html = "
\n";
			html += "	\n";
			html += "
";

			md = markdown(html);
			expect(md).toEqual("");
		});

		it("should convert elements with child elements surrounded by whitespace", function() {
			var html = "
\n\t
\n\t\tYahoo! Finance\n\t
\n
";
			md = markdown(html);
			expect(md).toEqual("## [Yahoo! Finance][0]\n\n[0]: http://finance.yahoo.com");

			html = "\n\tHello\n\t";
			md = markdown(html);
			expect(md).toEqual(" **Hello** ");
		});

		it("should convert image wrapped in anchor to markdown that can be rendered using showdown - inline style parsing", function() {
			var md = markdown("", {"inlineStyle": true});
			var expected = "[![Example Image](/img/62838.jpg \"Free example image\")](/exec/j/4/?pid=62838&lno=1&afsrc=1)";
			expect(md).toEqual(expected);
		});

		it("should convert image wrapped in anchor to markdown that can be rendered using showdown - reference style parsing", function() {
			var md = markdown("", {"inlineStyle": false});
			var expected = "[![Example Image](/img/62838.jpg \"Free example image\")](/exec/j/4/?pid=62838&lno=1&afsrc=1)";

			var html = "\n\t\n\t";
			md = markdown(html, {"inlineStyle": false});
			expect(md).toEqual(expected);

		});

		it("should output only text of empty links", function() {
			var md = markdown("Empty Link Text", {"inlineStyle": true});
			var expected = "Empty Link Text";
			expect(md).toEqual(expected);
		});

		//tags that have no parsing rules e.g. form elements 'head', 'style', script', 'link' 'option', 'noscript', 'noframes', 'input', 'button', 'select', 'textarea', and 'label'
		it("should not convert any elements that have no parsing rules. ", function() {
			var html = "<link rel='openid.delegate' href='http://jeresig.livejournal.com/'/>";
			html +=	"";

			var md = markdown(html);
			expect(md).toEqual("");
		});

		//tables
		it("should be able to convert tables", function() {
			var html = "
";
			html += "
Row 1 Cell 1	Row 1 Cell 2
";
			html += "
Row 2 Cell 1	Row 2 Cell 2
";
			html += "
";

			var md = markdown(html);

			var expected = "Row 1 Cell 1\n\n";
			expected += "Row 1 Cell 2\n\n";
			expected += "Row 2 Cell 1\n\n";
			expected += "Row 2 Cell 2\n\n";

			expect(md).toEqual(expected);
		});

		it("should be able to convert tables with lists", function() {
			var html = "
";
			html += "

List Item 1

List Item 2

	";
			html += "

List Item 3

List Item 4

";
			html += "
";

			var md = markdown(html);
			var expected = "* List Item 1\n* List Item 2\n\n* List Item 3\n* List Item 4\n\n";

			expect(md).toEqual(expected);
		});

		//test empty block element
		it("should not convert emptyt tags", function() {
			var md = markdown("

");
			expect(md).toEqual("");

			md = markdown("

");
			expect(md).toEqual("");

			md = markdown("        ");
			expect(md).toEqual("");
		});

		it("should collape whitespace to single space for text nodes", function() {
			var md = markdown("
     a     b     c\n     d
");
			expect(md).toEqual(" a b c d \n\n");

			md = markdown("

     a     b     c\n     d
");
			expect(md).toEqual(" a b c d \n\n");

			md = markdown("
1

     a     b     c\n     d
");
			expect(md).toEqual("1\n\na b c d \n\n");

			md = markdown("
     a     b     c\n     d
");
			expect(md).toEqual("# a b c d \n\n");
		});

		it("should trim anchor title and text", function() {
			var md = markdown("   Visit Example    ", {"inlineStyle": true});
			expect(md).toEqual("[Visit Example](http://www.example.com \"Example\")");

			md = markdown("   Visit Example    ", {"inlineStyle": false});
			expect(md).toEqual("[Visit Example][0]\n\n[0]: http://www.example.com");

			var html ="\n";
			html += "32\n";
			html += "comments\n";

			md = markdown(html);
			expect(md).toEqual("[32 comments][0]\n\n[0]: /blog/line-length-readability#comments");
		});

		it("should trim image alt and title", function() {
			var html = "";

			var md = markdown(html, {"inlineStyle": true});
			var expected = "![Example Image](/img/62838.jpg \"Free example image\")\n\n";
			expect(md).toEqual(expected);

			md = markdown(html);
			expected = "![Example Image][0]\n\n[0]: /img/62838.jpg";
			expect(md).toEqual(expected);
		});

		it("should be able to convert image followed by link to markdown that can be renderd using showdown", function() {
			var html = "
\n";
			html += "	\n";
			html += "	Memento\n";
			html += "
";

			var md = markdown(html);
			var expected = "![Feed][0]\n\n[Memento][1]\n\n";
			expected += "[0]: http://mementodb.com/images/logo.png\n";
			expected += "[1]: http://mementodb.com";

			expect(md).toEqual(expected);
		});

		it("should be able to convert list items with linked images as only linked images", function() {
			var html = "before list";
				html += "
\n";
				html += "

";
				html += "

";
				html += "
\n";
			var md = markdown(html);
			var expected = "before list\n\n";
			expected += "[![Watch the new iPad video](http://images.apple.com/home/images/promo_video_ipad_launch.png)](/ipad/#video)\n\n";
			expected += "[![Watch the new iPhone TV Ad](http://images.apple.com/home/images/promo_video_iphone4s_ad.png)](/iphone/videos/#tv-ads-datenight)\n\n";
			expect(md).toEqual(expected);
		});

		it("should be able to convert title", function() {
			var html = "<hgroup>\n";
			html += "\t
Nathen Harvey
\n";
			html += "\t
a blog
\n";
			html += "</hgroup>";
			var md = markdown(html);

			var expected = "# [Nathen Harvey][0]\n\n## a blog\n\n\n\n[0]: http://www.google.com";
			expect(md).toEqual(expected);
		});

		it("should be able to convert paragrphs in blocquotes", function() {
			var html="
\n";
	    	html+="\t
Lorem ipsum
\n";
	  		html+="\t
Lorem ipsum
\n";
			html+="
";

			var md = markdown(html);
			var expected = "> Lorem ipsum\n\n> Lorem ipsum\n\n";
			expect(md).toEqual(expected);

			html = "
\n";
	    	html+="\t
Lorem ipsum
\n";
			html+="
\n";
			html+="
\n";
	    	html+="\t
Lorem ipsum
\n";
			html+="
"

			md = markdown(html);
			expect(md).toEqual(expected);
		});

		it("should be able to convert pre block", function() {
			var html = "
";
			html += "	void main(String[] args) {\n";
			html += "		System.out.println(\"Hello Markdown\");\n";
			html += "	}";
			html += "
";

			var expected = "    " + "	void main(String[] args) {\n";
			expected += "    " + "		System.out.println(\"Hello Markdown\");\n";
			expected += "    " + "	}";
			expected += "\n\n";

			var md = markdown(html);
			expect(md).toEqual(expected);
		});

		it("should be able to convert pre block with html tags", function() {
			var html = "
\n";
			html += "
\n";
			html += "	this is span inside pre block\n";
			html += "	this is paragraph inside pre block\n";
			html += "
";
			html += "
";

			var expected = "    " + "\n\n\n";
			expected += "    " + "	this is span inside pre block\n";
			expected += "    " + "	this is paragraph inside pre block\n";
			expected += "    " + "\n";
			expected += "\n";

			var md = markdown(html);
			expect(md).toEqual(expected);
		});

		it("should be able to convert
...
 blocks", function() {
			var html= "
{% blockquote [author[, source]] [link] [source_link_title] %}";
			html+= "\nQuote string";
			html+= "\n{% endblockquote %}";
			html+= "\n
";

			var md = markdown(html);
			expected="    {% blockquote [author[, source]] [link] [source_link_title] %}";
	        expected+="\n    Quote string";
	        expected+="\n    {% endblockquote %}";
	        expected+="\n    ";
	        expected+="\n\n";

	        expect(md).toEqual(expected);
		});
	});
}

describe("markdownDOMParser", function() {
	it("parser function should be able to echo input html", function() {
		var html = "
 Hmm
 Hello markdown converter
";
		var result ="";

		markdownHTMLParser(html, {
			start: function(tag, attrs, unary) {
				result+="<"+tag.toLowerCase();

				for ( var i = 0; i < attrs.length; i++ ) {
					result += " " + attrs[i].name + '="' + attrs[i].value + '"';
				}

				result += (unary ? "/" : "") + ">";
			},
			chars: function(text) {
				result += text;
			},
			end: function(tag) {
				result+="</"+tag.toLowerCase()+">";
			},
			comment: function(text) {
				result += "";
			}
		});
		expect(html).toEqual(result);
	});
});

//TODO add test for block function
//TODO test bookmarklet links
//TODO add test for xss protection
//TODO test parsing of iframe/frame element
//TODO add tests to verify hidden nodes are not parsed
//TODO add more unit tests based on official markdown syntax
//TODO improve formatting of pre/code tags


text:
require 'tempfile'

module Veewee
  module Provider
    module Vmfusion
      module BoxCommand
        # This function 'exports' the box based on the definition
        def export_vmfusion(options)
          case options["export_type"]
          when "ova"
            debug="--X:logToConsole=true --X:logLevel=\"verbose\""
            debug=""
            flags="--compress=9"

            if File.exists?("#{name}.ova")
              if options["force"]
                env.logger.debug("#{name}.ova exists, but --force was provided")
                env.logger.debug("removing #{name}.ova first")
                FileUtils.rm("#{name}.ova")
                env.logger.debug("#{name}.ova removed")
              else
                raise Veewee::Error, "export file #{name}.ova already exists. Use --force option to overwrite."
              end
            end

            # before exporting the system needs to be shut down
            ensure_vm_stopped(options)

            # otherwise the debug log will show - The specified virtual disk needs repair
            env.ui.info "Exporting VM to #{options["export_type"]}"
            shell_exec("#{File.dirname(vmrun_cmd).shellescape}#{"/VMware OVF Tool/ovftool".shellescape} #{debug} #{flags} #{vmx_file_path.shellescape} #{name}.ova")
          when "vagrant"
            debug=""
            flags="-tt=OVF"

            ensure_vm_stopped(options)

            optimize_disk

            # get a temp dir
            Dir.mktmpdir do |tmpdir|
              env.ui.info "Exporting VM to #{options["export_type"]} box"
              FileUtils.cp_r(Dir["#{vm_path}/*"],tmpdir)

              # Inject a Vagrantfile unless one is provided
              if options['vagrantfile']
                FileUtils.cp(options['vagrantfile'], File.join(tmpdir, 'Vagrantfile'))
              else
                File.open(File.join(tmpdir, 'Vagrantfile'), 'w') {|f| f.write(template_vagrantfile()) }
              end
              #Inject a metadata.json file
              File.open(File.join(tmpdir, 'metadata.json'), 'w') {|f| f.write(template_metadatafile()) }

              # Tar it up into the destination
              pwd = Dir.pwd
              shell_exec("cd #{tmpdir} && tar -czf #{File.join(pwd, name)}.box *")
            end
          end

        end

        protected

        def ensure_vm_stopped(options={})
          # Need to check binary first
          if self.running?.data
            # Wait for the shutdown to complete
            begin
              Timeout::timeout(60) do
                self.halt(options)
                loop do
                  sleep 4
                  break unless self.running?.data
                end
              end
            rescue TimeoutError => ex
              raise Veewee::Error,ex
            end
          end
        end

        def template_metadatafile
          %Q({"provider": "vmware_fusion"}\n)
        end

        def template_vagrantfile
          <<EOF
Vagrant::Config.run do |config|
  # This Vagrantfile is auto-generated by `vagrant package` to contain
  # the MAC address of the box. Custom configuration should be placed in
  # the actual `Vagrantfile` in this box.
  config.vm.base_mac = "080027AC6969"
end

# Load include vagrant file if it exists after the auto-generated
# so it can override any of the settings
include_vagrantfile = File.expand_path("../include/_Vagrantfile", __FILE__)
load include_vagrantfile if File.exist?(include_vagrantfile)
EOF
        end

        def optimize_disk
          current_dir=Dir.pwd
          FileUtils.chdir(vm_path)
          env.ui.info "Optimizing Disk"
          shell_exec("#{File.dirname(vmrun_cmd).shellescape}#{"/vmware-vdiskmanager".shellescape} -d #{name}.vmdk")
          shell_exec("#{File.dirname(vmrun_cmd).shellescape}#{"/vmware-vdiskmanager".shellescape} -k #{name}.vmdk")

          [name,
           "#{name}.plist",
           "quicklook-cache.png"
          ].each do |file|
            File.delete(file) if File.exist?(file)
          end

          Dir.glob("*.log").map { |f| File.delete(f) }
          FileUtils.chdir(current_dir)
        end

      end
    end
  end
end


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "spotibad.h"

struct song_node *table[26];

void add_song_node(struct song_node *track) {
  char first_letter = track->artist[0];
  int i = first_letter >= 97 ? first_letter - 97 : first_letter - 65; // Getting the index of the alphabet[] array
  table[i] = insert_order(track->name, track->artist, table[i]);
  printf("Added song: %s - %s \n", track->artist, track->name);
}

struct song_node * song_search(char song[], char artist[]) {
  int i = artist[0]; // Getting the index of the alphabet[] array
  i = i >= 97 ? i - 97 : i - 65; // Getting the index of the alphabet[] array
  return locate_song(song, artist, table[i]);
}

struct song_node * artist_search (char artist[]){
  int i = artist[0]; // Getting the index of the alphabet[] array
  i = i >= 97 ? i - 97 : i - 65; // Getting the index of the alphabet[] array
  return locate_artist(artist, table[i]);
}

void print_letter(char directory){
  //If Directory is a lowercase letter, returns it as an uppercase
  int i = directory >= 97 ? directory - 97 : directory - 65; // Getting the index of the alphabet[] array
  print_list(table[i]);

}

void print_artists_songs(char artist[]){
  int i = artist[0]; // Getting the index of the alphabet[] array
  i = i >= 97 ? i - 97 : i - 65; // Getting the index of the alphabet[] array
  struct song_node* head = locate_artist(artist, table[i]);
  while(head && (! strcmp(head->artist, artist))) {
    print_song(head);
    head = head->next;
  }
}

void print_library(){
  int i;
  for(i = 0; i < 26; i++){
    struct song_node * head = table[i];
    print_list(head);
  }
}

/* WILL NOT WORK IF THE PRNG HAS NOT BEEN SEEDED.
*/
void shuffle(int val) {
  int i;

  while (val--) {
    i = rand() % 26;

    if (table[i]) {
      print_song(rand_song(table[i]));
    } else {
      val++;
    }
  }
}

void delete_song(struct song_node *song){
  char first_letter = song->artist[0];
  int i = first_letter >= 97 ? first_letter - 97 : first_letter - 65; // Getting the index of the alphabet[] array
  table[i] = remove_node(table[i], song);
}

void clear_all(){
  int i;
  for(i = 0; i < 26; i++){
    free_list(table[i]);
  }
}


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../../polymer/polymer.html">
<link rel="import" href="../iron-control-state.html">
<link rel="import" href="../iron-button-state.html">

<script>

  Polymer({

    is: 'test-control',

    behaviors: [
      Polymer.IronControlState
    ]

  });

</script>

<script>

  Polymer({

    is: 'test-button',

    behaviors: [
      Polymer.IronControlState,
      Polymer.IronButtonState
    ],

    _buttonStateChanged: function() {

    }

  });

</script>

<dom-module id="nested-focusable">

  <template>
    <input id="input">
  </template>

</dom-module>

<script>

  Polymer({

    is: 'nested-focusable',

    behaviors: [
      Polymer.IronControlState
    ]

  });

</script>

<dom-module id="test-light-dom">

  <template>
    <slot></slot>
  </template>

</dom-module>

<script>

  Polymer({

    is: 'test-light-dom',

    behaviors: [
      Polymer.IronControlState,
      Polymer.IronButtonState
    ]

  });

</script>


text:
package org.wso2.carbon.identity.user.functionality.mgt.model;

/**
 * A data model class to define the functionality lock status element.
 */
public class FunctionalityLockStatus {

    public static final FunctionalityLockStatus UNLOCKED_STATUS = new FunctionalityLockStatus(false, 0, null, null);

    private boolean lockStatus;
    private long unlockTime;
    private String lockReasonCode;
    private String lockReason;

    public FunctionalityLockStatus(boolean lockStatus, long unlockTime, String lockReasonCode, String lockReason) {

        this.lockStatus = lockStatus;
        this.unlockTime = unlockTime;
        this.lockReasonCode = lockReasonCode;
        this.lockReason = lockReason;
    }

    /**
     * Checks the status of the functionality. Whether the functionality is locked or unlocked.
     *
     * @return The status for the functionality.
     */
    public boolean getLockStatus() {

        return lockStatus;
    }

    /**
     * Set the locked/unlocked status for the functionality.
     *
     * @param lockStatus Status for the functionality.
     */
    public void setLockStatus(boolean lockStatus) {

        this.lockStatus = lockStatus;
    }

    /**
     * Get the unlock time for the functionality.
     *
     * @return The unlock time for the functionality.
     */
    public long getUnlockTime() {

        return unlockTime;
    }

    /**
     * Set the unlock time for the functionality.
     *
     * @param unlockTime Unlock time for the functionality.
     */
    public void setUnlockTime(long unlockTime) {

        this.unlockTime = unlockTime;
    }

    /**
     * Get the lock reason code for the functionality.
     *
     * @return The lock reason code for the functionality.
     */
    public String getLockReasonCode() {

        return lockReasonCode;
    }

    /**
     * Set the lock reason code for the functionality.
     *
     * @param lockReasonCode Lock reason code of the functionality.
     */
    public void setLockReasonCode(String lockReasonCode) {

        this.lockReasonCode = lockReasonCode;
    }

    /**
     * Get the lock reason for the functionality.
     *
     * @return The lock reason for the functionality.
     */
    public String getLockReason() {

        return lockReason;
    }

    /**
     * Set the lock reason for the functionality.
     *
     * @param lockReason Lock reason for the functionality.
     */
    public void setLockReason(String lockReason) {

        this.lockReason = lockReason;
    }
}


text:
<?php
/**
  Document Header
  ===============
  HTML Header for Meta, Script and CSS Loading

*/
?>
<head>
  <meta charset="<?php bloginfo( 'charset' ); ?>">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ': '; } ?><?php bloginfo('name'); ?></title>
  <link rel="profile" href="http://gmpg.org/xfn/11">
  <link rel="stylesheet" href="<?= get_template_directory_uri(); ?>/assets/css/style.css">
  <link rel="shortcut icon" href="<?= get_template_directory_uri(); ?>/assets/system/favicon.png">
  <?php wp_head(); ?>
  <?php if (WP_ENV != 'local') : ?>
    <script>document.getElementsByTagName('html')[0].classList.add('plj')</script>
  <?php endif; ?>
</head>


text:
select c1.cohort_definition_id,
  810 as analysis_id,
  cast( '' as varchar(1) ) as stratum_1, cast( '' as varchar(1) ) as stratum_2, cast( '' as varchar(1) ) as stratum_3, cast( '' as varchar(1) ) as stratum_4,
  COUNT_BIG(distinct o1.observation_id) as count_value
into #results_810
from
@CDM_schema.observation o1
inner join #HERACLES_cohort_subject c1
on o1.person_id = c1.subject_id
left join @CDM_schema.observation_period op1
on op1.person_id = o1.person_id
and o1.observation_date >= op1.observation_period_start_date
and o1.observation_date <= op1.observation_period_end_date
where op1.person_id is null
group by c1.cohort_definition_id
;


text:
#include "webserver.h"

#include "mongoose/mongoose.h"

#include <QByteArray>
#include <QHostAddress>
#include <QMetaType>
#include <QThread>
#include <QUrl>
#include <QVector>
#include <QDebug>

namespace UrlEncodedParser {

QString unescape(QByteArray in)
{
    // first step: decode '+' to spaces
    for(int i = 0; i < in.length(); ++i) {
        QByteRef c = in[i];
        if (c == '+') {
            c = ' ';
        }
    }
    // now decode as usual
    return QUrl::fromPercentEncoding(in);
};

// Parse a application/x-www-form-urlencoded data string
QVariantMap parse(const QByteArray &data) {
    QVariantMap ret;
    if (data.isEmpty()) {
        return ret;
    }
    foreach(const QByteArray &part, data.split('&')) {
        const int eqPos = part.indexOf('=');
        if (eqPos == -1) {
            ret[unescape(part)] = "";
        } else {
            const QByteArray key = part.mid(0, eqPos);
            const QByteArray value = part.mid(eqPos + 1);
            ret[unescape(key)] = unescape(value);
        }
    }

    return ret;
}

}

static void *callback(mg_event event,
                      mg_connection *conn,
                      const mg_request_info *request)
{
    WebServer* server = static_cast<WebServer*>(request->user_data);
    if (server->handleRequest(event, conn, request)) {
        // anything non-null... pretty ugly, why not simply a bool??
        return server;
    } else {
        return 0;
    }
}

WebServer::WebServer(QObject *parent, Config *config)
    : REPLCompletable(parent)
    , m_config(config)
    , m_ctx(0)
{
    setObjectName("WebServer");
    qRegisterMetaType<WebServerResponse*>("WebServerResponse*");
}

WebServer::~WebServer()
{
    close();
}

bool WebServer::listenOnPort(const QString& port, const QVariantMap& opts)
{
    ///TODO: listen on multiple ports?
    close();

    QVector<const char*> options;
    options <<  "listening_ports" << qstrdup(qPrintable(port));
    options << "enable_directory_listing" << "no";
    if (opts.value("keepAlive", false).toBool()) {
        options << "enable_keep_alive" << "yes";
    }
    options << NULL;
    ///TODO: more options from m_config?
    m_ctx = mg_start(&callback, this, options.data());
    if (!m_ctx) {
        return false;
    }

    m_port = port;
    return true;
}

QString WebServer::port() const
{
    return m_port;
}

void WebServer::close()
{
    if (m_ctx) {
        m_closing = 1;
        {
            // make sure we wake up all pending responses, such that mg_stop()
            // can be called without deadlocking
            QMutexLocker lock(&m_mutex);
            foreach(WebServerResponse* response, m_pendingResponses) {
                response->close();
            }
        }
        mg_stop(m_ctx);
        m_ctx = 0;
        m_port.clear();
    }
}

bool WebServer::handleRequest(mg_event event, mg_connection *conn, const mg_request_info *request)
{
    if (event != MG_NEW_REQUEST) {
        return false;
    }

    if (m_closing) {
        return false;
    }

    // Modelled after http://nodejs.org/docs/latest/api/http.html#http.ServerRequest
    QVariantMap requestObject;

    ///TODO: encoding?!

    if (request->request_method)
        requestObject["method"] = QString::fromLocal8Bit(request->request_method);
    if (request->http_version)
        requestObject["httpVersion"] = QString::fromLocal8Bit(request->http_version);
    if (request->status_code >=0)
        requestObject["statusCode"] = request->status_code;

    QByteArray uri(request->uri);
    if (uri.startsWith('/'))
        uri = '/' + QUrl::toPercentEncoding(QString::fromLatin1(request->uri + 1), "/?&#");
    if (request->query_string)
        uri.append('?').append(QByteArray(request->query_string));
    requestObject["url"] = uri.data();

#if 0
    // Non-standard and thus disable for the time being.
    requestObject["isSSL"] = request->is_ssl;
    requestObject["remoteIP"] = QHostAddress(request->remote_ip).toString();;
    requestObject["remotePort"] = request->remote_port;
    if (request->remote_user)
        requestObject["remoteUser"] = QString::fromLocal8Bit(request->remote_user);
#endif

    QVariantMap headersObject;
    for (int i = 0; i < request->num_headers; ++i) {
        QString key = QString::fromLocal8Bit(request->http_headers[i].name);
        QString value = QString::fromLocal8Bit(request->http_headers[i].value);
        headersObject[key] = value;
    }
    requestObject["headers"] = headersObject;

    if ((requestObject["method"] == "POST" || requestObject["method"] == "PUT")
        && headersObject.contains("Content-Length"))
    {
        bool ok = false;
        uint contentLength = headersObject["Content-Length"].toUInt(&ok);
        if (ok) {
            contentLength += 1; // allow \0 at end
            char * data = new char[contentLength];
            int read = mg_read(conn, data, contentLength);
            QByteArray rawData(data, read);
            requestObject["rawData"] = QVariant(rawData);
            // Check if the 'Content-Type' requires decoding
            if (headersObject["Content-Type"] == "application/x-www-form-urlencoded") {
                requestObject["post"] = UrlEncodedParser::parse(rawData);
            } else {
                requestObject["post"] = QVariant(rawData);
            }
            delete[] data;
        }
    }

    // Emit signal that is catched by the PhantomJS callback,
    // then wait until response.close() was called from
    // the PhantomJS script.
    //
    // This is achieved using the wait semaphore, which is
    // acquired here, in the background thread, and released
    // in WebServerResponse::close() i.e. the foreground thread
    QSemaphore wait;
    WebServerResponse responseObject(conn, &wait);
    responseObject.moveToThread(thread());

    {
        if (m_closing) {
            return false;
        }
        QMutexLocker lock(&m_mutex);
        if (m_closing) {
            return false;
        }
        m_pendingResponses << (&responseObject);
    }
    newRequest(requestObject, &responseObject);
    wait.acquire();
    {
        if (m_closing) {
            return false;
        }
        QMutexLocker lock(&m_mutex);
        if (m_closing) {
            return false;
        }
        m_pendingResponses.removeOne(&responseObject);
    }
    return true;
}

void WebServer::initCompletions()
{
    // Add completion for the Dynamic Properties of the 'webpage' object
    // properties
    addCompletion("clipRect");
    // functions
    addCompletion("listen");
    addCompletion("close");
    // callbacks
    addCompletion("onNewRequest");
}

//BEGIN WebServerResponse

WebServerResponse::WebServerResponse(mg_connection* conn, QSemaphore* close)
    : REPLCompletable()
    , m_conn(conn)
    , m_statusCode(200)
    , m_headersSent(false)
    , m_close(close)
{
}

const char* responseCodeString(int code)
{
    // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
    switch (code) {
        case 100:
            return "Continue";
        case 101:
            return "Switching Protocols";
        case 200:
            return "OK";
        case 201:
            return "Created";
        case 202:
            return "Accepted";
        case 203:
            return "Non-Authoritative Information";
        case 204:
            return "No Content";
        case 205:
            return "Reset Content";
        case 206:
            return "Partial Content";
        case 300:
            return "Multiple Choices";
        case 301:
            return "Moved Permanently";
        case 302:
            return "Found";
        case 303:
            return "See Other";
        case 304:
            return "Not Modified";
        case 305:
            return "Use Proxy";
        case 307:
            return "Temporary Redirect";
        case 400:
            return "Bad Request";
        case 401:
            return "Unauthorized";
        case 402:
            return "Payment Required";
        case 403:
            return "Forbidden";
        case 404:
            return "Not Found";
        case 405:
            return "Method Not Allowed";
        case 406:
            return "Not Acceptable";
        case 407:
            return "Proxy Authentication Required";
        case 408:
            return "Request Timeout";
        case 409:
            return "Conflict";
        case 410:
            return "Gone";
        case 411:
            return "Length Required";
        case 412:
            return "Precondition Failed";
        case 413:
            return "Request Entity Too Large";
        case 414:
            return "Request-URI Too Long";
        case 415:
            return "Unsupported Media Type";
        case 416:
            return "Requested Range not Satisfiable";
        case 417:
            return "Expectation Failed";
        case 500:
            return "Internal Server Error";
        case 501:
            return "Not Implemented";
        case 502:
            return "Bad Gateway";
        case 503:
            return "Service Unavailable";
        case 504:
            return "Gateway Timeout";
        case 505:
            return "HTTP Version Not Supported";
        case 306:
            // unused: fallthrough
        default:
            return "";
    }
}

void WebServerResponse::writeHead(int statusCode, const QVariantMap &headers)
{
    ///TODO: what is the best-practice error handling in javascript? exceptions?
    Q_ASSERT(!m_headersSent);
    m_headersSent = true;
    m_statusCode = statusCode;
    mg_printf(m_conn, "HTTP/1.1 %d %s\r\n", m_statusCode, responseCodeString(m_statusCode));
    QVariantMap::const_iterator it = headers.constBegin();
    while(it != headers.constEnd()) {
        qDebug() << "Response Header key:" << it.key() << "value:" << it.value().toString();
        mg_printf(m_conn, "%s: %s\r\n", qPrintable(it.key()), qPrintable(it.value().toString()));
        ++it;
    }
    mg_write(m_conn, "\r\n", 2);
}

void WebServerResponse::write(const QString &body)
{
    if (!m_headersSent) {
        writeHead(m_statusCode, m_headers);
    }
    ///TODO: encoding?!
    const QByteArray data = body.toLocal8Bit();
    mg_write(m_conn, data.constData(), data.size());
}

void WebServerResponse::close()
{
    m_close->release();
}

int WebServerResponse::statusCode() const
{
    return m_statusCode;
}

void WebServerResponse::setStatusCode(int code)
{
    ///TODO: what is the best-practice error handling in javascript? exceptions?
    Q_ASSERT(!m_headersSent);
    m_statusCode = code;
}

QString WebServerResponse::header(const QString &name) const
{
    return m_headers.value(name).toString();
}

void WebServerResponse::setHeader(const QString &name, const QString &value)
{
    ///TODO: what is the best-practice error handling in javascript? exceptions?
    Q_ASSERT(!m_headersSent);
    m_headers.insert(name, value);
}

QVariantMap WebServerResponse::headers() const
{
    return m_headers;
}

void WebServerResponse::setHeaders(const QVariantMap &headers)
{
    ///TODO: what is the best-practice error handling in javascript? exceptions?
    Q_ASSERT(!m_headersSent);
    m_headers = headers;
}

void WebServerResponse::initCompletions()
{
    // Add completion for the Dynamic Properties of the 'webpage' object
    // properties
    addCompletion("statusCode");
    addCompletion("headers");
    // functions
    addCompletion("writeHead");
    addCompletion("write");
}

//END WebServerResponse


text:
/*
 *
 */
package io.github.pflima92.plyshare.common.web;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
public enum Parameter {

	DELIVERY("alias");

	@Getter
	private final String value;
}


text:
<?php

/**
 * Zend_Translate_Adapter_Xliff
 */
require_once 'Zend/Translate/Adapter/Xliff.php';

/**
 * @category   Zend
 * @package    Zend_Translate
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Translate
 */
class Zend_Translate_Adapter_XliffTest extends PHPUnit_Framework_TestCase
{
    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite("Zend_Translate_Adapter_XliffTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    public function testCreate()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en.xliff', 'en');
        $this->assertTrue($adapter instanceof Zend_Translate_Adapter_Xliff);

        try {
            $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/nofile.xliff', 'en');
            $this->fail("exception expected");
        } catch (Zend_Translate_Exception $e) {
            $this->assertContains('is not readable', $e->getMessage());
        }

        try {
            $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/failed.xliff', 'en');
            $this->fail("exception expected");
        } catch (Zend_Translate_Exception $e) {
            $this->assertContains('Mismatched tag at line', $e->getMessage());
        }
    }

    /**
     * @group ZF-12012
     */
    public function testErrorOnCreateIncludesFilename()
    {
        try {
            $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/nofile.xliff', 'en');
            $this->fail("exception expected");
        } catch (Zend_Translate_Exception $e) {
            $this->assertContains('nofile.xliff', $e->getMessage());
        }
    }

    public function testToString()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en.xliff', 'en');
        $this->assertEquals('Xliff', $adapter->toString());
    }

    public function testTranslate()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en.xliff', 'fr');
        $this->assertEquals('Message 1 (en)', $adapter->translate('Message 1'));
        $this->assertEquals('Message 1 (en)', $adapter->_('Message 1'));
        $this->assertEquals('Message 6', $adapter->translate('Message 6'));
        $this->assertEquals('Küchen Möbel (en)', $adapter->translate('Cooking furniture'));
        $this->assertEquals('Cooking furniture (en)', $adapter->translate('Küchen Möbel'));
    }

    public function testIsTranslated()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en.xliff', 'en');
        $this->assertTrue($adapter->isTranslated('Message 1'));
        $this->assertFalse($adapter->isTranslated('Message 6'));
        $this->assertTrue($adapter->isTranslated('Message 1', true));
        $this->assertTrue($adapter->isTranslated('Message 1', true, 'en'));
        $this->assertFalse($adapter->isTranslated('Message 1', false, 'es'));
    }

    public function testLoadTranslationData()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en.xliff', 'fr');
        $this->assertEquals('Message 1 (en)', $adapter->translate('Message 1'));
        $this->assertEquals('Message 4 (en)', $adapter->translate('Message 4'));
        $this->assertEquals('Message 2', $adapter->translate('Message 2', 'ru'));
        $this->assertEquals('Message 1', $adapter->translate('Message 1', 'xx'));
        $this->assertEquals('Message 1 (en)', $adapter->translate('Message 1', 'fr_FR'));

        try {
            $adapter->addTranslation(dirname(__FILE__) . '/_files/translation_en.xliff', 'xx');
            $this->fail("exception expected");
        } catch (Zend_Translate_Exception $e) {
            $this->assertContains('does not exist', $e->getMessage());
        }

        $adapter->addTranslation(dirname(__FILE__) . '/_files/translation_en2.xliff', 'de', array('clear' => true));
        $this->assertEquals('Nachricht 1', $adapter->translate('Message 1'));
        $this->assertEquals('Message 4', $adapter->translate('Message 4'));
    }

    public function testOptions()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en.xliff', 'en');
        $adapter->setOptions(array('testoption' => 'testkey'));
        $expected = array(
            'testoption'      => 'testkey',
            'clear'           => false,
            'content'         => dirname(__FILE__) . '/_files/translation_en.xliff',
            'scan'            => null,
            'locale'          => 'en',
            'ignore'          => '.',
            'disableNotices'  => false,
            'log'             => false,
            'logMessage'      => 'Untranslated message within \'%locale%\': %message%',
            'logUntranslated' => false,
            'reload'          => false,
        );
        $options = $adapter->getOptions();

        foreach ($expected as $key => $value) {
            $this->assertArrayHasKey($key, $options);
            $this->assertEquals($value, $options[$key]);
        }

        $this->assertEquals('testkey', $adapter->getOptions('testoption'));
        $this->assertTrue(is_null($adapter->getOptions('nooption')));
    }

    public function testClearing()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en.xliff', 'fr');
        $this->assertEquals('Message 1 (en)', $adapter->translate('Message 1'));
        $this->assertEquals('Message 6', $adapter->translate('Message 6'));
        $adapter->addTranslation(dirname(__FILE__) . '/_files/translation_en2.xliff', 'de', array('clear' => true));
        $this->assertEquals('Nachricht 1', $adapter->translate('Message 1'));
        $this->assertEquals('Message 5', $adapter->translate('Message 5'));
    }

    public function testLocale()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en.xliff', 'en');
        $this->assertEquals('en', $adapter->getLocale());
        $locale = new Zend_Locale('en');
        $adapter->setLocale($locale);
        $this->assertEquals('en', $adapter->getLocale());

        try {
            $adapter->setLocale('nolocale');
            $this->fail("exception expected");
        } catch (Zend_Translate_Exception $e) {
            $this->assertContains('does not exist', $e->getMessage());
        }

        set_error_handler(array($this, 'errorHandlerIgnore'));
        $adapter->setLocale('it');
        restore_error_handler();
        $this->assertEquals('it', $adapter->getLocale());
    }

    public function testList()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en.xliff', 'en');
        $this->assertEquals(array('en' => 'en', 'fr' => 'fr'), $adapter->getList());
        $adapter->addTranslation(dirname(__FILE__) . '/_files/translation_en2.xliff', 'de');
        $this->assertEquals(array('en' => 'en', 'de' => 'de', 'fr' => 'fr'), $adapter->getList());
        $this->assertTrue($adapter->isAvailable('de'));
        $locale = new Zend_Locale('en');
        $this->assertTrue($adapter->isAvailable($locale));
        $this->assertFalse($adapter->isAvailable('sr'   ));
    }

    public function testOptionLocaleDirectory()
    {
        require_once 'Zend/Translate.php';
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/testxliff', 'de', array('scan' => Zend_Translate::LOCALE_DIRECTORY));
        $this->assertEquals(array('de' => 'de', 'en' => 'en', 'fr' => 'fr'), $adapter->getList());
        $this->assertEquals('Nachricht 1', $adapter->translate('Message 1'));
    }

    public function testOptionLocaleFilename()
    {
        require_once 'Zend/Translate.php';
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/testxliff', 'de', array('scan' => Zend_Translate::LOCALE_FILENAME));
        $this->assertEquals(array('de' => 'de', 'en' => 'en', 'fr' => 'fr'), $adapter->getList());
        $this->assertEquals('Nachricht 1', $adapter->translate('Message 1'));
    }

    public function testIsoEncoding()
    {
        $adapter = new Zend_Translate_Adapter_Xliff(dirname(__FILE__) . '/_files/translation_en3.xliff', 'en', array('useId' => false));
        $this->assertEquals('Message 1 (en)', $adapter->translate('Message 1'));
        $this->assertEquals('Message 1 (en)', $adapter->_('Message 1'));

        if (PHP_OS == 'AIX') {
            return;
            // 'Charsets below are not supported on AIX';
        }

        $this->assertEquals(iconv('UTF-8', 'ISO-8859-1', 'Küchen Möbel (en)'), $adapter->translate('Cooking furniture'));
        $this->assertEquals('Cooking furniture (en)', $adapter->translate(iconv('UTF-8', 'ISO-8859-1', 'Küchen Möbel')));
    }

    /**
     * Ignores a raised PHP error when in effect, but throws a flag to indicate an error occurred
     *
     * @param  integer $errno
     * @param  string  $errstr
     * @param  string  $errfile
     * @param  integer $errline
     * @param  array   $errcontext
     * @return void
     */
    public function errorHandlerIgnore($errno, $errstr, $errfile, $errline, array $errcontext)
    {
        $this->_errorOccurred = true;
    }
}

// Call Zend_Translate_Adapter_XliffTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_Translate_Adapter_XliffTest::main") {
    Zend_Translate_Adapter_XliffTest::main();
}