text:
require 'rack'

class AutoDiscoveryServer
  attr_reader :app

  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, body = @app.call(env)

    if body.empty?
      request = Rack::Request.new(env)

      xmlrpc_url = route_for(request, "/xmlrpc.php")

      if request.path_info == "/"
        res = %Q(

            <link rel="EditURI" type="application/rsd+xml" title="RSD" href="#{ xmlrpc_url }?rsd" />

Welcome to Inkplate!

        )
        [ 200, { "Content-Type" => "text/html" }, [ res ] ]
      elsif request.path_info == "/xmlrpc.php" && request.params.has_key?("rsd")
        res = [
          %(<?xml version="1.0" encoding="UTF-8"?>),
          %(<rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">),
            %(<service>),
              %(<engineName>WordPress</engineName>),
              %(<engineLink>https://wordpress.org/</engineLink>),
              %Q(<homePageLink>#{ request.base_url }</homePageLink>),
              %(<apis>),
                %Q(<api name="WordPress" blogID="1" preferred="true" apiLink="#{ xmlrpc_url }" />),
                %Q(<api name="Movable Type" blogID="1" preferred="false" apiLink="#{ xmlrpc_url }" />),
                %Q(<api name="MetaWeblog" blogID="1" preferred="false" apiLink="#{ xmlrpc_url }" />),
                %Q(<api name="Blogger" blogID="1" preferred="false" apiLink="#{ xmlrpc_url }" />),
                %Q(<api name="WP-API" blogID="1" preferred="false" apiLink="#{ route_for(request, "/wp-json/") }" />),
              %(</apis>),
            %(</service>),
          %(</rsd>)
        ]
        [ 200, { "Content-Type" => "text/xml; charset=UTF-8" }, res ]
      else
        [status, headers, body]
      end
    else
      [status, headers, body]
    end
  end

  protected

  def route_for(request, path)
    route = URI(request.base_url)
    route.path = path
    route.to_s
  end

end


text:
from biicode.common.model.symbolic.reference import References
from biicode.common.deps.block_version_graph_builder import block_version_graph_build
from biicode.server.deps.compatibility_closure_builder import build_compatibility_closure
from biicode.server.deps.compatibility_closure import CompatibilityClosure
from biicode.common.model.symbolic.block_version_table import BlockVersionTable

class Hypothesis(object):
    def __init__(self, block_version, dep_dict, ref_translator, base_block_names, biiresponse):
        self.block_version = block_version
        self.dep_dict = dep_dict
        self._ref_translator = ref_translator
        self._base_block_names = base_block_names
        self._closure = None
        self._block_closure = None
        self._invalid = None
        self.biiresponse = biiresponse

    @property
    def closure(self):  # Lazy computation of closures
        if self._closure is None:
            missing = References()
            for targets in self.dep_dict.values():
                for target in targets:
                    missing[self.block_version].add(target.cell_name)
            self._closure = CompatibilityClosure(missing)
        return self._closure

    @property
    def invalid(self):
        if self._invalid is None:
            dep_block_names = self.block_closure.versions.keys()
            cycles = self._base_block_names.intersection(dep_block_names)
            if cycles:
                self.biiresponse.error('Version %s discarded, it has cycles to %s'
                                       % (self.block_version, cycles))
                self._invalid = True
            else:
                self._invalid = False
        return self._invalid

    @property
    def block_closure(self):  # Lazy computation of closures
        if self._block_closure is None:
            self._block_closure, _ = block_version_graph_build(self._ref_translator.get_dep_table,
                                                        [self.block_version],
                                                        BlockVersionTable())
        return self._block_closure

    def is_compatible(self, other):
        '''check if compatible with other Hypothesis object'''
        if self.invalid or other.invalid:
            return False
        graph_collision = self.block_closure.collision(other.block_closure)
        if not graph_collision:
            return True

        c1 = self.closure
        c2 = other.closure

        build_compatibility_closure(self._ref_translator, c1, graph_collision.nodes, self.block_closure)
        build_compatibility_closure(self._ref_translator, c2, graph_collision.nodes, other.block_closure)
        return c1.conflicts(c2) == 0

    def __repr__(self):
        return repr(self.block_version)

redpajama_set_name: RedPajamaGithub


text:
![](https://travis-ci.org/AVGP/gltf-viewer.svg?branch=master)
![BrowserStack Status](https://www.browserstack.com/automate/badge.svg?badge_key=UzNReXpkU1F0L0ZiT1Q4Zk1DNDd3WThjazVDZXRZbTRVdm5VN3BUYTdjcz0tLVVEUTZrYWhjdlR3d3U1V05ab3hqMkE9PQ==--c9e78044bc4836e4162cb00b0d45e04578e02938)

Displays a 3D representation of a glTF model, interactive or static.

Tested with [BrowserStack <img src="https://dgzoq9b5asjg1.cloudfront.net/production/images/static/header/header-logo.svg" height="30">](https://browserstack.com)

## Live demo

<!--
```
<custom-element-demo height="300">
  <template>
    <link rel="import" href="gltf-viewer.html">
    <gltf-viewer src="demo/duck.gltf" interactive></gltf-viewer>
  </template>
</custom-element-demo>
```
-->
```html
  <gltf-viewer src="demo/duck.gltf" interactive></gltf-viewer>
```

[See the component in action](https://avgp.github.io/gltf-viewer).

## Usage

Here is a simple sample to get you started:

*Important note:* The example is great to try it out, but you should install the component if you build an application with `<gltf-viewer>` so you don't rely on external sources too much!

```html
<!doctype html>
<html>
<head>
  <!--  polyfill for older browsers -->
  <script src="https://cdnjs.com/webcomponentsjs/webcomponents-lite.js"></script>

  <link rel="import" href="https://avgp.github.io/gltf-viewer/gltf-viewer.html">
</head>
<body>
  <gltf-viewer interactive src="/model.gltf"></gltf-viewer>
</body>
</html>
```

## Installation

The component can be installed via [Bower](https://bower.io):

```bash
bower install gltf-viewer
```

## Browser support & glTF support

The component supports:

* Safari (OSX & iOS)
* Opera
* Firefox
* Edge
* Chrome & Android browser from 4.x upwards

The component supports both glTF 1.0 and glTF 2.0 models.

## Contributing

If you think the component is missing something or you found a bug, please submit an issue and/or a pull request!

### Setup for contributing

The easiest way to get going is to install the `polymer-cli`:

```bash
npm install -g polymer-cli
```

Then you can clone this repository to your local computer:

```bash
git clone https://github.com/avgp/gltf-viewer.git
cd gltf-viewer
```
You are now inside your cloned repository.

## Serving the local component

If you have `polymer-cli` installed, go into your clone of this repository and run `polymer serve` in a terminal.
You can access the demos via the URL that will be displayed and use the component locally.

### Running Tests
```
$ polymer test
```

The component uses [web-component-tester](https://github.com/Polymer/web-component-tester). Run `polymer test` to run your application's test suite locally.


text:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="150dp"
    android:minHeight="150dp"
    android:updatePeriodMillis="2000"
    android:initialLayout="@layout/test_appwidget"
    >
</appwidget-provider>


text:
/**
 * ConsoleMessage objects are dispatched by page via the 'console' event.
 * @public
 */
export class ConsoleMessage {
    /**
     * @public
     */
    constructor(type, text, args, stackTraceLocations) {
        this._type = type;
        this._text = text;
        this._args = args;
        this._stackTraceLocations = stackTraceLocations;
    }
    /**
     * @returns The type of the console message.
     */
    type() {
        return this._type;
    }
    /**
     * @returns The text of the console message.
     */
    text() {
        return this._text;
    }
    /**
     * @returns An array of arguments passed to the console.
     */
    args() {
        return this._args;
    }
    /**
     * @returns The location of the console message.
     */
    location() {
        return this._stackTraceLocations.length ? this._stackTraceLocations[0] : {};
    }
    /**
     * @returns The array of locations on the stack of the console message.
     */
    stackTrace() {
        return this._stackTraceLocations;
    }
}
//# sourceMappingURL=ConsoleMessage.js.map


text:
<?php

namespace Front\FrontBundle\Repository;
use Doctrine\ORM\EntityRepository;

class TeacherObjectsRepository extends EntityRepository {

    /**
     * teacher objects
     * @param type $teacher_id
     * @return type
     */
    public function teacherObjects($teacher_id) {
        $query = "
            SELECT *, `to`.id AS teacher_object_id
            FROM teacher_objects `to`, system_objects so
            WHERE `to`.object_id=so.id
            AND `to`.teacher_id=:teacher_id
        ";
        $q = $this->getEntityManager()->getConnection()->executeQuery($query, array(':teacher_id' => $teacher_id));
        $result = $q->fetchAll(2);

        return $result;
    }

    public function deleteTeacherObject($teacher_id, $object_id) {
        $query = "
            DELETE
            FROM teacher_objects
            WHERE teacher_id=:teacher_id
            AND object_id=:object_id
        ";
        $q = $this->getEntityManager()->getConnection()->executeQuery($query, array(':teacher_id' => $teacher_id, ':object_id' => $object_id));
    }

    public function teacherObjectsCnt($teacher_id) {
        $query = "
            SELECT COUNT(`to`.id) AS cnt
            FROM teacher_objects `to`
            WHERE `to`.teacher_id=:teacher_id
        ";
        $q = $this->getEntityManager()->getConnection()->executeQuery($query, array(':teacher_id' => $teacher_id));
        $result = $q->fetch(2);

        return $result['cnt'];
    }

    /**
     * adds teacher objects
     * @param type $teacher_id
     * @param type $objects
     */
    public function addObjects($teacher_id, $objects, $object_experience) {
        $cnt = count($objects);
        for ($i = 0; $i < $cnt; $i++) {
            $query = "
                INSERT INTO teacher_objects(teacher_id, object_id, experience_years, added)
                VALUES(:teacher_id, '".$objects[$i]."', '".$object_experience[$i]."', NOW())
            ";
            $q = $this->getEntityManager()->getConnection()->executeQuery($query, array(':teacher_id' => $teacher_id));
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#FD5859</color>
    <color name="colorPrimaryDark">#FD5859</color>
    <color name="colorAccent">#FD5859</color>
    <color name="colorItemDark">#FD5859</color>
    <color name="colorItemLight">#FD5870</color>
</resources>


text:
<!DOCTYPE html>

    <title>Cómo Ayudar MX | Help Needed.</title>
    <meta name="description" content="Information Repository to assist those affected by the earthquake in Mexico." />

    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@comoayudarmx">
    <meta name="twitter:title" content="Help those affected by the earthquake in Mexico.">
    <meta name="twitter:description" content="Find different organizations, collection centers or other helping methods to assist those affected by the earthquake in Mexico or earthquake rescuers.">
    <meta name="twitter:image" content="http://javierivero.com/twitter.png">

    <meta property="og:title" content="Help those affected by the earthquake in Mexico." />
    <meta property="og:type" content="web" />
    <meta property="og:url" content="http://comoayudar.mx/" />
    <meta property="og:image" content="facebook.jpg" />
    <meta property="og:description" content="Help those affected by the earthquake in Mexico. Help needed." />

    <link rel="stylesheet" type="text/css" href="style.min.css">
    <link rel="stylesheet" type="text/css" href="lib/chosen/chosen.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://fonts.googleapis.com/css?family=Roboto+Slab:400,700|Roboto:400,500" rel="stylesheet">

    <link rel="icon" href="favicon.png" type="image/x-icon" />

¿Como Ayudar?

          Home
          About
          Español
          Contribute

Help Needed for Mexico Earthquake
Sep 19, 2017

CDMX, Puebla

          How Can You Help?
          Publish

Emergency Contacts

Here is a contact list that can help you if you are in an area affected by the earthquake.

If you know any other important contact information Contact us.

          <template id="card_template">

Donation Type:

Location:

            More Information

          </template>

      Close

About Como Ayudar

This volunteer project is an effort to centralize all information regarding assistance and distribution to help those affected by the earthquake in Mexico on September 19, 2017.

If you are a developer and want to help, please check our repo on Github

 If you wish to add a Helping Source, please contact us here:

        @comoayudarmx or comoayudarmx@gmail.com

      Close

Publish a Helping Source

Send us the information about a Helping Source with all the applicable information: Who are you helping, location, type of help. You can send us the information using the following methods:

        @comoayudarmx or comoayudarmx@gmail.com


text:
var MySale = artifacts.require("./MySale.sol");
var MyCrowdsaleToken = artifacts.require("./MyCrowdsaleToken.sol");

var waitForTime = require("./helpers/waitForTime");

contract('MySale', function(accounts) {
  var initialEndTime
  it("should not activate hardCap", async function() {
    var instance = await MySale.deployed();
    initialEndTime = await instance.endTime();

    await instance.setHardCap(web3.toWei(6.0, 'ether'), '591563213198454323051378072341')
    await instance.setHardCap(web3.toWei(2.1, 'ether'), '591563213198454323051378072340')
    await instance.setHardCap(web3.toWei(2.1, 'ether'), '691563213198454323051378072341')
    var hardCap = await instance.hardCap()

    assert.equal(hardCap.valueOf(), 0, "hard cap was set")
  });

  it("will wait 40 blocks for presale end (please wait)", async function() {
    var instance = await MySale.deployed();
    var startTime = await instance.startTime();
    var targetTime = web3.eth.getBlock(web3.eth.blockNumber).timestamp+1230;
    console.log("    ...advancing blocks, please wait...")
    await waitForTime(targetTime);
    assert.equal((targetTime/10).toFixed(), (web3.eth.getBlock('latest').timestamp/10).toFixed(), "Times not elapsed");
  });

  it("should activate hardCap and not activate", async function() {
    var instance = await MySale.deployed();
    instance.setHardCap(web3.toWei(2.1, 'ether'), '591563213198454323051378072341')
    var endTime = await instance.endTime()
    assert.equal(endTime.valueOf(), initialEndTime.valueOf(), "final block was set")
  });

  it("should allow token pregeneration", async function() {
    var instance = await MySale.deployed();
    var address = await instance.pregenTokens(accounts[6], web3.toWei(0.002, 'ether'), web3.toWei(1000, 'ether'));

    var tokenAddress = await instance.token();
    var tokInstance = MyCrowdsaleToken.at(tokenAddress);

    var balance = await tokInstance.balanceOf(accounts[6]);

    assert.equal(balance.valueOf(), 1e+21, "token pregeneration failed");
  });

  it("should not allow token pregeneration if not owner", async function() {
    var instance = await MySale.deployed();
    var tokenAddress = await instance.token();
    var tokInstance = MyCrowdsaleToken.at(tokenAddress);

    instance.pregenTokens(accounts[6], web3.toWei(0.002, 'ether'), web3.toWei(1000, 'ether'), {from: accounts[1]}).then(function() {}, function() {});

    var balance = await tokInstance.balanceOf(accounts[6]);

    assert.equal(balance.valueOf(), 1e+21, "token pregeneration failed");
  });

  it("should put 2000 MySale in the first account", async function() {
    var account1 = accounts[1]
    var instance = await MySale.deployed();

    instance.sendTransaction({ from: account1, value: web3.toWei(2, "ether")})

    var tokenAddress = await instance.token()
    var tokInstance = MyCrowdsaleToken.at(tokenAddress)
    var balance = await tokInstance.balanceOf(account1)

    assert.equal(balance.valueOf(), 2e+21, "2000 wasn't in the first account");
  });

  it("should not allow token transfers", async function() {
    var account1 = accounts[1]
    var account2 = accounts[2]
    var instance = await MySale.deployed();
    var tokenAddress = await instance.token()
    var tokInstance = MyCrowdsaleToken.at(tokenAddress)

    tokInstance.transfer(account2, 2e+21, {from: account1}).then(function(){}, function(){});

    var balance = await tokInstance.balanceOf(account2)

    assert.equal(balance.valueOf(), 0, "0 wasn't in the second account");
  });

  it("should assign 1600 to the third account (soft cap test)", async function() {
    var account1 = accounts[3]
    var instance = await MySale.deployed();
    var tokenAddress = await instance.token()
    var tokInstance = MyCrowdsaleToken.at(tokenAddress)

    instance.sendTransaction({ from: account1, value: web3.toWei(2, "ether")})

    var balance = await tokInstance.balanceOf(account1)

    assert.equal(balance.valueOf(), 1.6e+21, "1600 wasn't in the third account");
  });

  it("should have activated hardCap", async function() {
    var instance = await MySale.deployed();
    var endTime = await instance.endTime()

    assert.notEqual(endTime.toNumber(10), initialEndTime.valueOf(), "hard cap was not activated")
  });

  it("should assign 1200 to the fourth account (hard cap test)", async function() {
    var account1 = accounts[4]
    var instance = await MySale.deployed();
    var tokenAddress = await instance.token()
    var tokInstance = MyCrowdsaleToken.at(tokenAddress)

    instance.sendTransaction({ from: account1, value: web3.toWei(2, "ether")})

    var balance = await tokInstance.balanceOf(account1)

    assert.equal(balance.valueOf(), 1.2e+21, "1200 wasn't in the fourth account");
  });

  it("will wait 70 blocks (please wait)", async function() {
    var instance = await MySale.deployed();
    var targetTime = web3.eth.getBlock('latest').timestamp+1420;
    console.log("    ...advancing blocks, please wait...")

    await waitForTime(targetTime);

    assert.equal(targetTime+1, web3.eth.getBlock('latest').timestamp, "Times not elapsed");
  });

  it("should be finished", async function() {
    var instance = await MySale.deployed();
    var hasEnded = await instance.hasEnded()

    assert.equal(hasEnded, true, 'not finished');
  });

  it("should not allow further deposits", async function() {
    var account1 = accounts[3]
    var instance = await MySale.deployed();
    var tokenAddress = await instance.token()
    var tokInstance = MyCrowdsaleToken.at(tokenAddress)

    instance.sendTransaction({ from: account1, value: web3.toWei(2, "ether")}).then(
        function(){}, function(){});
    var balance = await tokInstance.balanceOf(account1)
    assert.equal(balance.valueOf(), 1.6e+21, "1600 wasn't in the third account");
  });

  it("should allow finalizing", async function() {
    var targetAccount = accounts[5];
    var instance = await MySale.deployed();
    var tokenAddress = await instance.token()
    var tokInstance = MyCrowdsaleToken.at(tokenAddress)

    var balance = await tokInstance.balanceOf(targetAccount)
    assert.equal(balance.toNumber(10), 0.0, 'destination doesnt have 0 tokens');

    instance.finalize()
    balance = await tokInstance.balanceOf(targetAccount)

    assert.equal(balance.valueOf(), 2.4824e+21, 'destination doesnt have 2482.4 tokens');
    var totalSupply = await tokInstance.totalSupply()
    assert.equal(totalSupply.toNumber(10), 8.2824e+21, 'total supply is not 8282.4 tokens');
  });

  it("should not finalize again", async function() {
    var targetAccount = accounts[5];
    var instance = await MySale.deployed();
    var tokenAddress = await instance.token()
    var tokInstance = MyCrowdsaleToken.at(tokenAddress)

    instance.finalize().then(function(){}, function(){});
    var balance = await tokInstance.balanceOf(targetAccount)

    assert.equal(balance.valueOf(), 2.4824e+21, 'destination doesnt have 2482.4 tokens');
  });

  it("should allow token transfers", async function() {
    var account1 = accounts[1]
    var account2 = accounts[2]
    var instance = await MySale.deployed();
    var tokenAddress = await instance.token()
    var tokInstance = MyCrowdsaleToken.at(tokenAddress)

    tokInstance.transfer(account2, web3.toWei(1, "ether"), {from: account1});
    var balance = await tokInstance.balanceOf(account2)

    assert.equal(balance.valueOf(), 1e+18, "1000 wasn't in the second account");
  });

  it("should not allow token transfers beyond balance", async function() {
    var account1 = accounts[1]
    var account2 = accounts[2]
    var instance = await MySale.deployed();
    var tokenAddress = await instance.token()
    var tokInstance = MyCrowdsaleToken.at(tokenAddress)

    tokInstance.transfer(account2, web3.toWei(50000, "ether"), {from: account1}).then(
        function(){}, function(){});
    var balance = await tokInstance.balanceOf(account2)

    assert.equal(balance.valueOf(), 1e+18, "1000 wasn't in the second account");
  });

});


text:
namespace IECorePython
{
IECOREPYTHON_API void bindObjectVector();
}

#endif // IECOREPYTHON_OBJECTVECTOR_H


text: Efficient Combinatorics package for Go


text:
package cml.language.foundation;

import cml.language.generated.ModelElement;
import cml.language.generated.Scope;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public abstract class ScopeBase extends ModelElementBase implements Scope
{
    protected final Scope scope;

    public ScopeBase(@Nullable Scope parent, List<ModelElement> members)
    {
        super(parent);

        this.scope = Scope.extendScope(this, element, modelElement, members);
    }

    @Override
    public List<ModelElement> getMembers()
    {
        return scope.getMembers();
    }
}


text:
package org.apache.flink.annotation.docs;

import org.apache.flink.annotation.Internal;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** Collection of annotations to modify the behavior of the documentation generators. */
public final class Documentation {

    /** Annotation used on config option fields to override the documented default. */
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Internal
    public @interface OverrideDefault {
        String value();
    }

    /**
     * Annotation used on config option fields to include them in specific sections. Sections are
     * groups of options that are aggregated across option classes, with each group being placed
     * into a dedicated file.
     *
     *
The {@link Section#position()} argument controls the position in the generated table, with
     * lower values being placed at the top. Fields with the same position are sorted alphabetically
     * by key.
     */
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Internal
    public @interface Section {

        /** The sections in the config docs where this option should be included. */
        String[] value() default {};

        /** The relative position of the option in its section. */
        int position() default Integer.MAX_VALUE;
    }

    /** Constants for section names. */
    public static final class Sections {

        public static final String COMMON_HOST_PORT = "common_host_port";
        public static final String COMMON_STATE_BACKENDS = "common_state_backends";
        public static final String COMMON_HIGH_AVAILABILITY = "common_high_availability";
        public static final String COMMON_HIGH_AVAILABILITY_ZOOKEEPER =
                "common_high_availability_zk";
        public static final String COMMON_HIGH_AVAILABILITY_JOB_RESULT_STORE =
                "common_high_availability_jrs";
        public static final String COMMON_MEMORY = "common_memory";
        public static final String COMMON_MISCELLANEOUS = "common_miscellaneous";

        public static final String SECURITY_SSL = "security_ssl";
        public static final String SECURITY_AUTH_KERBEROS = "security_auth_kerberos";
        public static final String SECURITY_AUTH_ZOOKEEPER = "security_auth_zk";

        public static final String STATE_BACKEND_ROCKSDB = "state_backend_rocksdb";

        public static final String STATE_BACKEND_LATENCY_TRACKING =
                "state_backend_latency_tracking";

        public static final String STATE_BACKEND_CHANGELOG = "state_backend_changelog";

        public static final String EXPERT_CLASS_LOADING = "expert_class_loading";
        public static final String EXPERT_DEBUGGING_AND_TUNING = "expert_debugging_and_tuning";
        public static final String EXPERT_SCHEDULING = "expert_scheduling";
        public static final String EXPERT_FAULT_TOLERANCE = "expert_fault_tolerance";
        public static final String EXPERT_STATE_BACKENDS = "expert_state_backends";
        public static final String EXPERT_REST = "expert_rest";
        public static final String EXPERT_HIGH_AVAILABILITY = "expert_high_availability";
        public static final String EXPERT_ZOOKEEPER_HIGH_AVAILABILITY =
                "expert_high_availability_zk";
        public static final String EXPERT_KUBERNETES_HIGH_AVAILABILITY =
                "expert_high_availability_k8s";
        public static final String EXPERT_SECURITY_SSL = "expert_security_ssl";
        public static final String EXPERT_ROCKSDB = "expert_rocksdb";
        public static final String EXPERT_CLUSTER = "expert_cluster";
        public static final String EXPERT_JOB_MANAGER = "expert_jobmanager";

        public static final String ALL_JOB_MANAGER = "all_jobmanager";
        public static final String ALL_TASK_MANAGER = "all_taskmanager";
        public static final String ALL_TASK_MANAGER_NETWORK = "all_taskmanager_network";

        public static final String DEPRECATED_FILE_SINKS = "deprecated_file_sinks";

        private Sections() {}
    }

    /**
     * Annotation used on table config options for adding meta data labels.
     *
     *
The {@link TableOption#execMode()} argument indicates the execution mode the config works
     * for (batch, streaming or both).
     */
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Internal
    public @interface TableOption {
        ExecMode execMode();
    }

    /** The execution mode the config works for. */
    public enum ExecMode {
        BATCH("Batch"),
        STREAMING("Streaming"),
        BATCH_STREAMING("Batch and Streaming");

        private final String name;

        ExecMode(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    /**
     * Annotation used on config option fields or options class to mark them as a suffix-option;
     * i.e., a config option where the key is only a suffix, with the prefix being dynamically
     * provided at runtime.
     */
    @Target({ElementType.FIELD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Internal
    public @interface SuffixOption {}

    /**
     * Annotation used on config option fields or REST API message headers to exclude it from
     * documentation.
     */
    @Target({ElementType.FIELD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Internal
    public @interface ExcludeFromDocumentation {
        /** The optional reason why it is excluded from documentation. */
        String value() default "";
    }

    private Documentation() {}
}


text:
using Machine.Specifications;
using MFlow.Core.Conditions;

namespace MFlow.Core.Tests.for_Conditions.given
{
    [Subject("for Conditions")]
    public class multiple_if_conditions_evaluating_to_true
    {
        protected static IFluentConditions<object> fluent_conditions;

        Establish context = () =>
        {
            var expressionBuilder = MFlowConfiguration.Current.ExpressionBuilder.Builder;
            fluent_conditions = new FluentConditions<object>(new object(), expressionBuilder);
            fluent_conditions.If(1 == 1).And(1 == 1).And(true);
        };
    }
}


text:
package org.apache.lens.driver.es;

import org.apache.lens.server.api.error.LensException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.session.SessionState;

import org.testng.annotations.BeforeTest;

public abstract class ESDriverTest {

  protected Configuration config = new Configuration();
  protected ESDriverConfig esDriverConfig;
  protected ESDriver driver = new ESDriver();
  protected MockClientES mockClientES;

  @BeforeTest
  public void beforeTest() throws LensException {
    initializeConfig(config);
    esDriverConfig = new ESDriverConfig(config);
    driver.configure(config, "es", "es1");
    mockClientES = (MockClientES) driver.getESClient();
    HiveConf conf = new HiveConf();
    conf.addResource(config);
    SessionState.start(conf);
  }

  protected abstract void initializeConfig(Configuration config);
}


text:
from __future__ import annotations

import os
from dataclasses import dataclass
from typing import Callable, Iterator

from pants.backend.java.compile.javac import CompileJavaSourceRequest
from pants.engine.fs import AddPrefix, Digest, MergeDigests, Snapshot
from pants.engine.rules import Get, MultiGet, collect_rules, rule
from pants.engine.target import CoarsenedTargets, Targets
from pants.jvm.compile import CompiledClassfiles
from pants.jvm.resolve.coursier_fetch import (
    CoursierLockfileForTargetRequest,
    CoursierResolvedLockfile,
    MaterializedClasspath,
    MaterializedClasspathRequest,
)

_USERCP_RELPATH = "__usercp"

@dataclass(frozen=True)
class Classpath:
    """A transitive classpath which is sufficient to launch the target(s) it was generated for.

    This classpath is guaranteed to contain only JAR files.
    """

    content: Snapshot

    def classpath_entries(self, prefix: str | None = None) -> Iterator[str]:
        """Returns optionally prefixed classpath entry filenames.

        :param prefix: if set, will be prepended to all entries.  This is useful
            if the process working directory is not the same as the root
            directory for the process input `Digest`.
        """
        return self._classpath(lambda _: True, prefix=prefix)

    def user_classpath_entries(self, prefix: str | None = None) -> Iterator[str]:
        """Like `classpath_entries`, but returns only entries corresponding to first-party code."""
        return self._classpath(lambda f: f.startswith(_USERCP_RELPATH), prefix=prefix)

    def _classpath(
        self, predicate: Callable[[str], bool], prefix: str | None = None
    ) -> Iterator[str]:
        def maybe_add_prefix(file_name: str) -> str:
            if prefix is None:
                return file_name
            return os.path.join(prefix, file_name)

        return (
            maybe_add_prefix(file_path) for file_path in self.content.files if predicate(file_path)
        )

@rule
async def classpath(coarsened_targets: CoarsenedTargets) -> Classpath:
    targets = Targets(t for ct in coarsened_targets.closure() for t in ct.members)

    lockfile = await Get(CoursierResolvedLockfile, CoursierLockfileForTargetRequest(targets))
    materialized_classpath = await Get(
        MaterializedClasspath,
        MaterializedClasspathRequest(
            prefix="__thirdpartycp",
            lockfiles=(lockfile,),
        ),
    )
    transitive_user_classfiles = await MultiGet(
        Get(CompiledClassfiles, CompileJavaSourceRequest(component=t))
        for t in coarsened_targets.closure()
    )
    merged_transitive_user_classfiles_digest = await Get(
        Digest, MergeDigests(classfiles.digest for classfiles in transitive_user_classfiles)
    )
    prefixed_transitive_user_classfiles_digest = await Get(
        Digest, AddPrefix(merged_transitive_user_classfiles_digest, _USERCP_RELPATH)
    )

    return Classpath(
        await Get(
            Snapshot,
            MergeDigests(
                (
                    prefixed_transitive_user_classfiles_digest,
                    materialized_classpath.digest,
                )
            ),
        )
    )

def rules():
    return collect_rules()


text:
if [ "$1" = "--help" ]; then
cat <<EOF
${0##*/}, version %version%
This script implemtents statistical analysis for the Inverse Monte Carlo Method
using generic csg tools (csg_stat)

Usage: ${0##*/}
EOF
   exit 0
fi

sim_prog="$(csg_get_property cg.inverse.program)"

topol=$(csg_get_property --allow-empty cg.inverse.$sim_prog.imc.topol)
[[ -z $topol ]] && topol=$(csg_get_property cg.inverse.$sim_prog.topol)
[[ -f $topol ]] || die "${0##*/}: topol file '$topol' not found, possibly you have to add it to cg.inverse.filelist"

traj=$(csg_get_property --allow-empty cg.inverse.$sim_prog.imc.traj)
[[ -z $traj ]] && traj=$(csg_get_property cg.inverse.$sim_prog.traj)
[[ -f $traj ]] || die "${0##*/}: traj file '$traj' not found"

equi_time="$(csg_get_property cg.inverse.$sim_prog.equi_time)"
if [[ ${CSG_RUNTEST} ]] && csg_calc "$equi_time" ">" "0"; then
  msg --color blue --to-stderr "Automatically setting equi_time to 0, because CSG_RUNTEST was set"
  equi_time=0
fi

first_frame="$(csg_get_property cg.inverse.$sim_prog.first_frame)"
if [[ ${CSG_RUNTEST} ]] && csg_calc "$first_frame" ">" "0"; then
  msg --color blue --to-stderr "Automatically setting first_frame to 0, because CSG_RUNTEST was set"
  first_frame=0
fi

tasks=$(get_number_tasks)
msg "Calculating IMC statistics using $tasks tasks"
if is_done "imc_analysis"; then
  echo "IMC analysis is already done"
else
  #copy+resample all target dist in $this_dir
  for_all "non-bonded bonded" do_external resample target '$(csg_get_interaction_property inverse.target)' '$(csg_get_interaction_property name).dist.tgt'

  critical csg_stat --do-imc --options "$CSGXMLFILE" --top "$topol" --trj "$traj" \
        --begin $equi_time --first-frame $first_frame --nt $tasks
  mark_done "imc_analysis"
fi


text:
package com.cloudray.scalapress.account.controller

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{ExceptionHandler, ResponseBody, ModelAttribute, RequestMethod, RequestMapping}
import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import org.springframework.security.authentication.encoding.PasswordEncoder
import org.hibernate.validator.constraints.NotEmpty
import javax.validation.Valid
import org.springframework.validation.Errors
import org.springframework.security.authentication.{AuthenticationManager, UsernamePasswordAuthenticationToken}
import org.springframework.security.web.authentication.WebAuthenticationDetails
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.savedrequest.HttpSessionRequestCache
import com.cloudray.scalapress.theme.ThemeService
import com.cloudray.scalapress.util.mvc.{ScalapressPage, RedirectException}
import scala.beans.BeanProperty
import com.cloudray.scalapress.account._
import com.cloudray.scalapress.account.controller.renderer.RegistrationRenderer
import org.springframework.beans.factory.annotation.{Qualifier, Autowired}
import com.cloudray.scalapress.framework.{ScalapressRequest, ScalapressContext}

/** @author Stephen Samuel */
@Controller
@RequestMapping(Array("register"))
@Autowired
class RegistrationController(themeService: ThemeService,
                             accountPluginDao: AccountPluginDao,
                             accountTypeDao: AccountTypeDao,
                             accountDao: AccountDao,
                             passwordEncoder: PasswordEncoder,
                             context: ScalapressContext,
                             @Qualifier("authman") authenticationManager: AuthenticationManager) {

  //@Qualifier("authman")

  @ExceptionHandler
  @ResponseBody
  def redirect(e: RedirectException, resp: HttpServletResponse) {
    resp.sendRedirect(e.url)
  }

  //
  // @ResponseBody
  // @RequestMapping(Array("type"))
  //    def showAccountTypes(req: HttpServletRequest, @ModelAttribute("form") form: RegistrationForm): ScalapressPage = {
  //
  //        val plugin = accountPluginDao.get
  //        val sreq = ScalapressRequest(req).withTitle("Registration")
  //        val theme = themeService.default
  //        val page = ScalapressPage(theme, sreq)
  //
  //        page.body("
Choose Account Type
")
  //        page.body(RegistrationRenderer.renderChooseAccountType(plugin))
  //        page
  //    }

  @ResponseBody
  @RequestMapping(method = Array(RequestMethod.GET), produces = Array("text/html"))
  def showRegistrationPage(req: HttpServletRequest,
                           @ModelAttribute("form") form: RegistrationForm,
                           errors: Errors): ScalapressPage = {

    val plugin = accountPluginDao.get
    val renderer = new RegistrationRenderer(context.installationDao.get)
    val sreq = ScalapressRequest(req, context).withTitle("Registration")

    val theme = themeService.default
    val page = ScalapressPage(theme, sreq)

    Option(plugin.registrationPageHeader).foreach(arg => page body arg)
    page.body(renderer.renderRegistrationPage(form, plugin, errors, context))
    Option(plugin.registrationPageFooter).foreach(arg => page body arg)

    page
  }

  @ResponseBody
  @RequestMapping(method = Array(RequestMethod.POST), produces = Array("text/html"))
  def submitRegistrationPage(req: HttpServletRequest,
                             resp: HttpServletResponse,
                             @Valid @ModelAttribute("form") form: RegistrationForm,
                             errors: Errors): ScalapressPage = {

    if (accountDao.byEmail(form.email).isDefined) {
      errors
        .rejectValue("email",
        "email.exists",
        "Email address already in use, please choose another. " +
          "If you are already registered you can login here.")
    }

    errors.hasErrors match {
      case true => showRegistrationPage(req, form, errors)
      case false =>

        val account = createAccount(form)
        accountDao.save(account)

        autologin(req, form.email, form.password)

        Option(accountPluginDao.get.registrationRedirect) match {
          case Some(redirect) =>
            throw new RedirectException(redirect)

          case None =>
            Option(new HttpSessionRequestCache().getRequest(req, resp))
              .flatMap(arg => Option(arg.getRedirectUrl)) match {
              case None =>

                val text = Option(accountPluginDao.get.registrationCompletionHtml)
                  .getOrElse(new DefaultRegistrationCompletionRenderer(context.installationDao.get).render)

                val sreq = ScalapressRequest(req, context).withTitle("Registration Completed")
                val theme = themeService.default
                val page = ScalapressPage(theme, sreq)
                page.body(text)
                page
              case Some(redirect) =>
                throw new RedirectException(redirect)
            }
        }
    }
  }

  def createAccount(form: RegistrationForm): Account = {
    val accountType = accountTypeDao.default
    val account = Account(accountType)
    account.name = form.name
    account.email = form.email
    account.passwordHash = passwordEncoder.encodePassword(form.password, null)
    account
  }

  @ModelAttribute("form")
  def form = new RegistrationForm

  def autologin(req: HttpServletRequest, email: String, password: String) {
    val token = new UsernamePasswordAuthenticationToken(email, password)
    req.getSession(true)
    token.setDetails(new WebAuthenticationDetails(req))
    val authenticatedUser = authenticationManager.authenticate(token)
    SecurityContextHolder.getContext.setAuthentication(authenticatedUser)
  }
}

class RegistrationForm {

  @NotEmpty(message = "Please enter your name")
  @BeanProperty
  var name: String = _

  @NotEmpty(message = "Please enter your email address")
  @BeanProperty
  var email: String = _

  @NotEmpty(message = "A password is needed")
  @BeanProperty
  var password: String = _
}


text:
title: Homework #1, Due Monday 1/26/15
---

Haskell Formalities
-------------------

We declare that this is the Hw1 module and import some libraries:

10: > module Hw1 where
11: > import SOE
12: > import Play
13: > import XMLTypes

Part 0: All About You
---------------------

Tell us your name, email and student ID, by replacing the respective
strings below

21: > myName  = "Write Your Name  Here"
22: > myEmail = "Write Your Email Here"
23: > mySID   = "Write Your SID   Here"

Preliminaries
-------------

Before starting this assignment:

* Download and install the [Haskell Platform](http://www.haskell.org/platform/).
* Download the [SOE code bundle](/static/SOE-cse230-wi15.tar.gz).

* Verify that it works by changing into the `SOE/src` directory and
   running `ghci Draw.lhs`, then typing `main0` at the prompt:

~~~
cd SOE/src
ghci Draw.lhs
*Draw> main0
~~~

  You should see a window with some shapes in it.

**NOTE:** If you have trouble installing SOE, [see this page](soe-instructions.html)

5. Download the required files for this assignment: [hw1.tar.gz](/static/hw1.tar.gz).
   Unpack the files and make sure that you can successfully run the main program (in `Main.hs`).
   We've provided a `Makefile`, which you can use if you like. You should see this output:

~~~
Main: Define me!
~~~

Part 1: Defining and Manipulating Shapes
----------------------------------------

You will write all of your code in the `hw1.lhs` file, in the spaces
indicated. Do not alter the type annotations --- your code must
typecheck with these types to be accepted.

The following are the definitions of shapes:

64: > data Shape = Rectangle Side Side
65: >            | Ellipse Radius Radius
66: >            | RtTriangle Side Side
67: >            | Polygon [Vertex]
68: >            deriving Show
69: >
70: > type Radius = Float
71: > type Side   = Float
72: > type Vertex = (Float, Float)

1. Below, define functions `rectangle` and `rtTriangle` as suggested
   at the end of Section 2.1 (Exercise 2.1). Each should return a Shape
   built with the Polygon constructor.

78: > rectangle :: Side -> Side -> Shape
79: > rectangle = error "Define me!"

81: > rtTriangle :: Side -> Side -> Shape
82: > rtTriangle = error "Define me!"

2. Define a function

86: > sides :: Shape -> Int
87: > sides = error "Define me!"

  which returns the number of sides a given shape has.
  For the purposes of this exercise, an ellipse has 42 sides,
  and empty polygons, single points, and lines have zero sides.

3. Define a function

95: > bigger :: Shape -> Float -> Shape
96: > bigger = error "Define me!"

  that takes a shape `s` and expansion factor `e` and returns
  a shape which is the same as (i.e., similar to in the geometric sense)
  `s` but whose area is `e` times the area of `s`.

4. The Towers of Hanoi is a puzzle where you are given three pegs,
   on one of which are stacked $n$ discs in increasing order of size.
   To solve the puzzle, you must move all the discs from the starting peg
   to another by moving only one disc at a time and never stacking
   a larger disc on top of a smaller one.

   To move $n$ discs from peg $a$ to peg $b$ using peg $c$ as temporary storage:

   1. Move $n - 1$ discs from peg $a$ to peg $c$.
   2. Move the remaining disc from peg $a$ to peg $b$.
   3. Move $n - 1$ discs from peg $c$ to peg $b$.

   Write a function

116: > hanoi :: Int -> String -> String -> String -> IO ()
117: > hanoi = error "Define me!"

  that, given the number of discs $n$ and peg names $a$, $b$, and $c$,
  where a is the starting peg,
  emits the series of moves required to solve the puzzle.
  For example, running `hanoi 2 "a" "b" "c"`

  should emit the text

~~~
move disc from a to c
move disc from a to b
move disc from c to b
~~~

Part 2: Drawing Fractals
------------------------

1. The Sierpinski Carpet is a recursive figure with a structure similar to
   the Sierpinski Triangle discussed in Chapter 3:

![Sierpinski Carpet](/static/scarpet.png)

Write a function `sierpinskiCarpet` that displays this figure on the
screen:

143: > sierpinskiCarpet :: IO ()
144: > sierpinskiCarpet = error "Define me!"

Note that you either need to run your program in `SOE/src` or add this
path to GHC's search path via `-i/path/to/SOE/src/`.
Also, the organization of SOE has changed a bit, so that now you use
`import SOE` instead of `import SOEGraphics`.

2. Write a function `myFractal` which draws a fractal pattern of your
   own design.  Be creative!  The only constraint is that it shows some
   pattern of recursive self-similarity.

155: > myFractal :: IO ()
156: > myFractal = error "Define me!"

Part 3: Recursion Etc.
----------------------

First, a warmup. Fill in the implementations for the following functions.

(Your `maxList` and `minList` functions may assume that the lists
they are passed contain at least one element.)

Write a *non-recursive* function to compute the length of a list

168: > lengthNonRecursive :: [a] -> Int
169: > lengthNonRecursive = error "Define me!"

`doubleEach [1,20,300,4000]` should return `[2,40,600,8000]`

173: > doubleEach :: [Int] -> [Int]
174: > doubleEach = error "Define me!"

Now write a *non-recursive* version of the above.

178: > doubleEachNonRecursive :: [Int] -> [Int]
179: > doubleEachNonRecursive = error "Define me!"

`pairAndOne [1,20,300]` should return `[(1,2), (20,21), (300,301)]`

183: > pairAndOne :: [Int] -> [(Int, Int)]
184: > pairAndOne = error "Define me!"

Now write a *non-recursive* version of the above.

189: > pairAndOneNonRecursive :: [Int] -> [(Int, Int)]
190: > pairAndOneNonRecursive = error "Define me!"

`addEachPair [(1,2), (20,21), (300,301)]` should return `[3,41,601]`

194: > addEachPair :: [(Int, Int)] -> [Int]
195: > addEachPair = error "Define me!"

Now write a *non-recursive* version of the above.

199: > addEachPairNonRecursive :: [(Int, Int)] -> [Int]
200: > addEachPairNonRecursive = error "Define me!"

`minList` should return the *smallest* value in the list. You may assume the
input list is *non-empty*.

205: > minList :: [Int] -> Int
206: > minList = error "Define me!"

Now write a *non-recursive* version of the above.

210: > minListNonRecursive :: [Int] -> Int
211: > minListNonRecursive = error "Define me!"

`maxList` should return the *largest* value in the list. You may assume the
input list is *non-empty*.

216: > maxList :: [Int] -> Int
217: > maxList = error "Define me!"

Now write a *non-recursive* version of the above.

221: > maxListNonRecursive :: [Int] -> Int
222: > maxListNonRecursive = error "Define me!"

Now, a few functions for this `Tree` type.

226: > data Tree a = Leaf a | Branch (Tree a) (Tree a)
227: >               deriving (Show, Eq)

`fringe t` should return a list of all the values occurring as a `Leaf`.
So: `fringe (Branch (Leaf 1) (Leaf 2))` should return `[1,2]`

232: > fringe :: Tree a -> [a]
233: > fringe = error "Define me!"

`treeSize` should return the number of leaves in the tree.
So: `treeSize (Branch (Leaf 1) (Leaf 2))` should return `2`.

238: > treeSize :: Tree a -> Int
239: > treeSize = error "Define me!"

`treeSize` should return the height of the tree.
So: `height (Branch (Leaf 1) (Leaf 2))` should return `1`.

244: > treeHeight :: Tree a -> Int
245: > treeHeight = error "Define me!"

Now, a tree where the values live at the nodes not the leaf.

249: > data InternalTree a = ILeaf | IBranch a (InternalTree a) (InternalTree a)
250: >                       deriving (Show, Eq)

`takeTree n t` should cut off the tree at depth `n`.
So `takeTree 1 (IBranch 1 (IBranch 2 ILeaf ILeaf) (IBranch 3 ILeaf ILeaf)))`
should return `IBranch 1 ILeaf ILeaf`.

256: > takeTree :: Int -> InternalTree a -> InternalTree a
257: > takeTree = error "Define me!"

`takeTreeWhile p t` should cut of the tree at the nodes that don't satisfy `p`.
So: `takeTreeWhile (< 3) (IBranch 1 (IBranch 2 ILeaf ILeaf) (IBranch 3 ILeaf ILeaf)))`
should return `(IBranch 1 (IBranch 2 ILeaf ILeaf) ILeaf)`.

263: > takeTreeWhile :: (a -> Bool) -> InternalTree a -> InternalTree a
264: > takeTreeWhile = error "Define me!"

Write the function map in terms of foldr:

268: > myMap :: (a -> b) -> [a] -> [b]
269: > myMap = error "Define me!"

Part 4: Transforming XML Documents
----------------------------------

The rest of this assignment involves transforming XML documents.
To keep things simple, we will not deal with the full generality of XML,
or with issues of parsing. Instead, we will represent XML documents as
instances of the following simplified type:

~~~~
data SimpleXML =
   PCDATA String
 | Element ElementName [SimpleXML]
 deriving Show

type ElementName = String
~~~~

That is, a `SimpleXML` value is either a `PCDATA` ("parsed character
data") node containing a string or else an `Element` node containing a
tag and a list of sub-nodes.

The file `Play.hs` contains a sample XML value. To avoid getting into
details of parsing actual XML concrete syntax, we'll work with just
this one value for purposes of this assignment. The XML value in
`Play.hs` has the following structure (in standard XML syntax):

~~~
<PLAY>
  <TITLE>TITLE OF THE PLAY</TITLE>
  <PERSONAE>
    <PERSONA> PERSON1 </PERSONA>
    <PERSONA> PERSON2 </PERSONA>
    ... -- MORE PERSONAE
    </PERSONAE>
  <ACT>
    <TITLE>TITLE OF FIRST ACT</TITLE>
    <SCENE>
      <TITLE>TITLE OF FIRST SCENE</TITLE>
      <SPEECH>
        <SPEAKER> PERSON1 </SPEAKER>
        <LINE>LINE1</LINE>
        <LINE>LINE2</LINE>
        ... -- MORE LINES
      </SPEECH>
      ... -- MORE SPEECHES
    </SCENE>
    ... -- MORE SCENES
  </ACT>
  ... -- MORE ACTS
</PLAY>
~~~

* `sample.html` contains a (very basic) HTML rendition of the same
  information as `Play.hs`. You may want to have a look at it in your
  favorite browser.  The HTML in `sample.html` has the following structure
  (with whitespace added for readability):

~~~

TITLE OF THE PLAY

Dramatis Personae

    PERSON1

    PERSON2

    ...

TITLE OF THE FIRST ACT

TITLE OF THE FIRST SCENE

    PERSON1

    LINE1

    LINE2

    ...
    PERSON2

    LINE1

    LINE2

    ...

TITLE OF THE SECOND SCENE

    PERSON3

    LINE1

    LINE2

    ...

~~~

You will write a function `formatPlay` that converts an XML structure
representing a play to another XML structure that, when printed,
yields the HTML specified above (but with no whitespace except what's
in the textual data in the original XML).

360: > formatPlay :: SimpleXML -> SimpleXML
361: > formatPlay xml = PCDATA "WRITE ME!"

The main action that we've provided below will use your function to
generate a file `dream.html` from the sample play. The contents of this
file after your program runs must be character-for-character identical
to `sample.html`.

368: > mainXML = do writeFile "dream.html" $ xml2string $ formatPlay play
369: >              testResults "dream.html" "sample.html"
370: >
371: > firstDiff :: Eq a => [a] -> [a] -> Maybe ([a],[a])
372: > firstDiff [] [] = Nothing
373: > firstDiff (c:cs) (d:ds)
374: >      | c==d = firstDiff cs ds
375: >      | otherwise = Just (c:cs, d:ds)
376: > firstDiff cs ds = Just (cs,ds)
377: >
378: > testResults :: String -> String -> IO ()
379: > testResults file1 file2 = do
380: >   f1 <- readFile file1
381: >   f2 <- readFile file2
382: >   case firstDiff f1 f2 of
383: >     Nothing -> do
384: >       putStr "Success!\n"
385: >     Just (cs,ds) -> do
386: >       putStr "Results differ: '"
387: >       putStr (take 20 cs)
388: >       putStr "' vs '"
389: >       putStr (take 20 ds)
390: >       putStr "'\n"

Important: The purpose of this assignment is not just to "get the job
done" --- i.e., to produce the right HTML. A more important goal is to
think about what is a good way to do this job, and jobs like it. To
this end, your solution should be organized into two parts:

1. a collection of generic functions for transforming XML structures
   that have nothing to do with plays, plus

2. a short piece of code (a single definition or a collection of short
   definitions) that uses the generic functions to do the particular
   job of transforming a play into HTML.

Obviously, there are many ways to do the first part. The main challenge
of the assignment is to find a clean design that matches the needs of
the second part.

You will be graded not only on correctness (producing the required
output), but also on the elegance of your solution and the clarity and
readability of your code and documentation.  Style counts.  It is
strongly recommended that you rewrite this part of the assignment a
couple of times: get something working, then step back and see if
there is anything you can abstract out or generalize, rewrite it, then
leave it alone for a few hours or overnight and rewrite it again. Try
to use some of the higher-order programming techniques we've been
discussing in class.

Submission Instructions
-----------------------

* If working with a partner, you should both submit your assignments
  individually.
* Make sure your `hw1.lhs` is accepted by GHC without errors or warnings.
* Attach your `hw1.hs` file in an email to `cse230@goto.ucsd.edu` with the
  subject "HW1" (minus the quotes).
  *This address is unmonitored!*

Credits
-------

This homework is essentially Homeworks 1 & 2 from
UPenn's CIS 552.


text:
package org.apereo.cas.logout;

import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.web.UrlValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;

/**
 * This is {@link DefaultSingleLogoutServiceLogoutUrlBuilder} which acts on a registered
 * service to determine how the logout url endpoint should be decided.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
public class DefaultSingleLogoutServiceLogoutUrlBuilder implements SingleLogoutServiceLogoutUrlBuilder {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSingleLogoutServiceLogoutUrlBuilder.class);

    private final UrlValidator urlValidator;

    public DefaultSingleLogoutServiceLogoutUrlBuilder(final UrlValidator urlValidator) {
        this.urlValidator = urlValidator;
    }

    @Override
    public URL determineLogoutUrl(final RegisteredService registeredService, final WebApplicationService singleLogoutService) {
        try {
            final URL serviceLogoutUrl = registeredService.getLogoutUrl();
            if (serviceLogoutUrl != null) {
                LOGGER.debug("Logout request will be sent to [{}] for service [{}]", serviceLogoutUrl, singleLogoutService);
                return serviceLogoutUrl;
            }
            final String originalUrl = singleLogoutService.getOriginalUrl();
            if (this.urlValidator.isValid(originalUrl)) {
                LOGGER.debug("Logout request will be sent to [{}] for service [{}]", originalUrl, singleLogoutService);
                return new URL(originalUrl);
            } else {
                LOGGER.debug("Logout request will not be sent, the URL [{}] for service [{}] is not valid", originalUrl, singleLogoutService);
            }
            return null;
        } catch (final Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<module version="0.1">
    <name lang="en">Content Tracker</name>
    <description lang="en">Statistics of which content pages students have viewed are avaiable in "My Tracker".  Overall content usage is also available to instructors.</description>
    <maintainers>
        <maintainer>
            <name>ATutor Team</name>
            <email>info@atutor.ca</email>
        </maintainer>
    </maintainers>
    <url>http://atutor.ca</url>
    <license>GPL</license>
	<release>
        <version>0.1</version>
        <use_privilege>true</use_privilege>
        <date>2005-08-25</date>
        <state>stable</state>
        <notes></notes>
    </release>
</module>


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Address — django BMF alpha documentation</title>

    <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />

    <link rel="top" title="django BMF alpha documentation" href="../index.html"/>
        <link rel="up" title="User Guide" href="index.html"/>
        <link rel="next" title="Customer" href="customer.html"/>
        <link rel="prev" title="Accounting" href="accounting.html"/>

             django BMF

                0.2.3

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Getting Started

User Guide

Accounting

Address

Customer

Employee

Invoice

Position

Product

Project

Task

Tax

Team

Timesheet

Quotation

Developing Applications

Tutorial

Philosophies

About Us

Contributing

TODO-List

Roadmap

Changelog

        django BMF

Docs »

User Guide »

Address

             View page source

Address¶

        Next

         Previous

        © Copyright 2013, Sebastian Braun.

  Built with Sphinx using a theme provided by Read the Docs.


text:
package poolcontroller

import (
	"os"
	"reflect"

	"github.com/openebs/maya/cmd/cstor-pool-mgmt/controller/common"
	apis "github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1"
	"github.com/pkg/errors"
)

const (
	// PoolPrefix is prefix for pool name
	PoolPrefix string = "cstor-"
)

// IsRightCStorPoolMgmt is to check if the pool request is for this pod.
func IsRightCStorPoolMgmt(csp *apis.NewTestCStorPool) bool {
	return os.Getenv(string(common.OpenEBSIOCStorID)) == string(csp.ObjectMeta.UID)
}

// IsDestroyed is to check if the call is for cStorPool destroy.
func IsDestroyed(csp *apis.NewTestCStorPool) bool {
	return csp.ObjectMeta.DeletionTimestamp != nil
}

// IsOnlyStatusChange is to check only status change of cStorPool object.
func IsOnlyStatusChange(ocsp, ncsp *apis.NewTestCStorPool) bool {
	if reflect.DeepEqual(ocsp.Spec, ncsp.Spec) &&
		!reflect.DeepEqual(ocsp.Status, ncsp.Status) {
		return true
	}
	return false
}

// IsStatusChange is to check only status change of cStorPool object.
func IsStatusChange(oldStatus, newStatus apis.CStorPoolStatus) bool {
	return !reflect.DeepEqual(oldStatus, newStatus)
}

// IsSyncEvent is to check if ResourceVersion of cStorPool object is not modifed.
func IsSyncEvent(ocsp, ncsp *apis.NewTestCStorPool) bool {
	return ncsp.ResourceVersion == ocsp.ResourceVersion
}

// IsEmptyStatus is to check if the status of cStorPool object is empty.
func IsEmptyStatus(csp *apis.NewTestCStorPool) bool {
	return csp.Status.Phase == apis.CStorPoolStatusEmpty
}

// IsPendingStatus is to check if the status of cStorPool object is pending.
func IsPendingStatus(csp *apis.NewTestCStorPool) bool {
	return csp.Status.Phase == apis.CStorPoolStatusPending
}

// IsErrorDuplicate is to check if the status of cStorPool object is error-duplicate.
func IsErrorDuplicate(csp *apis.NewTestCStorPool) bool {
	return csp.Status.Phase == apis.CStorPoolStatusErrorDuplicate
}

// IsDeletionFailedBefore is to make sure no other operation should happen if the
// status of cStorPool is deletion-failed.
func IsDeletionFailedBefore(csp *apis.NewTestCStorPool) bool {
	return csp.Status.Phase == apis.CStorPoolStatusDeletionFailed
}

// IsUIDSet check if UID is set or not
func IsUIDSet(csp *apis.NewTestCStorPool) bool {
	return len(csp.ObjectMeta.UID) != 0
}

// IsReconcileDisabled check if reconciliation is disabled for given object or not
func IsReconcileDisabled(csp *apis.NewTestCStorPool) bool {
	return csp.Annotations[string(apis.OpenEBSDisableReconcileKey)] == "true"
}

// IsHostNameChanged check if hostname for CSP object is changed
func IsHostNameChanged(ocsp, ncsp *apis.NewTestCStorPool) bool {
	return ncsp.Spec.HostName != ocsp.Spec.HostName
}

// IsEmpty check if string is empty or not
func IsEmpty(s string) bool {
	return len(s) == 0
}

// ErrorWrapf wrap error
// If given err is nil then it will return new error
func ErrorWrapf(err error, format string, args ...interface{}) error {
	if err == nil {
		return errors.Errorf(format, args...)
	}

	return errors.Wrapf(err, format, args...)
}

// PoolName return pool name for given CSP object
func PoolName(csp *apis.NewTestCStorPool) string {
	return PoolPrefix + string(csp.ObjectMeta.UID)
}


text:
Preconfigured all-in-one servers
================================

A pre configured server is an all-in-one endpoint serving a specific class of
application clients. As the individual endpoints, they depend on the use of a
:doc:`validator`.

Construction is simple, only import your validator and you are good to go::

    from your_validator import your_validator
    from oauthlib.oauth2 import WebApplicationServer

    server = WebApplicationServer(your_validator)

If you prefer to construct tokens yourself you may pass a token generator::

    def your_token_generator(request):
        return 'a_custom_token' + request.client_id

    server = WebApplicationServer(your_validator, token_generator=your_token_generator)

.. autoclass:: oauthlib.oauth2.WebApplicationServer
    :members:

.. autoclass:: oauthlib.oauth2.MobileApplicationServer
    :members:

.. autoclass:: oauthlib.oauth2.LegacyApplicationServer
    :members:

.. autoclass:: oauthlib.oauth2.BackendApplicationServer
    :members:


text:
<?php
require_once __DIR__ . '/../../../TestHelper.php';
require_once PHPTEST_PATH . 'Spy.php';

class PHPTest_Spy_StubTest extends PHPTest_TestCase {
    public function testReturnValue() {
        $stub = PHPTest_Spy::interceptFunction('mail');
        $stub->setReturnValue($expected = "TEST");

        $result = mail();

        $this->assertEquals($expected, $result, 'Wrong result');
    }

    public function testException() {
        $stub = PHPTest_Spy::interceptFunction('mail');
        $stub->setException($expected = new Exception('TEST'));

        try {
            $result = mail();
        } catch (Exception $e) {
        }

        $this->assertEquals($expected, $e, 'Wrong exception');
    }

    public function testGetCallParams() {
        $stub = PHPTest_Spy::interceptFunction('mail');
        $args1 = array();
        $args2 = array($exp1 = PHPTest_Util::getRandomNumber(), $exp2 = PHPTest_Util::getRandomNumber());

        mail();
        mail($exp1, $exp2);

        $this->assertEquals(array($args1, $args2), $stub->getCallParams(), 'Wrong result');
    }
}


text:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'errorDescription'
})

export class ErrorDescriptionPipe implements PipeTransform {
    transform(value: any, ...args: any[]): any {
        switch (value) {
            case 10: {
                return "File is empty";
            }
            case 20: {
                return "File doesn't have extension";
            }
            case 30: {
                return "File extension is invalid";
            }
            case 40: {
                return "File format doesn't supported";
            }
            case 99:
            default: {
                return "An unexpected error occurred. Please try again. If the problem persists, please contact the developer.";
            }
        }
    }
}


text:
package us.corenetwork.pumpkinchallenge;

import org.bukkit.command.CommandSender;

public class PumpkinCommand {

	public static void run(CommandSender sender) {
		if (!EventManager.isActive())
		{
			Util.Message(Settings.getString(Setting.MESSAGE_NOT_ACTIVE), sender);
			return;
		}

		EventManager.tryAdvanceHour();

		String message = Settings.getString(Setting.MESSAGE_PUMPKINS);
		message = message.replace("<HourCollected>", Integer.toString(EventManager.drops));
		message = message.replace("<TotalCollected>", Integer.toString(EventManager.drops + EventManager.totalDrops));

		int hourlyCap = Settings.getInt(Setting.CAP_PER_HOUR);
		int duration = Settings.getInt(Setting.EVENT_DURATION);

		message = message.replace("<HourlyCap>", Integer.toString(hourlyCap));
		message = message.replace("<TotalCap>", Integer.toString(duration * hourlyCap));

		Util.Message(message, sender);
	}

}


text:
'use strict';

var StringAtom = require('../BaseAtoms/StringAtom.js');
var validator = require('validator');
var er = require('../AtomError.js');

/**
 * Atom to store email
 * @class
 * @classdesc atom to store email
 */
class EmailAtom extends StringAtom {
    /**
     * @desc
     * Creates an instance of EmailAtom.
     *
     * @constructor
     * @param {String} [value=undefined] init value of EmailAtom
     * @param {object} [options={
            "database_type":"VARCHAR",
            "type":"STRING",
            "max":255
        }] set options for new EmailAtom
     *
     * @example
     * var ea = new EmailAtom('sample@email.com');
     *
     *
     * @memberOf EmailAtom
     */
    constructor(value=undefined, op={
            "database_type":"VARCHAR",
            "type":"STRING",
            "max":255
        }) {
        op.max = 255;
        super(value,op);

    }

    /**
     * Check's if newValue is valid email address
     * @private
     *
     * @param {String} newValue email to be set
     * @returns {Boolean} true if newValue can be set, else false
     *
     * @memberOf EmailAtom
     */
    _isNewValueValid(newValue) {
        if( !super._isNewValueValid(newValue) ) return false;
        if(newValue===null) return true;
        if(newValue===undefined) return true;

        if( !validator.isEmail(newValue) ) {
            this._putError(er.INVALID_EMAIL );
            return false;
        }
        return true;
    }
}

module.exports = EmailAtom;


text:
--TEST--
Test session_set_cookie_params() function : variation
--INI--
session.cookie_lifetime=3600
--SKIPIF--
<?php include('skipif.inc'); ?>
--FILE--
<?php

ob_start();

/*
 * Prototype : void session_set_cookie_params(int $lifetime [, string $path [, string $domain [, bool $secure [, bool $httponly]]]])
 * Description : Set the session cookie parameters
 * Source code : ext/session/session.c
 */

echo "*** Testing session_set_cookie_params() : variation ***\n";

var_dump(ini_get("session.cookie_lifetime"));
var_dump(session_set_cookie_params(3600));
var_dump(ini_get("session.cookie_lifetime"));
var_dump(session_start());
var_dump(ini_get("session.cookie_lifetime"));
var_dump(session_set_cookie_params(1800));
var_dump(ini_get("session.cookie_lifetime"));
var_dump(session_destroy());
var_dump(ini_get("session.cookie_lifetime"));
var_dump(session_set_cookie_params(1234567890));
var_dump(ini_get("session.cookie_lifetime"));

echo "Done";
ob_end_flush();
?>
--EXPECTF--
*** Testing session_set_cookie_params() : variation ***
string(4) "3600"
NULL
string(4) "3600"
bool(true)
string(4) "3600"
NULL
string(4) "1800"
bool(true)
string(4) "1800"
NULL
string(10) "1234567890"
Done


text:
"""distutils.command.build_clib

Implements the Distutils 'build_clib' command, to build a C/C++ library
that is included in the module distribution and needed by an extension
module."""

# created (an empty husk) 1999/12/18, Greg Ward
# fleshed out 2000/02/03-04

__revision__ = "$Id: build_clib.py,v 1.22 2000/10/14 04:06:40 gward Exp $"

# XXX this module has *lots* of code ripped-off quite transparently from
# build_ext.py -- not surprisingly really, as the work required to build
# a static library from a collection of C source files is not really all
# that different from what's required to build a shared object file from
# a collection of C source files.  Nevertheless, I haven't done the
# necessary refactoring to account for the overlap in code between the
# two modules, mainly because a number of subtle details changed in the
# cut 'n paste.  Sigh.

import os, string
from types import *
from distutils.core import Command
from distutils.errors import *
from distutils.sysconfig import customize_compiler

def show_compilers ():
    from distutils.ccompiler import show_compilers
    show_compilers()

class build_clib (Command):

    description = "build C/C++ libraries used by Python extensions"

    user_options = [
        ('build-clib', 'b',
         "directory to build C/C++ libraries to"),
        ('build-temp', 't',
         "directory to put temporary build by-products"),
        ('debug', 'g',
         "compile with debugging information"),
        ('force', 'f',
         "forcibly build everything (ignore file timestamps)"),
        ('compiler=', 'c',
         "specify the compiler type"),
        ]

    boolean_options = ['debug', 'force']

    help_options = [
        ('help-compiler', None,
         "list available compilers", show_compilers),
        ]

    def initialize_options (self):
        self.build_clib = None
        self.build_temp = None

        # List of libraries to build
        self.libraries = None

        # Compilation options for all libraries
        self.include_dirs = None
        self.define = None
        self.undef = None
        self.debug = None
        self.force = 0
        self.compiler = None

    # initialize_options()

    def finalize_options (self):

        # This might be confusing: both build-clib and build-temp default
        # to build-temp as defined by the "build" command.  This is because
        # I think that C libraries are really just temporary build
        # by-products, at least from the point of view of building Python
        # extensions -- but I want to keep my options open.
        self.set_undefined_options('build',
                                   ('build_temp', 'build_clib'),
                                   ('build_temp', 'build_temp'),
                                   ('compiler', 'compiler'),
                                   ('debug', 'debug'),
                                   ('force', 'force'))

        self.libraries = self.distribution.libraries
        if self.libraries:
            self.check_library_list(self.libraries)

        if self.include_dirs is None:
            self.include_dirs = self.distribution.include_dirs or []
        if type(self.include_dirs) is StringType:
            self.include_dirs = string.split(self.include_dirs,
                                             os.pathsep)

        # XXX same as for build_ext -- what about 'self.define' and
        # 'self.undef' ?

    # finalize_options()

    def run (self):

        if not self.libraries:
            return

        # Yech -- this is cut 'n pasted from build_ext.py!
        from distutils.ccompiler import new_compiler
        self.compiler = new_compiler(compiler=self.compiler,
                                     verbose=self.verbose,
                                     dry_run=self.dry_run,
                                     force=self.force)
        customize_compiler(self.compiler)

        if self.include_dirs is not None:
            self.compiler.set_include_dirs(self.include_dirs)
        if self.define is not None:
            # 'define' option is a list of (name,value) tuples
            for (name,value) in self.define:
                self.compiler.define_macro(name, value)
        if self.undef is not None:
            for macro in self.undef:
                self.compiler.undefine_macro(macro)

        self.build_libraries(self.libraries)

    # run()

    def check_library_list (self, libraries):
        """Ensure that the list of libraries (presumably provided as a
           command option 'libraries') is valid, i.e. it is a list of
           2-tuples, where the tuples are (library_name, build_info_dict).
           Raise DistutilsSetupError if the structure is invalid anywhere;
           just returns otherwise."""

        # Yechh, blecch, ackk: this is ripped straight out of build_ext.py,
        # with only names changed to protect the innocent!

        if type(libraries) is not ListType:
            raise DistutilsSetupError, \
                  "'libraries' option must be a list of tuples"

        for lib in libraries:
            if type(lib) is not TupleType and len(lib) != 2:
                raise DistutilsSetupError, \
                      "each element of 'libraries' must a 2-tuple"

            if type(lib[0]) is not StringType:
                raise DistutilsSetupError, \
                      "first element of each tuple in 'libraries' " + \
                      "must be a string (the library name)"
            if '/' in lib[0] or (os.sep != '/' and os.sep in lib[0]):
                raise DistutilsSetupError, \
                      ("bad library name '%s': " +
                       "may not contain directory separators") % \
                      lib[0]

            if type(lib[1]) is not DictionaryType:
                raise DistutilsSetupError, \
                      "second element of each tuple in 'libraries' " + \
                      "must be a dictionary (build info)"
        # for lib

    # check_library_list ()

    def get_library_names (self):
        # Assume the library list is valid -- 'check_library_list()' is
        # called from 'finalize_options()', so it should be!

        if not self.libraries:
            return None

        lib_names = []
        for (lib_name, build_info) in self.libraries:
            lib_names.append(lib_name)
        return lib_names

    # get_library_names ()

    def build_libraries (self, libraries):

        compiler = self.compiler

        for (lib_name, build_info) in libraries:
            sources = build_info.get('sources')
            if sources is None or type(sources) not in (ListType, TupleType):
                raise DistutilsSetupError, \
                      ("in 'libraries' option (library '%s'), " +
                       "'sources' must be present and must be " +
                       "a list of source filenames") % lib_name
            sources = list(sources)

            self.announce("building '%s' library" % lib_name)

            # First, compile the source code to object files in the library
            # directory.  (This should probably change to putting object
            # files in a temporary build directory.)
            macros = build_info.get('macros')
            include_dirs = build_info.get('include_dirs')
            objects = self.compiler.compile(sources,
                                            output_dir=self.build_temp,
                                            macros=macros,
                                            include_dirs=include_dirs,
                                            debug=self.debug)

            # Now "link" the object files together into a static library.
            # (On Unix at least, this isn't really linking -- it just
            # builds an archive.  Whatever.)
            self.compiler.create_static_lib(objects, lib_name,
                                            output_dir=self.build_clib,
                                            debug=self.debug)

        # for libraries

    # build_libraries ()

# class build_lib


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/Magento/Mtf/ObjectManager/etc/config.xsd">
    <preference for="Mage\SalesRule\Test\Handler\SalesRule\SalesRuleInterface" type="\Mage\SalesRule\Test\Handler\SalesRule\Curl" />
</config>


text:
<?php

namespace Google\Service\AndroidPublisher;

class DeviceRam extends \Google\Model
{
  /**
   * @var string
   */
  public $maxBytes;
  /**
   * @var string
   */
  public $minBytes;

  /**
   * @param string
   */
  public function setMaxBytes($maxBytes)
  {
    $this->maxBytes = $maxBytes;
  }
  /**
   * @return string
   */
  public function getMaxBytes()
  {
    return $this->maxBytes;
  }
  /**
   * @param string
   */
  public function setMinBytes($minBytes)
  {
    $this->minBytes = $minBytes;
  }
  /**
   * @return string
   */
  public function getMinBytes()
  {
    return $this->minBytes;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(DeviceRam::class, 'Google_Service_AndroidPublisher_DeviceRam');


text:
package com.tassioauad.trackercoach.view.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.tassioauad.trackercoach.TrackerCoachApplication;
import com.tassioauad.trackercoach.R;
import com.tassioauad.trackercoach.dagger.MeasurementDetailViewModule;
import com.tassioauad.trackercoach.model.entity.ActivityLocation;
import com.tassioauad.trackercoach.presenter.MeasurementDetailPresenter;
import com.tassioauad.trackercoach.view.MeasurementDetailView;

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

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MeasurementDetailFragment extends Fragment implements MeasurementDetailView {

    private static final String BUNDLE_KEY_ACTIVITYLOCATION = "bundle_key_activitylocation";

    @Inject
    MeasurementDetailPresenter presenter;
    @Bind(R.id.textview_onfoot_distance)
    TextView textViewOnFootDistance;
    @Bind(R.id.textview_onfoot_time)
    TextView textViewOnFootTime;
    @Bind(R.id.textview_onfoot_averagespeed)
    TextView textViewOnFootAverageSpeed;
    @Bind(R.id.textview_running_distance)
    TextView textViewRunningDistance;
    @Bind(R.id.textview_running_time)
    TextView textViewRunningTime;
    @Bind(R.id.textview_running_averagespeed)
    TextView textViewRunningAverageSpeed;
    @Bind(R.id.textview_bicycle_distance)
    TextView textViewBicycleDistance;
    @Bind(R.id.textview_bicycle_time)
    TextView textViewBicycleTime;
    @Bind(R.id.textview_bicycle_averagespeed)
    TextView textViewBicycleAverageSpeed;
    @Bind(R.id.textview_invehicle_distance)
    TextView textViewVehicleDistance;
    @Bind(R.id.textview_invehicle_time)
    TextView textViewVehicleTime;
    @Bind(R.id.textview_invehicle_averagespeed)
    TextView textViewVehicleAverageSpeed;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_measurementdetail, container, false);
        ((TrackerCoachApplication) getActivity().getApplication()).getObjectGraph()
                .plus(new MeasurementDetailViewModule(this)).inject(this);
        ButterKnife.bind(this, view);

        List<ActivityLocation> activityLocationList = getArguments().getParcelableArrayList(BUNDLE_KEY_ACTIVITYLOCATION);
        presenter.init(activityLocationList);

        return view;
    }

    public static MeasurementDetailFragment newInstance(List<ActivityLocation> activityLocationList) {
        MeasurementDetailFragment measurementDetailFragment = new MeasurementDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(BUNDLE_KEY_ACTIVITYLOCATION, new ArrayList<>(activityLocationList));
        measurementDetailFragment.setArguments(bundle);

        return measurementDetailFragment;
    }

    @Override
    public void showInVehicleDetails(long distance, long timeInMilis) {
        float distanceInKm = distance / 1000f;
        float timeInHour = distanceInKm > 0 ? timeInMilis / 1000f / 60f / 60f : 0;
        float averageSpeed = distanceInKm > 0 && timeInHour > 0 ? distanceInKm / timeInHour : 0;
        textViewVehicleDistance.setText(String.format(getString(R.string.measurementdetailfragment_measuredistance), distanceInKm));
        textViewVehicleTime.setText(String.format(getString(R.string.measurementdetailfragment_measuretime), timeInHour));
        textViewVehicleAverageSpeed.setText(String.format(getString(R.string.measurementdetailfragment_measureaveragespeed), averageSpeed));
    }

    @Override
    public void showOnBicycleDetails(long distance, long timeInMilis) {
        float distanceInKm = distance / 1000f;
        float timeInHour = distanceInKm > 0 ? timeInMilis / 1000f / 60f / 60f : 0;
        float averageSpeed = distanceInKm > 0 && timeInHour > 0 ? distanceInKm / timeInHour : 0;
        textViewBicycleDistance.setText(String.format(getString(R.string.measurementdetailfragment_measuredistance), distanceInKm));
        textViewBicycleTime.setText(String.format(getString(R.string.measurementdetailfragment_measuretime), timeInHour));
        textViewBicycleAverageSpeed.setText(String.format(getString(R.string.measurementdetailfragment_measureaveragespeed), averageSpeed));
    }

    @Override
    public void showOnFootDetails(long distance, long timeInMilis) {
        float distanceInKm = distance / 1000f;
        float timeInHour = distanceInKm > 0 ? timeInMilis / 1000f / 60f / 60f : 0;
        float averageSpeed = distanceInKm > 0 && timeInHour > 0 ? distanceInKm / timeInHour : 0;
        textViewOnFootDistance.setText(String.format(getString(R.string.measurementdetailfragment_measuredistance), distanceInKm));
        textViewOnFootTime.setText(String.format(getString(R.string.measurementdetailfragment_measuretime), timeInHour));
        textViewOnFootAverageSpeed.setText(String.format(getString(R.string.measurementdetailfragment_measureaveragespeed), averageSpeed));
    }

    @Override
    public void showRunningDetails(long distance, long timeInMilis) {
        float distanceInKm = distance / 1000f;
        float timeInHour = distanceInKm > 0 ? timeInMilis / 1000f / 60f / 60f : 0;
        float averageSpeed = distanceInKm > 0 && timeInHour > 0 ? distanceInKm / timeInHour : 0;
        textViewRunningDistance.setText(String.format(getString(R.string.measurementdetailfragment_measuredistance), distanceInKm));
        textViewRunningTime.setText(String.format(getString(R.string.measurementdetailfragment_measuretime), timeInHour));
        textViewRunningAverageSpeed.setText(String.format(getString(R.string.measurementdetailfragment_measureaveragespeed), averageSpeed));
    }
}


text:
layout: post
title: Twitter / Identi.ca support
author: balleyne
nid: 48
comments: true
redirect_from: /forum/topics/48/
created: 1247558504
---

As per a discussion on Twitter, I really think that oscatholic should add support for Identi.ca alongside Twitter!

It's bit odd for an explicitly "open source" site to support a proprietary web service, but not its open source alternative. Identi.ca may have a smaller audience, but that audience is the open source community.

Plus, Identi.ca has the same API as Twitter. The Identi.ca project page on drupal.org just links to the Twitter module, which supports both services. It shouldn't be that hard to add support.

This is a perfect opportunity for oscatholic to lead by example.


text:
package com.shishuo.cms.exception;

/**
 *
 * 系统配置Key获得的Value为空
 *
 * @author Herbert
 *
 */
public class AuthException extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public AuthException(String msg) {
		super(msg);
	}
}


text:
from .iaa_svm_protectable_item import IaaSVMProtectableItem

class AzureIaaSClassicComputeVMProtectableItem(IaaSVMProtectableItem):
    """IaaS VM workload-specific backup item representing the Classic Compute VM.

    :param backup_management_type: Type of backup managemenent to backup an
     item.
    :type backup_management_type: str
    :param friendly_name: Friendly name of the backup item.
    :type friendly_name: str
    :param protection_state: State of the back up item. Possible values
     include: 'Invalid', 'NotProtected', 'Protecting', 'Protected'
    :type protection_state: str or :class:`ProtectionStatus
     <azure.mgmt.recoveryservicesbackup.models.ProtectionStatus>`
    :param protectable_item_type: Polymorphic Discriminator
    :type protectable_item_type: str
    :param virtual_machine_id: Fully qualified ARM ID of the virtual machine.
    :type virtual_machine_id: str
    """

    _validation = {
        'protectable_item_type': {'required': True},
    }

    def __init__(self, backup_management_type=None, friendly_name=None, protection_state=None, virtual_machine_id=None):
        super(AzureIaaSClassicComputeVMProtectableItem, self).__init__(backup_management_type=backup_management_type, friendly_name=friendly_name, protection_state=protection_state, virtual_machine_id=virtual_machine_id)
        self.protectable_item_type = 'Microsoft.ClassicCompute/virtualMachines'


text:
package gcsx

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"net/url"
	"path"

	"cloud.google.com/go/storage"
	"github.com/apache/beam/sdks/v2/go/pkg/beam/internal/errors"
	"google.golang.org/api/option"
)

// NewClient creates a new GCS client with default application credentials, and supplied
// OAuth scope. The OAuth scopes are defined in https://godoc.org/cloud.google.com/go/storage#pkg-constants.
func NewClient(ctx context.Context, scope string) (*storage.Client, error) {
	return storage.NewClient(ctx, option.WithScopes(scope))
}

// NewUnauthenticatedClient creates a new GCS client without authentication.
func NewUnauthenticatedClient(ctx context.Context) (*storage.Client, error) {
	return storage.NewClient(ctx, option.WithoutAuthentication())
}

// Upload writes the given content to GCS. If the specified bucket does not
// exist, it is created first. Returns the full path of the object.
func Upload(ctx context.Context, client *storage.Client, project, bucket, object string, r io.Reader) (string, error) {
	exists, err := BucketExists(ctx, client, bucket)
	if err != nil {
		return "", err
	}
	if !exists {
		if err = CreateBucket(ctx, client, project, bucket); err != nil {
			return "", err
		}
	}

	if err := WriteObject(ctx, client, bucket, object, r); err != nil {
		return "", err
	}
	return fmt.Sprintf("gs://%s/%s", bucket, object), nil

}

// CreateBucket creates a bucket in GCS.
func CreateBucket(ctx context.Context, client *storage.Client, project, bucket string) error {
	return client.Bucket(bucket).Create(ctx, project, nil)
}

// BucketExists returns true iff the given bucket exists.
func BucketExists(ctx context.Context, client *storage.Client, bucket string) (bool, error) {
	_, err := client.Bucket(bucket).Attrs(ctx)
	if err == storage.ErrBucketNotExist {
		return false, nil
	}
	return err == nil, err
}

// WriteObject writes the given content to the specified object. If the object
// already exist, it is overwritten.
func WriteObject(ctx context.Context, client *storage.Client, bucket, object string, r io.Reader) error {
	w := client.Bucket(bucket).Object(object).NewWriter(ctx)
	_, err := io.Copy(w, r)
	if err != nil {
		return err
	}
	return w.Close()
}

// ReadObject reads the content of the given object in full.
func ReadObject(ctx context.Context, client *storage.Client, bucket, object string) ([]byte, error) {
	r, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(r)
}

// MakeObject creates a object location from bucket and path. For example,
// MakeObject("foo", "bar/baz") returns "gs://foo/bar/baz". The bucket
// must be non-empty.
func MakeObject(bucket, path string) string {
	if bucket == "" {
		panic("bucket must be non-empty")
	}
	return fmt.Sprintf("gs://%v/%v", bucket, path)
}

// ParseObject deconstructs a GCS object name into (bucket, name).
func ParseObject(object string) (bucket, path string, err error) {
	parsed, err := url.Parse(object)
	if err != nil {
		return "", "", err
	}

	if parsed.Scheme != "gs" {
		return "", "", errors.Errorf("object %s must have 'gs' scheme", object)
	}
	if parsed.Host == "" {
		return "", "", errors.Errorf("object %s must have bucket", object)
	}
	if parsed.Path == "" {
		return parsed.Host, "", nil
	}

	// remove leading "/" in URL path
	return parsed.Host, parsed.Path[1:], nil
}

// Join joins a GCS path with an element. Preserves
// the gs:// prefix.
func Join(object string, elms ...string) string {
	bucket, prefix, err := ParseObject(object)
	if err != nil {
		panic(err)
	}
	return MakeObject(bucket, path.Join(prefix, path.Join(elms...)))
}


text:
using System;
using Cpf.App;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Parquet.CLI.Commands;
using Parquet.CLI.Models;
using Serilog;
using static Cpf.PoshConsole;

namespace Parquet.CLI
{
   /// <summary>
   /// This is a parquet.net dotnet CLI tool that can be installed globally. An ultimate replacement for "parq".
   /// It is very much in progress and in design.
   ///
   /// It's using CPF library for handling console commands which is very fresh and unstable. Why? Because no one
   /// ever
   /// </summary>
   class Program
   {
      static int Main(string[] args)
      {
         var app = new Application("Parquet CLI (https://github.com/elastacloud/parquet-dotnet)");
         ConfigureTelemetry(app, args);

         LinePrimitive<bool> verboseOption = app.SharedOption<bool>("-d|--debug", Help.App_Verbose);

         app.OnBeforeExecuteCommand(cmd =>
         {
            PoshWrite("{p}{a}{r}{q} v", ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.Green, ConsoleColor.Blue);

            string[] pts = app.Version.Split('.');
            for (int i = 0; i < pts.Length; i++)
            {
               if (i > 0)
                  Write(".", ConsoleColor.DarkGray);

               Write(pts[i], ConsoleColor.Green);
            }
            WriteLine();
            WriteLine();
         });

         app.OnError((cmd, err) =>
         {
            Log.Error(err, "error in command {command}", cmd.Name);
            return true;
         });

         app.Command("schema", cmd =>
         {
            cmd.Description = Help.Command_Schema_Description;

            LinePrimitive<string> path = cmd.Argument<string>("path", Help.Argument_Path).Required().FileExists();

            cmd.OnExecute(() =>
            {
               new SchemaCommand(path.Value).Execute();
            });
         });

         app.Command("meta", cmd =>
         {
            cmd.Description = Help.Command_Meta_Description;

            LinePrimitive<string> path = cmd.Argument<string>("path", Help.Argument_Path).Required().FileExists();

            cmd.OnExecute(() =>
            {
               new MetaCommand(path).Execute();
            });
         });

         app.Command("convert", cmd =>
         {
            cmd.Description = Help.Command_Convert_Description;

            LinePrimitive<string> input = cmd.Argument<string>("input", Help.Command_Convert_Input).Required().FileExists();
            //LinePrimitive<string> output = cmd.Argument<string>("output", Help.Command_Convert_Output);
            //LinePrimitive<string> style = cmd.Option<string>("-s|--style", Help.Command_Convert_Style);
            LinePrimitive<bool> pretty = cmd.Option<bool>("-p|--pretty", Help.Command_Convert_Pretty);
            LinePrimitive<int> maxRows = cmd.Option<int>("-m|--max-rows", Help.Command_Convert_MaxRows, 10);

            cmd.OnExecute(() =>
            {
               new ConvertCommand(input, null, null, pretty).Execute(maxRows);
            });
         });

         app.Command("view-all", cmd =>
         {
            cmd.Description = Help.Command_ViewAll_Description;
            LinePrimitive<string> path = cmd.Argument<string>("path", Help.Argument_Path).Required().FileExists();
            LinePrimitive<bool> expandCells = cmd.Option<bool>("-e|--expand", Help.Command_ViewAll_Expand, false);
            LinePrimitive<int> displayMinWidth = cmd.Option<int>("-m|--min", Help.Command_ViewAll_Min, 5);
            LinePrimitive<bool> displayNulls = cmd.Option<bool>("-n|--nulls", Help.Command_ViewAll_Nulls, false);

            cmd.OnExecute(() =>
            {
               ViewSettings settings = new ViewSettings
               {
                  displayMinWidth = displayMinWidth,
                  displayNulls = displayNulls,
                  displayTypes = false,
                  expandCells = expandCells,
                  truncationIdentifier = string.Empty
               };

               new DisplayFullCommand<Views.FullConsoleView>(path).Execute(settings);
            });
         });

         app.Command("view", cmd =>
         {
            cmd.Description = Help.Command_View_Description;
            LinePrimitive<string> path = cmd.Argument<string>("path", Help.Argument_Path).Required();
            LinePrimitive<bool> expandCells = cmd.Option<bool>("-e|--expand", Help.Command_ViewAll_Expand, false);
            LinePrimitive<int> displayMinWidth = cmd.Option<int>("-m|--min", Help.Command_ViewAll_Min, 5);
            LinePrimitive<bool> displayNulls = cmd.Option<bool>("-n|--nulls", Help.Command_ViewAll_Nulls, true);
            LinePrimitive<bool> displayTypes = cmd.Option<bool>("-t|--types", Help.Command_ViewAll_Types, true);
            LinePrimitive<string> truncationIdentifier = cmd.Option<string>("-u|--truncate", Help.Command_ViewAll_Types, defaultValue: "...");

            cmd.OnExecute(() =>
            {

               ViewSettings settings = new ViewSettings
               {
                  displayMinWidth = displayMinWidth,
                  displayNulls = displayNulls,
                  displayTypes = displayTypes,
                  expandCells = expandCells,
                  truncationIdentifier = truncationIdentifier.Value ?? "...",
                  displayReferences = false
               };

               new DisplayFullCommand<Views.InteractiveConsoleView>(path).Execute(settings);
            });
         });

         int exitCode = app.Execute();

         Log.CloseAndFlush();

         return exitCode;
      }

      private static void ConfigureTelemetry(Application app, string[] args)
      {
         //let's see if we get complains about performance here, should be OK

         /*
          * If you're wondering whether hardcoding the key is good or not - it doesn't really matter. The worst you can _attempt_ to do
          * is send us a lot of fake telemetry but we can live with it. Even if we would hide the key you could still do the same thing
          * by launching application instead of calling appinsights REST API.
          */

         /*var configuration = new TelemetryConfiguration
         {
            InstrumentationKey = "0a310ae1-0f93-43fc-bfa1-62e92fc869b9",
            TelemetryChannel = new PersistenceChannel()
         };*/

         Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .Enrich.WithProperty("Version", app.Version)
            .WriteTo.ApplicationInsightsTraces("0a310ae1-0f93-43fc-bfa1-62e92fc869b9")
            .WriteTo.Trace()
            .CreateLogger();

         Telemetry.CliInvoked(args);
      }
   }
}


text:
using Sniper.History;
using System.Collections.ObjectModel;

namespace Sniper.Contracts.Entities.History
{
    public interface IHasFeatureHistory
    {
        Collection<FeatureSimpleHistory> History { get; }
    }
}