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

    <groupId>computerDataBase</groupId>
    <artifactId>computerDataBase</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>computerDataBase</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <maven.version>3.2</maven.version>
        <junit.version>4.12</junit.version>
        <jbehave.version>4.0.5</jbehave.version>
        <selenium.version>2.53.1</selenium.version>
        <restassured.version>2.9.0</restassured.version>
    </properties>

    <build>
        <testSourceDirectory>src/main/java</testSourceDirectory>
        <finalName>${project.artifactId}</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <testSource>${java.version}</testSource>
                    <testTarget>${java.version}</testTarget>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.16</version>
                <configuration>
                    <includes>
                        <include>**/*.java</include>
                    </includes>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jbehave/jbehave-core -->
        <dependency>
            <groupId>org.jbehave</groupId>
            <artifactId>jbehave-core</artifactId>
            <version>${jbehave.version}</version>
        </dependency>

        <dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${restassured.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

    </dependencies>
    <profiles>
        <profile>
            <id>FunctionalTests</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <configuration>
                            <skipTests>false</skipTests>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <version>2.18.1</version>
                        <configuration>
                            <includes>
                                <include>**/mapper/*.java</include>
                            </includes>
                            <skipTests>false</skipTests>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

redpajama_set_name: RedPajamaGithub


text:
title: banner
tags: banner,uikit
---


text:
@interface PodsDummy_Pods_LoginForm : NSObject
@end
@implementation PodsDummy_Pods_LoginForm
@end


text: Resir.filters *%w(erb haml markaby markdown sass textile)


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

namespace UtilEx
{
    public static class IntExtension
    {
        public static void Times(this int i, Action<int> action)
        {
            for (var j = 0; j < i; j++)
            {
                action(j);
            }
        }

        public static string ToBinary(this int i)
        {
            var numBaseConv = new NumericBaseConverter();
            return numBaseConv.ToBinary(Convert.ToUInt64(i));
        }

        public static string ToHex(this int i)
        {
            var numBaseConv = new NumericBaseConverter();
            return numBaseConv.ToHex(Convert.ToUInt64(i));
        }

        public static string ToBase36(this int i)
        {
            var numBaseConv = new NumericBaseConverter();
            return numBaseConv.ToBase36(Convert.ToUInt64(i));
        }

        public static string ToBase(this int i, int numericBase)
        {
            var numBaseConv = new NumericBaseConverter();
            return numBaseConv.ToBase(Convert.ToUInt64(i), numericBase);
        }
    }
}


text:
#import <UIKit/UIKit.h>

#import "ABI8_0_0RCTComponent.h"

@class ABI8_0_0RCTShadowView;

@interface UIView (ReactABI8_0_0) <ABI8_0_0RCTComponent>

/**
 * ABI8_0_0RCTComponent interface.
 */
- (NSArray<UIView *> *)ReactABI8_0_0Subviews NS_REQUIRES_SUPER;
- (UIView *)ReactABI8_0_0Superview NS_REQUIRES_SUPER;
- (void)insertReactABI8_0_0Subview:(UIView *)subview atIndex:(NSInteger)atIndex NS_REQUIRES_SUPER;
- (void)removeReactABI8_0_0Subview:(UIView *)subview NS_REQUIRES_SUPER;

/**
 * z-index, used to override sibling order in didUpdateReactABI8_0_0Subviews.
 */
@property (nonatomic, assign) NSInteger ReactABI8_0_0ZIndex;

/**
 * The ReactABI8_0_0Subviews array, sorted by zIndex. This value is cached and
 * automatically recalculated if views are added or removed.
 */
@property (nonatomic, copy, readonly) NSArray<UIView *> *sortedReactABI8_0_0Subviews;

/**
 * Updates the subviews array based on the ReactABI8_0_0Subviews. Default behavior is
 * to insert the sortedReactABI8_0_0Subviews into the UIView.
 */
- (void)didUpdateReactABI8_0_0Subviews;

/**
 * Used by the UIIManager to set the view frame.
 * May be overriden to disable animation, etc.
 */
- (void)ReactABI8_0_0SetFrame:(CGRect)frame;

/**
 * Used to improve performance when compositing views with translucent content.
 */
- (void)ReactABI8_0_0SetInheritedBackgroundColor:(UIColor *)inheritedBackgroundColor;

/**
 * This method finds and returns the containing view controller for the view.
 */
- (UIViewController *)ReactABI8_0_0ViewController;

/**
 * This method attaches the specified controller as a child of the
 * the owning view controller of this view. Returns NO if no view
 * controller is found (which may happen if the view is not currently
 * attached to the view hierarchy).
 */
- (void)ReactABI8_0_0AddControllerToClosestParent:(UIViewController *)controller;

/**
 * Responder overrides - to be deprecated.
 */
- (void)ReactABI8_0_0WillMakeFirstResponder;
- (void)ReactABI8_0_0DidMakeFirstResponder;
- (BOOL)ReactABI8_0_0RespondsToTouch:(UITouch *)touch;

#if ABI8_0_0RCT_DEV

/**
 Tools for debugging
 */

@property (nonatomic, strong, setter=_DEBUG_setReactABI8_0_0ShadowView:) ABI8_0_0RCTShadowView *_DEBUG_ReactABI8_0_0ShadowView;

#endif

@end


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * @author Simon Thoresen Hult
 */
public class PredicateOperatorTest {

    @Test
    void requireThatOperatorIsAPredicate() {
        assertTrue(Predicate.class.isAssignableFrom(PredicateOperator.class));
    }
}


text:
<?php
/**
 * This file contains the following classes: {@link SimpleCollector},
 * {@link SimplePatternCollector}.
 *
 * @author Travis Swicegood <development@domain51.com>
 * @package SimpleTest
 * @subpackage UnitTester
 * @version $Id: collector.php 1784 2008-04-26 13:07:14Z pp11 $
 */

/**
 * The basic collector for {@link GroupTest}
 *
 * @see collect(), GroupTest::collect()
 * @package SimpleTest
 * @subpackage UnitTester
 */
class SimpleCollector {

    /**
     * Strips off any kind of slash at the end so as to normalise the path.
     * @param string $path    Path to normalise.
     * @return string         Path without trailing slash.
     */
    protected function removeTrailingSlash($path) {
        if (substr($path, -1) == DIRECTORY_SEPARATOR) {
            return substr($path, 0, -1);
        } elseif (substr($path, -1) == '/') {
            return substr($path, 0, -1);
        } else {
            return $path;
        }
    }

    /**
     * Scans the directory and adds what it can.
     * @param object $test    Group test with {@link GroupTest::addTestFile()} method.
     * @param string $path    Directory to scan.
     * @see _attemptToAdd()
     */
    function collect(&$test, $path) {
        $path = $this->removeTrailingSlash($path);
        if ($handle = opendir($path)) {
            while (($entry = readdir($handle)) !== false) {
                if ($this->isHidden($entry)) {
                    continue;
                }
                $this->handle($test, $path . DIRECTORY_SEPARATOR . $entry);
            }
            closedir($handle);
        }
    }

    /**
     * This method determines what should be done with a given file and adds
     * it via {@link GroupTest::addTestFile()} if necessary.
     *
     * This method should be overriden to provide custom matching criteria,
     * such as pattern matching, recursive matching, etc.  For an example, see
     * {@link SimplePatternCollector::_handle()}.
     *
     * @param object $test      Group test with {@link GroupTest::addTestFile()} method.
     * @param string $filename  A filename as generated by {@link collect()}
     * @see collect()
     * @access protected
     */
    protected function handle(&$test, $file) {
        if (is_dir($file)) {
            return;
        }
        $test->addFile($file);
    }

    /**
     *  Tests for hidden files so as to skip them. Currently
     *  only tests for Unix hidden files.
     *  @param string $filename        Plain filename.
     *  @return boolean                True if hidden file.
     *  @access private
     */
    protected function isHidden($filename) {
        return strncmp($filename, '.', 1) == 0;
    }
}

/**
 * An extension to {@link SimpleCollector} that only adds files matching a
 * given pattern.
 *
 * @package SimpleTest
 * @subpackage UnitTester
 * @see SimpleCollector
 */
class SimplePatternCollector extends SimpleCollector {
    private $pattern;

    /**
     *
     * @param string $pattern   Perl compatible regex to test name against
     *  See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE}
     *  for full documentation of valid pattern.s
     */
    function __construct($pattern = '/php$/i') {
        $this->pattern = $pattern;
    }

    /**
     * Attempts to add files that match a given pattern.
     *
     * @see SimpleCollector::_handle()
     * @param object $test    Group test with {@link GroupTest::addTestFile()} method.
     * @param string $path    Directory to scan.
     * @access protected
     */
    protected function handle(&$test, $filename) {
        if (preg_match($this->pattern, $filename)) {
            parent::handle($test, $filename);
        }
    }
}
?>


text:
'''
This code updates the smaller.db database.
To run this file, open a command prompt in this folder and run the command
python update_database.py
If you have any difficulties or questions, contact Max Vilgalys (vilgalys@mit.edu)
'''

print("Determining maximum date in database...")
# First find how current the database is - this finds the most recent month of data in
# smaller.db, so it won't pull any more recent data.
import sqlite3
import pandas
con = sqlite3.connect('smaller.db')
max_date = pandas.read_sql('select max(op_date) from data', con)
for i, row in max_date.iterrows():
    date = str(row[0])
max_month = date[0:2]
max_year = date[-4:]
print("Max date found: " + max_month + " " + max_year)

print()
print("Downloading additional zip files...")

from ftplib import FTP
import os.path

import zipfile
from pathlib2 import Path

ftp = FTP('ftp.epa.gov', timeout=60)
ftp.login()
ftp.cwd('dmdnload')
ftp.cwd('emissions')
ftp.cwd('hourly')
ftp.cwd('monthly')
years = []
ftp.retrlines('NLST', years.append)
parent_directory = ftp.pwd()

def zip_fetch(ftp, entry):
    print("Now fetching: " + entry)
    outfile = open('data/' + entry, 'wb')
    ftp.retrbinary('RETR ' + entry, outfile.write)
    outfile.close()
    return
states = ['wa', 'or', 'ca', 'id', 'nv', 'ut', 'az', 'nm', 'co', 'wy', 'mt', 'tx']
def inWest(string):
    return string[4:6] in states

if not os.path.exists('data'):
    os.makedirs('data')

def unzip(name):
    with zipfile.ZipFile(name, "r") as z:
        z.extractall('unzipped')

if not os.path.exists('unzipped'):
    os.makedirs('unzipped')

for year in years:
    if (int(year) < int(max_year)): continue
    ftp.cwd(str(year))
    files = []
    ftp.retrlines('NLST', files.append)
    for entry in files:
        if (int(year) == int(max_year) and int(entry[6:8]) <= int(max_month)) or not inWest(entry):
            continue
        try:
            zip_fetch(ftp, entry)

        except:
            pass
    for n_month in range(1, 13):
        for state in ['wa', 'or', 'ca', 'id', 'nv', 'ut', 'az', 'nm', 'co', 'wy', 'mt', 'tx']:
            month = str(n_month) if n_month > 9 else "0" + str(n_month)
            name = "data/" + str(year) + state + month + ".zip"
            if os.path.isfile(name):
            	print("Now unzipping: " + name )
                unzip(name)
    ftp.cwd('..')

# Begin reading in data, combining it
print("Reading data into database:")
import csv
con = sqlite3.connect("to_insert.db")
cur = con.cursor()

# Set up table to receive CEMS data
cur.execute('drop table if exists data;')
cur.execute(
"create table data( \
    state varchar, \
    facility_name varchar, \
    orispl_code int, \
    unitid varchar, \
    op_date date, \
    op_hour int, \
    op_time float, \
    gload float, \
    SO2_MASS float, \
    NOX_MASS float, \
    CO2_MASS float, \
    HEAT_INPUT float \
);")

# Iterate through files to read data into database
for year in years:
    print(year)
    for n_month in range(1, 13):
        for state in ['wa', 'or', 'ca', 'id', 'nv', 'ut', 'az', 'nm', 'co', 'wy', 'mt', 'tx']:
            month = str(n_month) if n_month > 9 else "0" + str(n_month)
            name = "unzipped/" + str(year) + state + month + ".csv"
            if os.path.isfile(name):
                with open(name, 'rb') as fin:
                    dr = csv.DictReader(fin)
                    try:
                        to_db = [(i['STATE'], i['FACILITY_NAME'], i['ORISPL_CODE'], i['UNITID'], i['OP_DATE'], i['OP_HOUR'], i['OP_TIME'], i['GLOAD (MW)'],
                                  i['SO2_MASS (lbs)'], i['NOX_MASS (lbs)'], i['CO2_MASS (tons)'], i['HEAT_INPUT (mmBtu)']) for i in dr]
                    except:
                        try:
                            to_db = [(i['STATE'], i['FACILITY_NAME'], i['ORISPL_CODE'], i['UNITID'], i['OP_DATE'], i['OP_HOUR'], i['OP_TIME'], i['GLOAD'],
                                  i['SO2_MASS'], i['NOX_MASS'], i['CO2_MASS'], i['HEAT_INPUT']) for i in dr]
                        except:
                            print(name)
#                     print to_db
                    cur.executemany("insert into data (STATE, FACILITY_NAME, ORISPL_CODE, UNITID, OP_DATE, \
OP_HOUR, OP_TIME, GLOAD, SO2_MASS, NOX_MASS, CO2_MASS, HEAT_INPUT ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", to_db)

con.commit()

cur.execute('drop table if exists labels;')
cur.execute(
"create table labels( \
    state varchar, \
    facility_name varchar, \
    orispl_code int, \
    unitid varchar, \
    year int, \
    county varhcar, \
    latitude float, \
    longitude float, \
    fuel_type varchar, \
    fule_type_secondary varchar \
);")

with open('EPADownload/labels.csv', 'rb') as fin:
    dr = csv.DictReader(fin)
    to_db = [(i['State'],  i[' Facility Name'], i[' Facility ID (ORISPL)'], i[' Unit ID'], i[' Year'], i[' County'],
              i[' Facility Latitude'], i[' Facility Longitude'], i[' Fuel Type (Primary)'], i[' Fuel Type (Secondary)']) for i in dr]
cur.executemany("insert into labels (    state, facility_name, orispl_code, unitid, year, \
    county, latitude, longitude, fuel_type, fule_type_secondary \
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", to_db)
con.commit()
con.close()

print("Combining databases: ")

con = sqlite3.connect("smaller.db")
cur = con.cursor()
cur.execute("ATTACH 'to_insert.db' as cems;")
cur.execute("INSERT into data select test.state as state, test.facility_name as name,\
 test.orispl_code as orispl_code, test.unitid as unitid, op_date, year, op_hour, op_time, gload, SO2_MASS, NOX_MASS, CO2_MASS,\
 HEAT_INPUT as heat_input, county, latitude, longitude, fuel_type, fule_type_secondary as fuel_type_2, \
 CASE WHEN (fuel_type is 'Natural Gas' or fuel_type is 'Pipeline Natural Gas' or fuel_type is 'Natural Gas, Pipeline Natural Gas')    THEN ('NG') ELSE (fuel_type) END as fuel_actual \
 from cems.data as test, cems.labels as labels \
 where substr(test.op_date, -4) is cast(labels.year as varchar) \
 AND labels.orispl_code is test.orispl_code AND test.unitid is labels.unitid;")
cur.execute("delete from data where state is 'TX' and (county is not 'El Paso' or name is 'Montana Power Station');")
cur.execute("vacuum")

con.commit()

print("Mostly done! Just cleaning up a bit")

import shutil
import os
shutil.rmtree('data')
shutil.rmtree('unzipped')
os.remove('to_insert.db')

con.close()


text:
Authors: Chris Dalton <cid@hpi.com>, Nigel Edwards <nigel.edwards@hpe.com>,
Theo Koulouris <theo.koulouris@hpe.com>

# Split Kernel

Project links:
- okernel sources on GitHub: https://github.com/linux-okernel/linux-okernel
- Userspace components and supporting material:
  https://github.com/linux-okernel/linux-okernel-components

Similar to the nested-kernel work for BSD by Dautenhahn et al[1], the aim
of the split kernel (okernel) is to introduce a level of intra-kernel
protection into the kernel so that, amongst other things, we can offer
lifetime guarantees over kernel code and data integrity.  Unlike the BSD-
based nested kernel work, we are focused on the Linux kernel (not BSD) and
do make use of HW virtualization features such as Extended Page Tables
(EPT) or equivalent to provide protection from malicious kernel
changes. (Our initial prototype is based on Intel x86, but the
intention is to be architecture neutral so we can apply it to other
architectures, including AMD and ARM.)

The split kernel provides a (protected) virtualized view of the kernel
for processes entering the kernel through exceptions, syscalls and
interrupts. Though we make use of hardware features designed to
support virtualization, we do not virtualize at the full virtual
machine level (like KVM or VMware, for example).  Instead conceptually
our model is closer to the approach prototyped by the DUNE[2] project
where they virtualize much higher up at the user space process
level. DUNE uses the hardware virtualization features to support
virtualization within the user space context of a Linux process to
safely expose privileged hardware features to user programs. We
instead take a cut-line lower down in the OS stack and include the
virtualization of the kernel space context of a process.  This kernel
virtualization allows us to introduce a level of intra-kernel
protection into the Linux kernel.

Our initial prototype consists of a combination of fairly extensive
modifications to the existing DUNE Linux kernel module (which itself
derives from KVM) and a relatively small number of select
modifications to the core Linux kernel code to support the virtualized
kernel cut-line.

In terms of operation, a process can be switched into 'outer-kernel'
mode which includes creating an EPT 'container' (lower level set of
page tables) for it. After switching, the process resumes running in a
non-root (NR) mode VMCS context even when in kernel context.

(In the remainder of this README we use root-mode or R-mode to
describe a process which is has full visibility of the page tables:
upper and lower. NR-mode or non-root mode describes a process which
only has visibility of the upper level page tables.)

With this model, the majority of kernel code can be run within the EPT
'container', offering an enhanced memory protection mechanism whilst
maintaining a single shared kernel image. A small handler loop within
the kernel for each process (thread) handles transitions from NR-mode
to R-mode where necessary to support VMEXITS and provide a privileged
operations interface.

Once a process is in NR-mode, the ability to make changes to kernel
memory is controlled by permissions on both the upper and lower level
page tables. Our security goal is to use the lower level page tables
to prevent a NR-mode process making malicious changes to the
kernel. For example, as far as possible it should not be able to write
code or data pages NR-mode, or if changes are made, they are isolated
to the NR-mode context.

If a process in NR-mode attempts to change the kernel memory in
conflict with permissions in the lower-level page tables, a VMEXIT (in
the current prototype which uses Intel VMX) is triggered. R-mode is
then entered where the permission violation can be handled.

# Integration with LinuxKit

Custom Linux distributions utilizing the split kernel can be readily built
using LinuxKit by simply specifying an okernel image in the `kernel` section
of the LinuxKit OS image YAML specification. See the sample YAML files provided
in [examples/](https://github.com/linuxkit/linuxkit/tree/master/projects/okernel/examples) for more details.

## Building the split kernel image for LinuxKit

 - `make` will build and package the latest version of the split kernel
   for LinuxKit, by    pulling sources from the top-of-tree of the
   okernel project GitHub    (https://github.com/linux-okernel/linux-okernel).
 - Alternatively, a specific version of the kernel can be built
   by setting the 'KERNEL' environment variable to the appropriate
   value, e.g.: `make KERNEL=ok-4.13-rc7`. The value MUST correspond
   to a legitimate okernel tag present in the project GitHub
   (https://github.com/linux-okernel/linux-okernel/tags) beginning
   with __"ok-"__.
   `make KERNEL=latest` will build the top-of-tree release, equivalent to `make`.

`make kvmod` or `make KERNEL=NNNNNNNN kvmod` where "NNNNNNNN" is the release
string corresponding to a kernel version, will build the kernel
vulnerability emulation kernel module for that kernel, useful for testing.

## Enabling NR-mode protections in LinuxKit
By default, okernel will treat processes like any standard Linux kernel, i.e. no
R-mode/NR-mode split is applied when processes are created. This is by design to
assist development and enable coexistence of normal and protected processes in
the same environment. A consequence of that is that processes must be explicitly
launched in NR-mode.

In early versions of LinuxKit we provided a lightly-modified version of the
default 'init' container to ensure runc launched in NR-mode and by extension all
its children processes/containers got instantiated in NR-mode as well.

Recent changes to how LinuxKit implements init made this approach obsolete. We
are in the process of developing an alternative (and hopefully more elegant)
way to launch containers in NR-mode (Aug 2017).

Note that because okernel utilizes the processor's VMX facilities, okernel
LinuxKit images with full NR-mode operation can only be run in baremetal
environments. If no processes are switched to NR-mode, okernel will boot and
operate normally inside a VM, however in this scenario it offers no benefits
compared to a standard Linux kernel.
We are investigating nested virtualization support to enable running okernel
inside VMs.

# Limitations and Caveats

The current implementation does not have any protection of the kernel
in place yet. It is a demonstration that you can create processes and
run them in NR-mode using EPTs with a shared kernel. As a further
demonstration of the concept, it implements protected memory pages,
whereby a process may request a protected memory page which will not
be mapped into the EPTs for other processes.

## Roadmap

The next step, and the subject of our ongoing research is to design
the memory protection architecture for the kernel. Examples of the
things that we are considering protecting from root mode processes
are:
 - Protection of the page tables (no NR mode process can modify a
   page table)
 - Protection of kernel executable code (RX only)
 - Protection of kernel data structures (RO)

# References

- [1] Nested Kernel: An Operating System Architecture for Intra-Kernel
Privilege Separation, Nathan Dautenhahn, Theodoros Kasampalis, Will
Dietz, John Criswell, Vikram Adve, ASPLOS '15, Proceedings of the
Twentieth International Conference on Architectural Support for
Programming Languages and Operating Systems, March 2015.
- [2] Dune: Safe user-level access to privileged CPU features, Adam
Belay, Andrea Bittau, Ali Mashtizadeh, David Terei, David Mazières,
and Christos Kozyrakis, OSDI '12, Proceedings of the 10th USENIX
Symposium on Operating Systems Design and Implementation, October 2012.


text:
'''
@author: jnaous
'''
from datetime import datetime, timedelta
from django.db import models
from expedient.clearinghouse.project.models import Project
from expedient.clearinghouse.aggregate.models import Aggregate
from django.contrib.auth.models import User
from expedient.common.permissions.models import ObjectPermission, Permittee
from expedient.clearinghouse.aggregate.utils import get_aggregate_classes
import logging, uuid
from django.db.models import signals
from expedient.common.messaging.models import DatedMessage
import traceback
from expedient.common.utils.mail import send_mail # Wrapper for django.core.mail__send_mail
from django.conf import settings
from expedient.common.timer.models import Job
#from expedient.common.timer.exceptions import JobAlreadyScheduled
from expedient.common.utils.modelfields import LimitedDateTimeField
from expedient.common.middleware import threadlocals
from expedient.common.utils.validators import asciiValidator, descriptionLightValidator
from expedient.clearinghouse.slice.utils import *

logger = logging.getLogger("slice.models")

def _get_slice_max_date():
    return datetime.now() + timedelta(days=settings.MAX_SLICE_LIFE)

class Slice(models.Model):
    '''
    Holds information about reservations across aggregates
    @ivar name: The name of the Slice
    @type name: L{str}
    @ivar description: Short description of the slice
    @type description: L{str}
    @ivar project: Project in which this slice belongs
    @type project: L{models.ForeignKey} to L{Project}
    @ivar owner: Original creator of the slice
    @type owner: C{User}
    @ivar started: Has this slice been reserved with the aggregates yet?
    @type started: C{bool}
    @ivar modified: Has this slice been modified since it was last reserved?
    @type modified: C{bool}
    @ivar expiration_date: Date and time of when the slice is going to
        expire in local time.
    @type expiration_date: L{datetime.datetime} instance
    @ivar aggregates: Read-only property returning all aggregates that can
        be used by the project (i.e. for which the project has the
        "can_use_aggregate" permission).
    @type aggregates: C{QuerySet} of L{Aggregate}s
    '''

    name = models.CharField(max_length=200, unique=True, validators=[asciiValidator])
    description = models.TextField(validators=[descriptionLightValidator])
    project = models.ForeignKey(Project)
    owner = models.ForeignKey(User, related_name="owned_slices")
    started = models.BooleanField(default=False, editable=False)
    modified = models.BooleanField(default=False, editable=False)
    uuid = models.CharField(max_length=200, default = "", unique=True, editable =False)
    expiration_date = LimitedDateTimeField(
        default=datetime.now() + timedelta(days=settings.SLICE_DEFAULT_EXPIRATION_TIME),
        help_text="Enter a date and time. The date should be in the"
            " following format: 'YYYY-MM-DD'. And for the time: 'HH:MM:SS'."
            " The expiration date cannot be later than %s days from"
            " now." % settings.MAX_SLICE_LIFE,
        max_date=_get_slice_max_date,
   )

    def __unicode__(self):
        return u"Slice '%s' in project '%s'" % (self.name, self.project.name)

    def start(self, user):
        """
        Should be an idempotent operation on the aggregates.
        """
        # check the expiration date
	# XXX: Expiration mechanism review needed
        #if self.expiration_date <= datetime.now():
        #    raise Exception("Slice expired. Update slice expiration time.")

	from vt_plugin.models.VtPlugin import VtPlugin

        logger.debug("Called start_slice on %s: %s" % (self, self.name))
        aggs = enumerate(self.aggregates.all())

        started_aggs = list()
        exceptions = list()

        for i, agg in aggs:
            logger.debug("starting slice on agg %s" % agg.name)
            try:
                agg.as_leaf_class().start_slice(self)
                started_aggs.append(agg)
            except Exception, e:
                logger.error("Error starting slice on agg %s" % agg.name)
                # try to stop slice on all previously started aggregates

                #Error is in a VT AM, can continue
                #if isinstance(agg.as_leaf_class(),VtPlugin):
                #    try:
                #        agg.as_leaf_class().stop_slice(self)
                #    except Exception, e2:
                #            # error stopping slice
                #            logger.error(traceback.format_exc())
                #            DatedMessage.objects.post_message_to_user(
                #            msg_text="Error stopping slice %s on "
                #            "aggregate %s" % (self, agg.name),
                #            user=user, msg_type=DatedMessage.TYPE_ERROR)
                #            # raise the original exception raised starting the slice.
                #    exceptions.append(e)
                ##Error is on a OF AM, can not start slice, and should stop all the AMs
                #else:
                for ragg in started_aggs:
                    try:
                        if not isinstance(agg.as_leaf_class(),VtPlugin):
                            ragg.as_leaf_class().stop_slice(self)
                    except Exception, e2:
                        # error stopping slice
                        logger.error(traceback.format_exc())
                        DatedMessage.objects.post_message_to_user(
                        msg_text="Error stopping slice %s on "
                        "aggregate %s" % (self, ragg.name),
                        user=user, msg_type=DatedMessage.TYPE_ERROR)
                # raise the original exception raised starting the slice.
                print e
                raise Exception(parseFVexception(e))

        # all is well
        self.started = True
        self.modified = False
        self.save()
        return exceptions

    def stop(self, user):
        """
        Should be an idempotent operation on the aggregates.
        """
        for agg in self.aggregates.all():
            agg.as_leaf_class().stop_slice(self)
        self.started = False
        self.save()

    def _get_aggregates(self):
        """Get all aggregates that can be used by the slice
        (i.e. for which the slice has the "can_use_aggregate" permission).
        """
        agg_ids = []
        agg_classes = get_aggregate_classes()
        permittee = Permittee.objects.get_as_permittee(self)
        for agg_class in agg_classes:
            agg_ids.extend(
                ObjectPermission.objects.filter_for_class(
                    agg_class,
                    permission__name="can_use_aggregate",
                    permittees=permittee,
                ).values_list("object_id", flat=True)
            )
        return Aggregate.objects.filter(pk__in=agg_ids)
#        return Aggregate.objects
    aggregates=property(_get_aggregates)

    @classmethod
    @models.permalink
    def get_create_url(cls, proj_id):
        "Returns the URL to create slices"
        return ("slice_create", (), {"proj_id": proj_id})

    @models.permalink
    def get_update_url(self):
        "Returns the URL to update slice info"
        return ("slice_update", (), {"slice_id": self.id})

    @models.permalink
    def get_detail_url(self):
        "Returns the URL for the slice detail page"
        return ("slice_detail", (), {"slice_id": self.id})

    @models.permalink
    def get_delete_url(self):
        "Returns the URL to delete a slice"
        return ("slice_delete", (), {"slice_id": self.id})

    @models.permalink
    def get_start_url(self):
        "Returns the URL to start the slice"
        return ("slice_start", (), {"slice_id": self.id})

    @models.permalink
    def get_stop_url(self):
        "Returns the URL to stop the slice"
        return ("slice_stop", (), {"slice_id": self.id})

    @models.permalink
    def get_agg_add_url(self):
        "Returns the URL to add an aggregate to a slice"
        return ("slice_add_agg", (), {"slice_id": self.id})

    @models.permalink
    def get_agg_update_url(self, aggregate):
        "Returns URL to update an aggregate's info related to the slice"
        return ("slice_update_agg", (), {
            "slice_id": self.id,
            "agg_id": aggregate.id})

    @models.permalink
    def get_agg_remove_url(self, aggregate):
        "Returns URL to remove aggregate from slice"
        return ("slice_remove_agg", (), {
            "slice_id": self.id,
            "agg_id": aggregate.id})

    @models.permalink
    def get_rsc_management_url(self):
        "Returns the URL at which to select a UI plugin."
        return ("slice_manage_resources", (), {"slice_id": self.id})

def stop_slice_before_delete(sender, **kwargs):
    """Before deleting a slice, make sure it is stopped"""
    try:
        kwargs["instance"].stop()
    except:
        pass
signals.pre_delete.connect(stop_slice_before_delete, Slice)

# Deal with expired slices ##################################################

def stop_expired_slices():
    """Find expired slices and stop them, sending an email to the owner."""

    expired_slices = Slice.objects.filter(
        expiration_date__lte=datetime.now(), started=True)

    for slice in expired_slices:
        threadlocals.push_frame(user=slice.owner)
        try:
            slice.stop(slice.owner)
        except:
            logger.error(
                "Error stopping expired slice"
                " %s: %s" % (slice, traceback.format_exc()))
        threadlocals.pop_frame()
        try:
            send_mail(
                "Your slice %s expired." % slice,
                "Your slice %s has been stopped because it expired on %s."
                "Before you restart your slice, you will need to update the "
                "slice's expiration date." % (slice, slice.expiration_date),
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[slice.owner.email],
            )
        except:
            logger.error(
                "Error sending expired slice "
                "email to user: %s" % traceback.format_exc())

def notify_slice_expirations():
    """Notify owners that their slices will expire soon."""

    expiration_time = datetime.now() + timedelta(
        seconds=settings.SLICE_EXPIRATION_NOTIFICATION_TIME)

    almost_expired_slices = Slice.objects.filter(
        expiration_date__lte=expiration_time, started=True)

    for slice in almost_expired_slices:
        try:
            send_mail(
                "Your slice %s is almost expired." % slice,
                "Your slice %s is almost expired. If you don't do anything, "
                "it will expired on %s. "
                "To renew your slice, you will need to update the "
                "slice's expiration date." % (slice, slice.expiration_date),
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[slice.owner.email],
            )
        except:
            logger.error(
                "Error sending almost expired slice "
                "email to user: %s" % traceback.format_exc())

# schedule jobs
# XXX: Expiration mechanism review needed
#try:
#    Job.objects.schedule_post_syncdb(settings.SLICE_EXPIRATION_CHECK_INTERVAL, stop_expired_slices)
#except JobAlreadyScheduled:
#    pass
#
#try:
#    Job.objects.schedule_post_syncdb(settings.SLICE_EXPIRATION_NOTIFICATION_TIME, notify_slice_expirations)
#except JobAlreadyScheduled:
#    pass


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Fixer\CastNotation;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author SpacePossum
 */
final class LowercaseCastFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, Tokens $tokens)
    {
        for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
            if (!$tokens[$index]->isCast()) {
                continue;
            }

            $tokens[$index]->setContent(strtolower($tokens[$index]->getContent()));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Cast should be written in lower case.',
            array(
                new CodeSample(
'<?php
    $a = (BOOLEAN) $b;
    $a = (BOOL) $b;
    $a = (INTEGER) $b;
    $a = (INT) $b;
    $a = (DOUBLE) $b;
    $a = (FLoaT) $b;
    $a = (reaL) $b;
    $a = (flOAT) $b;
    $a = (sTRING) $b;
    $a = (ARRAy) $b;
    $a = (OBJect) $b;
    $a = (UNset) $b;
    $a = (Binary) $b;
'
                ),
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isAnyTokenKindsFound(Token::getCastTokenKinds());
    }
}


text:
"""
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
"""
__author__ = 'Danyang'
# Definition for a  binary tree node
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def generateTrees(self, n):
        """
        dfs
        Catalan: https://www.youtube.com/watch?v=QdcujZTp_8M (Forth proof)
        :param n: integer
        :return: list of TreeNode
        """
        if n==0:
            return [None]

        return self.generate(1, n)

    def generate(self, start, end):
        """
        dfs without dp
        {number| number \in [start, end]}

        Follow the 1st proof of Catalan Number
        :param start: initial number in the array
        :param end: final number in the array
        :return: list of TreeNode
        """
        subtree_roots = []

        # trivial
        if start>end:
            subtree_roots.append(None)
            return subtree_roots

        # pivot
        # list of unique subtrees = list of unique left subtrees, pivot, list of unique right subtrees
        for pivot in range(start, end+1):
            left_subtree_roots = self.generate(start, pivot-1)  # no dp yet
            right_subtree_roots = self.generate(pivot+1, end)  # no dp yet

            for left_node in left_subtree_roots:
                for right_node in right_subtree_roots:
                    pivot_node = TreeNode(pivot)
                    pivot_node.left = left_node
                    pivot_node.right = right_node

                    subtree_roots.append(pivot_node)

        return subtree_roots


text:
// -------------------------------------------------------------------------------------------------
// <copyright file="DatabaseTests.cs" author="Christopher Sellers">
//   Copyright (C) 2017. All rights reserved.
//   https://github.com/cjdsellers/FuzzyLogic
//   the use of this source code is governed by the Apache 2.0 license
//   as found in the LICENSE.txt file.
// </copyright>
// -------------------------------------------------------------------------------------------------

namespace FuzzyLogic.UnitTests.InferenceTests
{
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using FuzzyLogic.Inference;
    using FuzzyLogic.TestKit;
    using Xunit;

    [SuppressMessage("StyleCop.CSharp.NamingRules", "*", Justification = "Reviewed. Suppression is OK within the Test Suite.")]
    [SuppressMessage("StyleCop.CSharp.DocumentationRules", "*", Justification = "Reviewed. Suppression is OK within the Test Suite.")]
    public class DatabaseTests
    {
        [Fact]
        internal void AddVariable_WhenVariableNotAlreadyInDatabase_AddsExpectedVariableToDatabase()
        {
            // Arrange
            var database = new Database();
            var label = Label.Create("pressure");

            // Act
            database.AddVariable(label, 3000);

            // Assert
            Assert.Equal(1, database.VariableCount);
        }

        [Fact]
        internal void ContainsVariable_WhenVariableNotContainedWithinDatabase_ReturnsFalse()
        {
            // Arrange
            var database = new Database();
            var label = Label.Create("pressure");

            // Act
            var result = database.ContainsVariable(label);

            // Assert
            Assert.False(result);
        }

        [Fact]
        internal void ContainsVariable_WhenVariableContainedWithinDatabase_ReturnsTrue()
        {
            // Arrange
            var database = new Database();
            var label = Label.Create("pressure");
            database.AddVariable(label, 3000);

            // Act
            var result1 = database.ContainsVariable(label);
            var result2 = database.ContainsVariable("pressure");

            // Assert
            Assert.True(result1);
            Assert.True(result2);
        }

        [Fact]
        internal void DeleteVariable_WhenVariableContainedWithinDatabase_ReturnsExpectedResultWhenQueried()
        {
            // Arrange
            var database = new Database();
            var label = Label.Create("pressure");
            database.AddVariable(label, 3000);
            var result1 = database.ContainsVariable(label);

            // Act
            database.DeleteVariable(label);
            var result2 = database.ContainsVariable(label);

            // Assert
            Assert.True(result1);
            Assert.False(result2);
            Assert.Equal(0, database.VariableCount);
        }

        [Fact]
        internal void DeleteAllVariables_WhenVariablesContainedWithinDatabase_ReturnsVariableCountZero()
        {
            // Arrange
            var database = new Database();
            var label1 = Label.Create("pressure");
            var label2 = Label.Create("temperature");
            var label3 = Label.Create("pump1");

            database.AddVariable(label1, 3000);
            database.AddVariable(label2, 25);
            database.AddVariable(label3, 199);

            // Tests the variables were added
            var result1 = database.VariableCount;

            // Act
            database.DeleteAllVariables();
            var result2 = database.VariableCount;

            // Assert
            Assert.Equal(3, result1);
            Assert.Equal(0, result2);
        }

        [Fact]
        internal void Variables_WhenVariablesContainedWithinDatabase_ReturnsExpectedList()
        {
            // Arrange
            var database = new Database();
            var label1 = Label.Create("pressure");
            var label2 = Label.Create("temperature");
            var label3 = Label.Create("pump1");

            database.AddVariable(label1, 3000);
            database.AddVariable(label2, 25);
            database.AddVariable(label3, 199);

            var expectedList = new List<Label> { label1, label2, label3 };

            // Act
            var result = database.VariableNames();

            // Assert
            Assert.Equal(expectedList, result);
        }

        [Fact]
        internal void GetData_WhenVariableContainedWithinDatabase_ThenReturnsExpectedData()
        {
            // Arrange
            var database = new Database();
            var pressure = Label.Create("pressure");

            database.AddVariable(pressure, 3000);

            var data = new DataPoint(pressure, 3001);

            // Act
            database.UpdateData(data);
            var result = database.GetData(pressure).Value;

            // Assert
            Assert.Equal(3001, result);
        }

        [Fact]
        internal void Update_WhenVariableContainedWithinDatabase_ThenReturnsExpectedData()
        {
            // Arrange
            var database = new Database();
            var pressure = Label.Create("pressure");

            database.AddVariable(pressure, 3000);

            var data = new DataPoint(pressure, 3001);

            // Act
            database.UpdateData(data);
            var result = database.GetData(pressure).Value;

            // Assert
            Assert.Equal(3001, result);
        }

        [Fact]
        internal void Update_GivenACollectionOfDataPoints_ThenReturnsExpectedData()
        {
            // Arrange
            var pressure = Label.Create(InputVariable.Pressure);
            var waterTemp = Label.Create(InputVariable.WaterTemp);
            var pumpSpeed = Label.Create(InputVariable.PumpSpeed);

            var database = new Database();
            database.AddVariable(pressure, 3000);
            database.AddVariable(waterTemp, 25);
            database.AddVariable(pumpSpeed);

            var dataCollection = new List<DataPoint>
                           {
                               new DataPoint(pressure, 3001),
                               new DataPoint(waterTemp, 24),
                               new DataPoint(pumpSpeed, 0)
                           };

            // Act
            database.UpdateData(dataCollection);

            var result1 = database.GetData(pressure).Value;
            var result2 = database.GetData(waterTemp).Value;
            var result3 = database.GetData(pumpSpeed).Value;

            // Assert
            Assert.Equal(3001, result1);
            Assert.Equal(24, result2);
            Assert.Equal(0, result3);
        }

        [Fact]
        internal void GetAllData_ReturnsExpectedData()
        {
            // Arrange
            var database = new Database();
            var label1 = Label.Create("pressure");
            var label2 = Label.Create("temperature");
            var label3 = Label.Create("pump1");

            database.AddVariable(label1, 3000);
            database.AddVariable(label2, 25);
            database.AddVariable(label3, 199);

            // Act
            var result = database.GetAllData();

            // Assert
            Assert.Equal(3, result.Count);
            Assert.Equal(3000, result[0].Value);
            Assert.Equal(25, result[1].Value);
            Assert.Equal(199, result[2].Value);
        }

        [Fact]
        internal void GetAllDataLabeled_ReturnsExpectedData()
        {
            // Arrange
            var database = new Database();
            var label1 = Label.Create("pressure");
            var label2 = Label.Create("temperature");
            var label3 = Label.Create("pump1");

            database.AddVariable(label1, 3000);
            database.AddVariable(label2, 25);
            database.AddVariable(label3, 199);

            // Act
            var result = database.GetAllDataLabeled();

            // Assert
            Assert.Equal(3, result.Count);
            Assert.Equal(3000, result[label1].Value);
            Assert.Equal(25, result[label2].Value);
            Assert.Equal(199, result[label3].Value);
        }
    }
}


text:
(function($) {$(function() {

    // encapsulate all LaterPay Javascript in function laterPayPostView
    function laterPayPostView() {
        var $o = {
                // post statistics pane
                postStatisticsPane              : $('#lp_js_postStatistics'),

                // post preview mode
                postPreviewModeForm             : $('#lp_js_postStatisticsPluginPreviewModeForm'),
                postPreviewModeToggle           : $('#lp_js_togglePostPreviewMode'),
                postPreviewModeInput            : $('#lp_js_postPreviewModeInput'),

                // post statistics pane visibility
                postStatisticsVisibilityForm    : $('#lp_js_postStatisticsVisibilityForm'),
                postStatisticsVisibilityToggle  : $('#lp_js_togglePostStatisticsVisibility'),
                postStatisticsVisibilityInput   : $('#lp_js_postStatisticsVisibilityInput'),

                // time passes
                timePass                        : '.lp_js_timePass',
                flipTimePassLink                : '.lp_js_flipTimePass',
                timePassPreviewPrice            : '.lp_js_timePassPreviewPrice',
                voucherCodeWrapper              : '#lp_js_voucherCodeWrapper',
                voucherCodeInput                : '.lp_js_voucherCodeInput',
                voucherRedeemButton             : '.lp_js_voucherRedeemButton',
                giftCardRedeemButton            : '.lp_js_giftCardRedeemButton',
                giftCardCodeInput               : '.lp_js_giftCardCodeInput',
                giftCardWrapper                 : '#lp_js_giftCardWrapper',
                giftCardActionsPlaceholder      : '.lp_js_giftCardActionsPlaceholder',
                giftsWrapper                    : $('.lp_js_giftsWrapper'),

                // placeholders for caching compatibility mode
                postContentPlaceholder          : $('#lp_js_postContentPlaceholder'),
                postStatisticsPlaceholder       : $('#lp_js_postStatisticsPlaceholder'),
                postRatingPlaceholder           : $('#lp_js_postRatingPlaceholder'),

                // purchase buttons and purchase links
                purchaseLink                    : '.lp_js_doPurchase',

                // content rating
                postRatingForm                  : $('.lp_js_ratingForm'),
                postRatingRadio                 : $('input[type=radio][name=rating_value]'),

                // strings cached for better compression
                hidden                          : 'lp_is-hidden',
                fadingOut                       : 'lp_is-fading-out',

                // premium content
                premiumBox                      : '.lp_js_premium-file-box',
            },

            recachePostStatisticsPane = function() {
                $o.postStatisticsPane              = $('#lp_js_postStatistics');
                $o.postPreviewModeForm             = $('#lp_js_postStatisticsPluginPreviewModeForm');
                $o.postPreviewModeToggle           = $('#lp_js_togglePostPreviewMode');
                $o.postPreviewModeInput            = $('#lp_js_postPreviewModeInput');
                $o.postStatisticsVisibilityForm    = $('#lp_js_postStatisticsVisibilityForm');
                $o.postStatisticsVisibilityToggle  = $('#lp_js_togglePostStatisticsVisibility');
                $o.postStatisticsVisibilityInput   = $('#lp_js_postStatisticsVisibilityInput');
            },

            recacheRatingForm = function() {
                $o.postRatingForm  = $('.lp_js_ratingForm');
                $o.postRatingRadio = $('input[type=radio][name=rating_value]');
            },

            bindPurchaseEvents = function() {
                // handle clicks on purchase links in test mode
                $('body')
                .on('mousedown', $o.purchaseLink, function() {
                    handlePurchaseInTestMode(this);
                })
                .on('click', $o.purchaseLink, function(e) {e.preventDefault();});

                // handle clicks on time passes
                $('body')
                .on('click', $o.flipTimePassLink, function() {
                    flipTimePass(this);
                })
                .on('click', $o.flipTimePassLink, function(e) {e.preventDefault();});
            },

            bindPostStatisticsEvents = function() {
                // toggle visibility of post statistics pane
                $o.postStatisticsVisibilityToggle
                .on('mousedown', function() {
                    togglePostStatisticsVisibility();
                })
                .on('click', function(e) {e.preventDefault();});

                // toggle plugin preview mode between 'preview as visitor' and 'preview as admin'
                $o.postPreviewModeToggle
                .on('change', function() {
                    togglePostPreviewMode();
                });
            },

            bindRatingEvents = function() {
                // save rating when input is selected
                $o.postRatingRadio
                .on('change', function() {
                    savePostRating();
                });
            },

            bindTimePassesEvents = function() {
                // redeem voucher code
                $($o.voucherRedeemButton)
                .on('mousedown', function() {
                    redeemVoucherCode($(this).parent(), $o.voucherCodeInput, false);
                })
                .on('click', function(e) {e.preventDefault();});

                $($o.giftCardRedeemButton)
                .on('mousedown', function() {
                    redeemVoucherCode($(this).parent(), $o.giftCardCodeInput, true);
                })
                .on('click', function(e) {e.preventDefault();});
            },

            redeemVoucherCode = function($wrapper, input, is_gift) {
                var code = $(input).val();

                if (code.length === 6) {
                    $.get(
                        lpVars.ajaxUrl,
                        {
                            action  : 'laterpay_redeem_voucher_code',
                            code    : code,
                            nonce   : lpVars.nonces.voucher,
                            link    : window.location.href
                        },
                        function(r) {
                            if (r.success) {
                                if (!is_gift) {
                                    // clear input
                                    $(input).val('');

                                    var has_matches = false,
                                        passId;
                                    $($o.timePass).each(function() {
                                        // check for each shown time pass, if the request returned updated data for it
                                        passId = $(this).data('pass-id');
                                        if (passId === r.pass_id) {
                                            // update purchase button price and url
                                            var priceWithVoucher = r.price +
                                                '' +
                                                    lpVars.default_currency +
                                                '';

                                            // update purchase button on time pass
                                            $(this)
                                                .find($o.purchaseLink)
                                                .attr('data-laterpay', r.url)
                                                .html(priceWithVoucher);

                                            // update price on time pass flipside as well
                                            $(this)
                                                .find($o.timePassPreviewPrice)
                                                .html(priceWithVoucher);

                                            has_matches = true;

                                            return false;
                                        }
                                    });

                                    if (has_matches) {
                                        // voucher is valid for at least one displayed time pass
                                        showVoucherCodeFeedbackMessage(lpVars.i18n.validVoucher, $wrapper);
                                    } else {
                                        // voucher is invalid for all displayed time passes
                                        showVoucherCodeFeedbackMessage(code + lpVars.i18n.invalidVoucher, $wrapper);
                                    }
                                } else {
                                    $('#fakebtn').attr('data-laterpay', r.url);
                                    // fire purchase event on hidden fake button
                                    YUI().use('node', 'node-event-simulate', function(Y) {
                                        Y.one('#fakebtn').simulate('click');
                                    });
                                }
                            } else {
                                // clear input
                                $(input).val('');

                                // voucher is invalid for all displayed time passes
                                showVoucherCodeFeedbackMessage(code + lpVars.i18n.invalidVoucher, $wrapper);
                            }
                        },
                        'json'
                    );
                } else {
                    // request was not sent, because voucher code is not six characters long
                    showVoucherCodeFeedbackMessage(lpVars.i18n.codeTooShort);
                }
            },

            showVoucherCodeFeedbackMessage = function(message, $wrapper) {
                var $feedbackMessage = $(
                                            '
' +
                                                message +
                                            '
'
                                        );

                $wrapper.prepend($feedbackMessage);

                $feedbackMessage = $('#lp_js_voucherCodeFeedbackMessage', $wrapper);
                $feedbackMessage
                .fadeIn(250)
                .click(function() {
                    // remove feedback message on click
                    removeVoucherCodeFeedbackMessage($feedbackMessage);
                });

                // automatically remove feedback message after 3 seconds
                setTimeout(function() {
                    removeVoucherCodeFeedbackMessage($feedbackMessage);
                }, 3000);
            },

            removeVoucherCodeFeedbackMessage = function($feedbackMessage) {
                $feedbackMessage.fadeOut(250, function() {
                    $feedbackMessage.unbind().remove();
                });
            },

            savePostRating = function() {
                $.post(
                    lpVars.ajaxUrl,
                    $o.postRatingForm.serializeArray(),
                    function(r) {
                        if (r.success) {
                            // replace rating form with thank you message and remove it after a few seconds
                            $('.lp_rating', $o.postRatingForm).addClass($o.fadingOut).html(r.message);
                            setTimeout(
                                function() {
                                    $o.postRatingForm.fadeOut(400, function() { $(this).remove(); });
                                },
                                4000
                            );
                        }
                    },
                    'json'
                );
            },

            loadRatingSummary = function() {
                $.get(
                    lpVars.ajaxUrl,
                    {
                        action  : 'laterpay_post_rating_summary',
                        post_id : lpVars.post_id,
                        nonce   : lpVars.nonces.rating
                    },
                    function(ratingSummary) {
                        if (ratingSummary) {
                            $o.postRatingPlaceholder.html(ratingSummary);
                        }
                    }
                );
            },

            loadGiftCards = function() {
                var ids     = [],
                    cards   = $o.giftsWrapper;

                // get all pass ids from wrappers
                $.each(cards, function(i) {
                    ids.push($(cards[i]).data('id'));
                });

                $.get(
                    lpVars.ajaxUrl,
                    {
                        action  : 'laterpay_get_gift_card_actions',
                        nonce   : lpVars.nonces.gift,
                        pass_id : ids,
                        link    : window.location.href
                    },
                    function(r) {
                        if (r.data) {
                            $.each(r.data, function(i) {
                                var gift    = r.data[i],
                                    $elem   = $($o.giftCardActionsPlaceholder + '_' + gift.id);

                                $elem.html(gift.html);

                                // add 'buy another gift card' after gift card
                                if (gift.buy_more) {
                                    // $elem.parent().after(gift.buy_more);
                                    $(gift.buy_more)
                                    .appendTo($elem.parent())
                                    .attr('href', window.location.href);
                                }
                            });

                            // remove gift code cookie if present
                            delete_cookie('laterpay_purchased_gift_card');
                        }
                    }
                );
            },

            loadPremiumUrls = function() {
                var ids   = [],
                    types = [],
                    boxes = $($o.premiumBox);

                // get all pass ids from wrappers
                $.each(boxes, function(i) {
                    ids.push($(boxes[i]).data('post-id'));
                    types.push($(boxes[i]).data('content-type'));
                });

                $.get(
                    lpVars.ajaxUrl,
                    {
                        action  : 'laterpay_get_premium_shortcode_link',
                        nonce   : lpVars.nonces.premium,
                        ids     : ids,
                        types   : types,
                        post_id : lpVars.post_id,
                    },
                    function(r) {
                        if (r.data) {
                            var url = null;
                            $.each(r.data, function(i) {
                                url = r.data[i];
                                $.each(boxes, function(j) {
                                    if ($(boxes[j]).data('post-id').toString() === i) {
                                        $(boxes[j]).prepend(url);
                                    }
                                });
                            });
                        }
                        initiateAttachmentDownload();
                    }
                );
            },

            loadPostStatistics = function() {
                $.get(
                    lpVars.ajaxUrl,
                    {
                        action  : 'laterpay_post_statistic_render',
                        post_id : lpVars.post_id,
                        nonce   : lpVars.nonces.statistic
                    },
                    function(data) {
                        if (data) {
                            $o.postStatisticsPlaceholder.before(data).remove();
                            renderPostStatisticsPane();
                        }
                    }
                );
            },

            renderPostStatisticsPane = function() {
                // make sure all objects are in the cache
                recachePostStatisticsPane();

                // bind events to post statistics pane
                bindPostStatisticsEvents();

                // render sparklines within post statistics pane
                $('.lp_js_sparklineBar', $o.postStatisticsPane).peity('bar', {
                    delimiter   : ';',
                    width       : 182,
                    height      : 42,
                    gap         : 1,
                    fill        : function(value, index, array) {
                                    var date        = new Date(),
                                        daysCount   = array.length,
                                        color       = '#999';
                                    date.setDate(date.getDate() - (daysCount - index));
                                    // highlight the last (current) day
                                    if (index === (daysCount - 1)) {
                                        color = '#555';
                                    }
                                    // highlight Saturdays and Sundays
                                    if (date.getDay() === 0 || date.getDay() === 6) {
                                        color = '#c1c1c1';
                                    }
                                    return color;
                                }
                });

                $('.lp_js_sparklineBackgroundBar', $o.postStatisticsPane).peity('bar', {
                    delimiter   : ';',
                    width       : 182,
                    height      : 42,
                    gap         : 1,
                    fill        : function() { return '#ddd'; }
                });
            },

            togglePostStatisticsVisibility = function() {
                var doHide = $o.postStatisticsPane.hasClass($o.hidden) ? '0' : '1';
                $o.postStatisticsVisibilityInput.val(doHide);

                // toggle the visibility
                $o.postStatisticsPane.toggleClass($o.hidden);

                // save the state
                $.post(
                    lpVars.ajaxUrl,
                    $o.postStatisticsVisibilityForm.serializeArray()
                );
            },

            togglePostPreviewMode = function() {
                if ($o.postPreviewModeToggle.prop('checked')) {
                    $o.postPreviewModeInput.val(1);
                } else {
                    $o.postPreviewModeInput.val(0);
                }

                // save the state and reload the page in the new preview mode
                $.post(
                    lpVars.ajaxUrl,
                    $o.postPreviewModeForm.serializeArray(),
                    function() {
                        window.location.reload();
                    }
                );
            },

            loadPostContent = function() {
                $.get(
                    lpVars.ajaxUrl,
                    {
                        action   : 'laterpay_post_load_purchased_content',
                        post_id  : lpVars.post_id,
                        nonce    : lpVars.nonces.content
                    },
                    function(postContent) {
                        if (postContent) {
                            $o.postContentPlaceholder.html(postContent);
                            // load rating form
                            recacheRatingForm();
                            bindRatingEvents();
                        }
                        loadPremiumUrls();
                    }
                );
            },

            trackViews = function() {
                $.post(
                    lpVars.ajaxUrl,
                    {
                        action  : 'laterpay_post_track_views',
                        post_id : lpVars.post_id,
                        nonce   : lpVars.nonces.tracking
                    }
                );
            },

            handlePurchaseInTestMode = function(trigger) {
                if ($(trigger).data('preview-as-visitor') && !$(trigger).data('is-in-visible-test-mode')) {
                    // show alert instead of loading LaterPay purchase dialogs
                    alert(lpVars.i18n.alert);
                }
            },

            initiateAttachmentDownload = function() {
                var url = get_cookie('laterpay_download_attached');
                // start attachment download, if requested
                if ( url ) {
                    delete_cookie('laterpay_download_attached');
                    window.location.href = url;
                }
            },

            flipTimePass = function(trigger) {
                $(trigger).parents('.lp_time-pass').toggleClass('lp_is-flipped');
            },

            delete_cookie = function( name ) {
                document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
            },

            get_cookie = function(name) {
                var matches = document.cookie.match(
                    new RegExp('(?:^|; )' + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + '=([^;]*)'));
                return matches ? decodeURIComponent(matches[1]) : undefined;
            },

        initializePage = function() {
                // load post content via Ajax, if plugin is in caching compatible mode
                // (recognizable by the presence of lp_js_postContentPlaceholder
                if ($o.postContentPlaceholder.length === 1) {
                    loadPostContent();
                    trackViews();
                }

                // render the post statistics pane, if a placeholder exists for it
                if ($o.postStatisticsPlaceholder.length === 1) {
                    loadPostStatistics();
                }

                if ($o.postRatingPlaceholder.length === 1) {
                    loadRatingSummary();
                }

                if ($o.giftsWrapper.length >= 1) {
                    loadGiftCards();
                }

                if ($($o.premiumBox).length >=1 && !$o.postContentPlaceholder.length) {
                    loadPremiumUrls();
                }

                bindPurchaseEvents();
                bindRatingEvents();
                bindTimePassesEvents();
            };

        initializePage();
    }

// initialize page
laterPayPostView();

});})(jQuery);

// render LaterPay purchase dialogs using the LaterPay YUI dialog manager library
YUI().use('node', 'laterpay-dialog', 'laterpay-iframe', 'laterpay-easyxdm', function(Y) {
    var dm = new Y.LaterPay.DialogManager();

    // bind event to purchase link and if 'preview as visitor' is activated for admins, handle it accordingly
    Y.one(Y.config.doc).delegate(
        'click',
        function(event) {
            event.preventDefault();
            if (
                event.currentTarget.getData('preview-as-visitor') &&
                !event.currentTarget.getData('is-in-visible-test-mode')
            ) {
                alert(lpVars.i18n.alert); // only show an alert instead of opening the dialog
            } else {
                var url = event.currentTarget.getAttribute('href');
                if (event.currentTarget.hasAttribute('data-laterpay')) {
                    url = event.currentTarget.getAttribute('data-laterpay');
                }

                dm.openDialog(url, true); // show the dialog
            }
        },
        '.lp_js_doPurchase'
    );
});


text:
bool sdl2_init_video(emu_state *state)
{
	sdl2_video_data *video;

	info(state, "Initalising the SDL video frontend!");

	if(SDL_InitSubSystem(SDL_INIT_VIDEO) != 0)
	{
		error(state, "Failed to initalise video frontend during video init: %s", SDL_GetError());
		return false;
	}

	video = calloc(1, sizeof(sdl2_video_data));
	state->front.video.data = video;

	video->window = SDL_CreateWindow("SuperGameHerm",
			SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
			WID*2, LEN*2, SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
	if(!(video->window))
	{
		error(state, "Failed to initalise video frontend during window creation: %s", SDL_GetError());
		free(video);
		return false;
	}

	video->render = SDL_CreateRenderer(video->window, -1, 0);
	if(!(video->render))
	{
		error(state, "Failed to initalise video frontend during render creation: %s", SDL_GetError());
		SDL_DestroyWindow(video->window);
		free(video);
		return false;
	}

	SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "2");
	SDL_RenderSetLogicalSize(video->render, WID, LEN);

	video->texture = SDL_CreateTexture(video->render,
			SDL_PIXELFORMAT_ARGB8888,
			SDL_TEXTUREACCESS_STREAMING,
			WID, LEN);
	if(!(video->texture))
	{
		error(state, "Failed to initalise video frontend during texture creation: %s", SDL_GetError());
		SDL_DestroyRenderer(video->render);
		SDL_DestroyWindow(video->window);
		free(video);
		return false;
	}

	SDL_SetRenderDrawColor(video->render, 255, 255, 255, 255);
	SDL_RenderClear(video->render);
	SDL_RenderPresent(video->render);

	return true;
}

void sdl2_finish_video(emu_state *state)
{
	sdl2_video_data *video = state->front.video.data;

	SDL_DestroyTexture(video->texture);
	SDL_DestroyRenderer(video->render);
	SDL_DestroyWindow(video->window);

	free(video);
	state->front.video.data = NULL;

	SDL_QuitSubSystem(SDL_INIT_VIDEO);

	info(state, "SDL video frontend has left the building!");
}

void sdl2_blit_canvas(emu_state *state)
{
	sdl2_video_data *video = state->front.video.data;
	int pitch = PITCH;
	void *data;

	if(unlikely(SDL_LockTexture(video->texture, NULL, &data, &pitch) < 0))
	{
		error(state, "Failed to lock texture: %s", SDL_GetError());
		return;
	}

	memcpy(data, state->lcdc.out, pitch * LEN);

	SDL_UnlockTexture(video->texture);

	SDL_RenderCopy(video->render, video->texture, NULL, NULL);
	SDL_RenderPresent(video->render);
}

const frontend_video sdl2_frontend_video =
{
	&sdl2_init_video,
	&sdl2_finish_video,
	&sdl2_blit_canvas,
	NULL,
};


text:
"""
Auto-generated class for FTPUrl
"""

from . import client_support

class FTPUrl(object):
    """
    auto-generated. don't touch.
    """

    @staticmethod
    def create(url):
        """
        :type url: str
        :rtype: FTPUrl
        """

        return FTPUrl(
            url=url,
        )

    def __init__(self, json=None, **kwargs):
        if json is None and not kwargs:
            raise ValueError('No data or kwargs present')

        class_name = 'FTPUrl'
        create_error = '{cls}: unable to create {prop} from value: {val}: {err}'
        required_error = '{cls}: missing required property {prop}'

        data = json or kwargs

        property_name = 'url'
        val = data.get(property_name)
        if val is not None:
            datatypes = [str]
            try:
                self.url = client_support.val_factory(val, datatypes)
            except ValueError as err:
                raise ValueError(create_error.format(cls=class_name, prop=property_name, val=val, err=err))
        else:
            raise ValueError(required_error.format(cls=class_name, prop=property_name))

    def __str__(self):
        return self.as_json(indent=4)

    def as_json(self, indent=0):
        return client_support.to_json(self, indent=indent)

    def as_dict(self):
        return client_support.to_dict(self)


text:
Because of the highly volatile nature of the project in its current state, we
do not currently accept external contributions.

#How to contribute

If you are part of those that can contribute to this project, you must respect
a set of standard practices when doing so. They exists to simplify that we get
the most out of our tools, and that you can easily browse this respoitory.

##Initial Setup
Please ensure that all the client-side git hooks are installed and up to date
by running this this simple command at the root of your repository:
```bash
# Windows
mklink /H ".git/hooks/pre-commit" "./hooks/pre-commit"

# Linux
ln "./hooks/pre-commit" ".git/hooks/pre-commit"
```

##Basic rules
1. Never commit directly to master. (Enforced by hooks)
2. Ensure that all tests passes before pushing. (TODO: Enforce by hooks)
3. Prefer pull requests when merging to a branch that you do not control.

##Git Commit Messages

We will eventually automate the production of a change log for each of our
releases. This requires us to impose a standard on how git commit messages are
formulated.

### Format of the commit message:
```bash
<type>(<scope>): <subject>

<body>

<footer>
```

### Message subject (first line)
The type and scope should always be lowercase as shown below. There is no
character limit but keep in mind that subjects longer than 80 characters are a
sign of a commit that tries to do too much.

### Allowed `<type>` values:
* **feat** (new feature for the user, not a new feature for build script)
* **fix** (bug fix for the user, not a fix to a build script)
* **docs** (changes to the documentation)
* **style** (formatting, missing semi colons, etc; no production code change)
* **refactor** (refactoring production code, eg. renaming a variable)
* **test** (adding missing tests, refactoring tests; no production code change)
* **chore** (updating grunt tasks etc; no production code change)

### Example `<scope>` values:
* config
* users
* contributions
* communities
* tags
* etc.

The `<scope>` can be empty (eg. if the change is a global or difficult to
assign to a single component), in which case the parentheses are omitted.
Generally, this will match the main API entity related to your changes.

### Message body
The message body is optional for any commit that does not cause a change in
behavior of the production code.

* uses the imperative, present tense: "change" not "changed" nor "changes"
* includes motivation for the change and contrasts with previous behavior

For more info about message body, see:

* http://365git.tumblr.com/post/3308646748/writing-git-commit-messages
* http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html

### Message footer
#### Referencing issues
Closed issues should be listed on a separate line in the footer prefixed with
"Closes" keyword like this:
```bash
Closes #234
```
or in case of multiple issues:
```bash
Closes #123, #245, #992
```

#### Breaking changes
_This section can be ommitted until the first public release._

All breaking changes have to be mentioned in footer with the description of the
change, justification and migration notes.
```bash
BREAKING CHANGE:

`port-runner` command line option has changed to `runner-port`, so that it is
consistent with the configuration file syntax.

To migrate your project, change all the commands, where you use `--port-runner`
to `--runner-port`.
```


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2014 The PeerCoin developers
// Copyright (c) 2011-2014 The NovaCoin developers
// Copyright (c) 2014-2016 The FriendshipCoin2 developers
// Copyright (c) 2016 The ArtBoomerangCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef SIGNVERIFYMESSAGEDIALOG_H
#define SIGNVERIFYMESSAGEDIALOG_H

#include <QDialog>
#include <QWindow>
#include "guiutil.h"
#ifdef USE_FULLSCREEN
#include "actionbar/actionbar.h"
#endif

namespace Ui {
    class SignVerifyMessageDialog;
}
class WalletModel;

QT_BEGIN_NAMESPACE
QT_END_NAMESPACE

class SignVerifyMessageDialog : public QDialog

{
    Q_OBJECT

public:
    explicit SignVerifyMessageDialog(QWidget *parent = 0, BitScreen *screen=0);
    ~SignVerifyMessageDialog();

    void setModel(WalletModel *model);
    void setAddress_SM(QString address);
    void setAddress_VM(QString address);

    void showTab_SM(bool fShow);
    void showTab_VM(bool fShow);

protected:
    bool eventFilter(QObject *object, QEvent *event);
    void keyPressEvent(QKeyEvent *event);
    void showEvent(QShowEvent *event);

private:
    Ui::SignVerifyMessageDialog *ui;
    WalletModel *model;
    BitScreen *screen;
#ifdef USE_FULLSCREEN
    ActionBar *actionBar;
#endif

private slots:
    void screenOrientationChanged();
    void clearAll();
    /* sign message */
    void on_addressBookButton_SM_clicked();
    void on_pasteButton_SM_clicked();
    void on_pasteButton_VM_clicked();
    void on_signMessageButton_SM_clicked();
    void on_copySignatureButton_SM_clicked();
    /* verify message */
    void on_addressBookButton_VM_clicked();
    void on_verifyMessageButton_VM_clicked();
    void on_pasteButtonVM2_clicked();
    void on_btnClearVM_clicked();
    void on_btnClearSM_clicked();
    void on_btnCloseVM_clicked();
    void on_btnCloseSM_clicked();
};

#endif // SIGNVERIFYMESSAGEDIALOG_H


text: `new` dpl/amui First version.


text:
package mllib.perf.clustering

import java.util.Random

import breeze.linalg.{DenseMatrix => BDM, DenseVector => BDV}
import org.json4s.JValue
import org.json4s.JsonDSL._

import org.apache.spark.SparkContext
import org.apache.spark.mllib.clustering.GaussianMixture
import org.apache.spark.mllib.linalg.{Vector, Vectors}
import org.apache.spark.rdd.RDD

import mllib.perf.PerfTest

class GaussianMixtureTest(sc: SparkContext) extends PerfTest {

  val NUM_EXAMPLES = ("num-examples", "number of examples for clustering tests")
  val NUM_FEATURES = ("num-features", "number of features for each example for clustering tests")
  val NUM_CENTERS = ("num-centers", "number of centers for clustering tests")
  val NUM_ITERATIONS = ("num-iterations", "number of iterations for the algorithm")

  intOptions ++= Seq(NUM_CENTERS, NUM_FEATURES, NUM_ITERATIONS)
  longOptions ++= Seq(NUM_EXAMPLES)
  val options = intOptions ++ stringOptions  ++ booleanOptions ++ longOptions ++ doubleOptions
  addOptionsToParser()

  var data: RDD[Vector] = _

  override def createInputData(seed: Long): Unit = {
    val m = longOptionValue(NUM_EXAMPLES)
    val n = intOptionValue(NUM_FEATURES)
    val k = intOptionValue(NUM_CENTERS)
    val p = intOptionValue(NUM_PARTITIONS)

    val random = new Random(seed ^ 8793480384L)
    val mu = Array.fill(k)(new BDV[Double](Array.fill(n)(random.nextGaussian())))
    val f = Array.fill(k)(new BDM[Double](n, n, Array.fill(n * n)(random.nextGaussian())))
    data = sc.parallelize(0L until m, p)
      .mapPartitionsWithIndex { (idx, part) =>
        val rng = new Random(seed & idx)
        part.map { _ =>
          val i = (rng.nextDouble() * k).toInt
          val x = new BDV[Double](Array.fill(n)(rng.nextGaussian()))
          val y = f(i) * x + mu(i)
          Vectors.dense(y.data)
        }
      }.cache()
    logInfo(s"Generated ${data.count()} examples.")
  }

  override def run(): JValue = {
    val numIterations = intOptionValue(NUM_ITERATIONS)
    val k = intOptionValue(NUM_CENTERS)
    val start = System.currentTimeMillis()
    val gmm = new GaussianMixture()
      .setK(k)
      .setMaxIterations(numIterations)
    val model = gmm.run(data)
    val duration = (System.currentTimeMillis() - start) / 1e3
    "time" -> duration
  }
}


text:
require 'jira_rest_api'
require 'rails'

module JiraRestApi
  class Railtie < Rails::Railtie
    rake_tasks do
      load 'tasks/generate.rake'
    end
  end
end


text:
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_GEOMETRIES_ADAPTED_STD_PAIR_AS_SEGMENT_HPP
#define BOOST_GEOMETRY_GEOMETRIES_ADAPTED_STD_PAIR_AS_SEGMENT_HPP

// Only possible if the std::pair is not used for iterator/pair
// (maybe it is possible to avoid that by detecting in the other file
//  if an iterator was used in the pair)

#ifdef BOOST_GEOMETRY_ADAPTED_STD_RANGE_TAG_DEFINED
#error Include only one headerfile to register tag for adapted std:: containers or iterator pair
#endif

#define BOOST_GEOMETRY_ADAPTED_STD_RANGE_TAG_DEFINED

#include <cstddef>

#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS
namespace traits
{

template <typename Point>
struct tag<std::pair<Point, Point> >
{
    typedef segment_tag type;
};

template <typename Point>
struct point_type<std::pair<Point, Point> >
{
    typedef Point type;
};

template <typename Point, std::size_t Dimension>
struct indexed_access<std::pair<Point, Point>, 0, Dimension>
{
    typedef typename geometry::coordinate_type<Point>::type coordinate_type;

    static inline coordinate_type get(std::pair<Point, Point> const& s)
    {
        return geometry::get<Dimension>(s.first);
    }

    static inline void set(std::pair<Point, Point>& s, coordinate_type const& value)
    {
        geometry::set<Dimension>(s.first, value);
    }
};

template <typename Point, std::size_t Dimension>
struct indexed_access<std::pair<Point, Point>, 1, Dimension>
{
    typedef typename geometry::coordinate_type<Point>::type coordinate_type;

    static inline coordinate_type get(std::pair<Point, Point> const& s)
    {
        return geometry::get<Dimension>(s.second);
    }

    static inline void set(std::pair<Point, Point>& s, coordinate_type const& value)
    {
        geometry::set<Dimension>(s.second, value);
    }
};

} // namespace traits
#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_GEOMETRIES_ADAPTED_STD_PAIR_AS_SEGMENT_HPP


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.DataProtection.StackExchangeRedis;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;

namespace Microsoft.AspNetCore.DataProtection;

/// <summary>
/// Contains Redis-specific extension methods for modifying a <see cref="IDataProtectionBuilder"/>.
/// </summary>
public static class StackExchangeRedisDataProtectionBuilderExtensions
{
    private const string DataProtectionKeysName = "DataProtection-Keys";

    /// <summary>
    /// Configures the data protection system to persist keys to specified key in Redis database
    /// </summary>
    /// <param name="builder">The builder instance to modify.</param>
    /// <param name="databaseFactory">The delegate used to create <see cref="IDatabase"/> instances.</param>
    /// <param name="key">The <see cref="RedisKey"/> used to store key list.</param>
    /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns>
    public static IDataProtectionBuilder PersistKeysToStackExchangeRedis(this IDataProtectionBuilder builder, Func<IDatabase> databaseFactory, RedisKey key)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }
        if (databaseFactory == null)
        {
            throw new ArgumentNullException(nameof(databaseFactory));
        }
        return PersistKeysToStackExchangeRedisInternal(builder, databaseFactory, key);
    }

    /// <summary>
    /// Configures the data protection system to persist keys to the default key ('DataProtection-Keys') in Redis database
    /// </summary>
    /// <param name="builder">The builder instance to modify.</param>
    /// <param name="connectionMultiplexer">The <see cref="IConnectionMultiplexer"/> for database access.</param>
    /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns>
    public static IDataProtectionBuilder PersistKeysToStackExchangeRedis(this IDataProtectionBuilder builder, IConnectionMultiplexer connectionMultiplexer)
    {
        return PersistKeysToStackExchangeRedis(builder, connectionMultiplexer, DataProtectionKeysName);
    }

    /// <summary>
    /// Configures the data protection system to persist keys to the specified key in Redis database
    /// </summary>
    /// <param name="builder">The builder instance to modify.</param>
    /// <param name="connectionMultiplexer">The <see cref="IConnectionMultiplexer"/> for database access.</param>
    /// <param name="key">The <see cref="RedisKey"/> used to store key list.</param>
    /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns>
    public static IDataProtectionBuilder PersistKeysToStackExchangeRedis(this IDataProtectionBuilder builder, IConnectionMultiplexer connectionMultiplexer, RedisKey key)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }
        if (connectionMultiplexer == null)
        {
            throw new ArgumentNullException(nameof(connectionMultiplexer));
        }
        return PersistKeysToStackExchangeRedisInternal(builder, () => connectionMultiplexer.GetDatabase(), key);
    }

    private static IDataProtectionBuilder PersistKeysToStackExchangeRedisInternal(IDataProtectionBuilder builder, Func<IDatabase> databaseFactory, RedisKey key)
    {
        builder.Services.Configure<KeyManagementOptions>(options =>
        {
            options.XmlRepository = new RedisXmlRepository(databaseFactory, key);
        });
        return builder;
    }
}


text:
package si.ijs.acs.objectexplorer;

import javax.swing.*;
import javax.swing.tree.*;
/**
 * Insert the type's description here.
 * Creation date: (9/26/98 1:24:30 PM)
 * @author: Miha Kadunc
 */
public class OETree extends JTree {
	// ----- integer constants, prepresenting hierarchy types -----
	public static final int HIERARCHY_BY_TYPE = 1;
	public static final int	HIERARCHY_BY_NAME = 2;
	// ----- * by rbertoncelj

	protected transient java.util.Vector aOETreeEventListener = null;
	private NotificationBean notifier=null;
/**
 * ComponentTree constructor comment.
 */
public OETree() {
	super();
	setShowsRootHandles(true);
	setRootVisible(false);
	setCellRenderer(new OETreeCellRenderer());
	setModel(new DefaultTreeModel(new OETreeNode(-1,"Objects","root",this)));
	getSelectionModel().setSelectionMode(DefaultTreeSelectionModel.SINGLE_TREE_SELECTION);

}
/**
 * Add a si.ijs.anka.utilities.serviceLocator.ServiceLocatorEventListener.
 */
public void addOETreeEventListener(OETreeEventListener newListener) {
	if (aOETreeEventListener == null) {
		aOETreeEventListener = new java.util.Vector();
	};
	aOETreeEventListener.addElement(newListener);
}
/**
 * Insert the method's description here.
 * Creation date: (9/27/98 6:38:56 PM)
 */
public void clearTree() {
  OETreeNode rootnode=new OETreeNode(0,"Objects","root",this);
  setModel(new DefaultTreeModel(rootnode));
  setSelectionRow(0);
}
/**
 * Method to support listener events.
 */
protected void fireFirstTimeExpanded(FirstTimeExpandedEvent event) {
	if (aOETreeEventListener == null) {
		return;
	};
	int currentSize = aOETreeEventListener.size();
	OETreeEventListener tempListener = null;
	for (int index = 0; index < currentSize; index++){
		tempListener = (OETreeEventListener)aOETreeEventListener.elementAt(index);
		if (tempListener != null) {
			tempListener.firstTimeExpanded(event);
		};
	};
}
/**
 * Insert the method's description here.
 * Creation date: (11/10/00 3:55:37 PM)
 * @return si.ijs.acs.objectexplorer.NotificationBean
 */
public NotificationBean getNotifier() {
	return notifier;
}
/**
 * Remove a si.ijs.anka.utilities.serviceLocator.ServiceLocatorEventListener.
 */
public void removeOETreeEventListener(OETreeEventListener newListener) {
	if (aOETreeEventListener != null) {
		aOETreeEventListener.removeElement(newListener);
	};
}
/**
 * Insert the method's description here.
 * Creation date: (11/10/00 3:55:37 PM)
 * @param newNotifier si.ijs.acs.objectexplorer.NotificationBean
 */
public void setNotifier(NotificationBean newNotifier) {
	notifier = newNotifier;
}
}


text:
//
//  WMUIMacros.h
//  Blast
//
//  Created by leon on 8/17/16.
//  Copyright © 2016 codoon. All rights reserved.
//

#ifndef WMUIMacros_h
#define WMUIMacros_h

#define isIPhone4s  ([UIScreen mainScreen].bounds.size.height < 568.0f)

#define kDefaultCropPhotoWidth  1080.0f

#endif /* WMUIMacros_h */


text:
require 'spec_helper'

describe RedisObj::SortedSet do
  let(:redis_method) {:"some_redis_method!"}
  let(:redis) { double(Redis, redis_method => true) }
  let(:key) { "key#{rand}" }
  let(:val) { rand }
  subject {RedisObj::SortedSet.new(redis,key)}

  it_should_behave_like "a method missing object", 'z'
end


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

<title>Diff.ScriptBuilder</title>
<meta name="date" content="2014-08-13">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

gov.va.med.lom.javaUtils.misc

Interface Diff.ScriptBuilder

Enclosing class:

Diff

public static interface Diff.ScriptBuilder

Method Summary

Methods

Modifier and Type
Method and Description

Diff.change
buildScript(boolean[] changed0,
           int len0,
           boolean[] changed1,
           int len1)

Method Detail

buildScript

Diff.change buildScript(boolean[] changed0,
                      int len0,
                      boolean[] changed1,
                      int len1)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method