text:
import optparse
import os
import sys
import time

# The tables maintained by this script
maintained_tables = [
    {'tablename' : 'bvermeulen_sdx', 'id_column' : 'id'},
    {'tablename' : 'msb_metrics', 'id_column' : 'id'},
    {'tablename' : 'nriganikytopo2', 'id_column' : 'id'},
    {'tablename' : 'starlight_metrics', 'id_column' : 'id'},
    {'tablename' : 'nmetrics_cpu', 'id_column' : 'oml_tuple_id'},
    {'tablename' : 'nmetrics_memory', 'id_column' : 'oml_tuple_id'},
    {'tablename' : 'nmetrics_network', 'id_column' : 'oml_tuple_id'}
                     ]

class TableMaintainer():
    def __init__(self):
        self._opts = self.parse_options()

    def add_parser_options(self, parser):
        parser.add_option("--dbname", help="Name of database", default="gec22")
        parser.add_option("--dbhost", help="host of database", default='localhost')
        parser.add_option("--dbuser", help="Database user", default="oml2")
        parser.add_option("--dbpass", help="Database password", default="0mlisg00d4u")
        parser.add_option("--dbport", help="Database port", default="5432")
        parser.add_option("--outfile", help="Database script filename")
        parser.add_option("--dumpdir", help="Database dump directory")
        parser.add_option('--frequency', help="How often to gather metrics in seconds",
                          default="3600")
        parser.add_option("--window", help="Length of window of data maintained in tables",
                          default="86400")

    # Check that all required parser arguments are provided
    def check_options(self, opts):
        required_missing_fields = []

        if opts.outfile == None: required_missing_fields.append('outfile')
        if opts.dumpdir == None: required_missing_fields.append('dumpdir')

	if len(required_missing_fields) > 0:
            raise Exception("Missing required arguments: " +
                            " ".join(required_missing_fields))

    # Parse command line options
    def parse_options(self):
       argv = sys.argv[1:]
       parser = optparse.OptionParser()
       self.add_parser_options(parser)
       [opts, args] = parser.parse_args(argv)
       self.check_options(opts)
       return opts

    def dump_database(self, tablename, timestamp):
        dumpfile = "%s-%s.sql" % (tablename, timestamp)
        dumpfile = os.path.join(self._opts.dumpdir, dumpfile)
        cmd = "PGPASSWORD=%s /usr/bin/pg_dump -U %s -h %s -t %s -f %s %s"
        cmd = cmd % (self._opts.dbpass, self._opts.dbuser, self._opts.dbhost,
                     tablename, dumpfile, self._opts.dbname)
        print "Dump command: %s" % (cmd)
        os.system(cmd)

    def run(self):

        timestamp = int(time.time())
        print "Running TableMaintainer at %d" % (timestamp)

        sql_file = open(self._opts.outfile, 'wb')

        # Start a transaction
        sql_file.write('begin transaction;\n')

        # Loop over all maintained tables
        for table in maintained_tables:

            tablename = table['tablename']
            id_column = table['id_column']
            # archive_tablename = "%s_ARCHIVE" % tablename
            window = int(self._opts.window)

            print "Backing up table %s" % (tablename)
            self.dump_database(tablename, timestamp)

            print "Maintaining table %s" % tablename

            # Make sure there is an empty archive table (copy of table)
            # create_stmt = "create table if not exists %s (like %s)" % (archive_tablename, tablename)
            # sql_file.write(create_stmt + ";\n");

            # Insert a record into table history
            insert_stmt = "insert into table_history (timestamp, max_id, tablename) " +\
                "values (%d, (select max(%s) from %s), '%s')" % \
                (timestamp, id_column, tablename, tablename);
            insert_stmt = "insert into table_history (timestamp, max_id, tablename) " +\
                "values (%d, (select max(%s) from %s), '%s')" %  \
                (timestamp, id_column, tablename, tablename);
            print "INSERT = %s" % insert_stmt
            sql_file.write(insert_stmt + ";\n");

            # Copy all rows with ID more than 24 hours old from data table into archive table
            # copy_template = "insert into %s select * from %s where %s < " +\
            #     "(select max(max_id) from table_history where tablename = '%s' " + \
            #     "and timestamp = (select max(timestamp) from table_history " + \
            #     "where tablename = '%s' and timestamp < %d))"
            # copy_stmt = copy_template % \
            #     (archive_tablename, tablename, id_column, tablename, tablename, (timestamp-window))
            # sql_file.write(copy_stmt + ";\n");

            # Delete all rows with ID more than 24 hours old from data table
            delete_template = "delete from %s where %s < (select max(max_id) from table_history " + \
                "where tablename = '%s' and timestamp = (select max(timestamp) " + \
                "from table_history where tablename = '%s' and timestamp < %d))"
            delete_stmt = delete_template % \
                (tablename, id_column, tablename, tablename, (timestamp-window))
            sql_file.write(delete_stmt + ";\n");

        # Commit transaction
        sql_file.write("commit;\n");

        sql_file.close()

        # Invoke SQL file
	sql_cmd = "PGPASSWORD=%s psql -U %s -h %s %s -f %s" % \
            (self._opts.dbpass, self._opts.dbuser, self._opts.dbhost,
             self._opts.dbname, self._opts.outfile)
        print "INVOKING CMD = %s" % sql_cmd
        os.system(sql_cmd)

def main():
    tbl_maint = TableMaintainer();
    while True:
        tbl_maint.run()
        frequency = int(tbl_maint._opts.frequency)
        time.sleep(frequency)

if __name__ == "__main__":
    sys.exit(main())


text:
package com.ivanov.tech.profile.service;

import java.util.ArrayList;

import com.ivanov.tech.communicator.service.TransportBase;

public class CommunicatorService extends com.ivanov.tech.communicator.service.CommunicatorService{

	//---------------Communicator Demo URL-------------
    public final static String URL_PROTOCOL="ws://";
    public final static String URL_DOMEN="igorpi25.ru";
    public final static String URL_PORT=":8001";//Websocket server port
    public final static String URL_SERVER=URL_PROTOCOL+URL_DOMEN+URL_PORT;
    public final static String URL_START_SERVER="http://"+URL_DOMEN+"/v2/communicator/start";

	@Override
	public ArrayList<TransportBase> createTransports() {

		ArrayList<TransportBase> transports=new ArrayList<TransportBase>();

		TransportProfile transportprofile=new TransportProfile(this);
		transports.add(transportprofile);

		return transports;
	}

	@Override
	public String getServerUrl() {
		return URL_SERVER;
	}

	@Override
	public String getRestartServerUrl() {
		return URL_START_SERVER;
	}

	@Override
	public String getCommunicatorServiceClass() {
		return CommunicatorService.class.getCanonicalName();
	}

}

redpajama_set_name: RedPajamaGithub


text:
Return the sine of the parameter

### Declaration
```glsl
float sin(float angle)
vec2 sin(vec2 angle)
vec3 sin(vec3 angle)
vec4 sin(vec4 angle)
```

### Parameters
```angle``` specify the quantity, in radians, of which to return the sine.

### Description
```sin()``` returns the trigonometric sine of angle.

### See Also
[acos](/glossary/?search=acos), [cos](/glossary/?search=cos), [asin](/glossary/?search=asin), [tan](/glossary/?search=tan), [atan](/glossary/?search=atan), [Chapter 05: Shaping Functions](/05/)


text:
license: Licensed to the Apache Software Foundation (ASF) under one
         or more contributor license agreements.  See the NOTICE file
         distributed with this work for additional information
         regarding copyright ownership.  The ASF licenses this file
         to you under the Apache License, Version 2.0 (the
         "License"); you may not use this file except in compliance
         with the License.  You may obtain a copy of the License at

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

         Unless required by applicable law or agreed to in writing,
         software distributed under the License is distributed on an
         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
         KIND, either express or implied.  See the License for the
         specific language governing permissions and limitations
         under the License.
---

volumeupbutton
===========

このイベントはユーザーがボリュームアップボタンを押したときに呼び出されます。

    document.addEventListener("volumeupbutton", yourCallbackFunction, false);

詳細
-------

もしデフォルトのボリュームアップボタンの挙動を上書きしたい場合は、 `volumeupbutton` イベントにイベントリスナーを登録することができます。

通常は、 `deviceready` イベントを受け取った後、 `document.addEventListener` を通じてイベントリスナーを登録します。

サポートされているプラットフォーム
-------------------

- BlackBerry WebWorks (OS 5.0 以上)

使用例
-------------

    document.addEventListener("volumeupbutton", onVolumeUpKeyDown, false);

    function onVolumeUpKeyDown() {
        // ボリュームアップボタン関する操作を記述
    }

詳細な使用例
------------

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
                          "http://www.w3.org/TR/html4/strict.dtd">
    <html>
      <head>
        <title>Cordova Volume Up Button 使用例</title>

        <script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Cordova の読み込み完了まで待機
        //
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }

        // Cordova 準備完了
        //
        function onDeviceReady() {
            // イベントリスナーを登録
            document.addEventListener("volumeupbutton", onVolumeUpKeyDown, false);
        }

        // ボリュームアップボタン関する操作を記述
        //
        function onVolumeUpKeyDown() {
        }

        </script>
      </head>
      <body onload="onLoad()">
      </body>
    </html>


text:
from __future__ import absolute_import
from __future__ import print_function

from buildbot.db import base

class TagsConnectorComponent(base.DBConnectorComponent):

    def findTagId(self, name):
        tbl = self.db.model.tags
        return self.findSomethingId(
            tbl=tbl,
            whereclause=(tbl.c.name == name),
            insert_values=dict(
                name=name,
                name_hash=self.hashColumns(name),
            ))


text:
@implementation MTRecommendHeadView

- (instancetype)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self) {
        self.backgroundColor=RGB(200, 200, 200);
        UILabel *label=[[UILabel alloc]init];
        label.text=@"  猜你喜欢";
        label.font=[UIFont boldSystemFontOfSize:16];
        label.backgroundColor=[UIColor whiteColor];
        [self addSubview:label];

    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    UILabel *label=self.subviews[0];

    label.frame=CGRectMake(0, 20, self.width, 30);

}

@end


text:
package edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2;

/**
 * SAML 2 Attribute Query configuration settings.
 */
public class AttributeQueryConfiguration extends AbstractSAML2ProfileConfiguration {

    /** ID for this profile configuration. */
    public static final String PROFILE_ID = "urn:mace:shibboleth:2.0:profiles:saml2:query:attribute";

    /** {@inheritDoc} */
    public String getProfileId() {
        return PROFILE_ID;
    }
}


text:
import { Component } from '@angular/core';
import { ColumnPickerGroup, ColumnPickerGroupItem } from '@ux-aspects/ux-aspects';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

    /** Store a list of all selected columns */
    selected: ReadonlyArray<string> = [
        'Type',
        'Date',
        'Requested by',
        'Status',
        'Completion'
    ];

    /** Store a list of columns that must be selected */
    locked: ReadonlyArray<string> = ['ID'];

    /** Store a list of columns that are not selected or locked */
    deselected: ReadonlyArray<string | ColumnPickerGroupItem> = [
        { group: 'Metadata', name: 'Author' },
        { group: 'Metadata', name: 'Category' },
        { group: 'Metadata', name: 'Date Created' },
        { group: 'Metadata', name: 'Date Modified' },
        { group: 'Metadata', name: 'Department' },
        'Document ID',
        'Flag',
        'From',
        'Icon',
        'Importance',
        'Location',
        'Location ID',
        'Message',
        { group: 'Metadata', name: 'Organization' },
        'Time',
        'Time Created',
        'Time Modified',
        'Work Completed'
    ];

    groups: ColumnPickerGroup[] = [
        { name: 'Metadata', expanded: true }
    ];

}


text:
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".

Replace these with more appropriate tests for your application.
"""

from ga_ows.views import common
from django.test.client import Client
from django.test import TestCase
from django.utils import unittest
import tempfile
import json
from lxml import etree

class tdict(dict):
    def __add__(self, other):
        ret = tdict(self.copy())
        for k,v in other.items():
            ret[k] = v

        return ret

class TestOWSCommon(TestCase):
    def testGetCapabilitiesParsing(self):
        g = common.GetCapabilitiesMixin()
        req = g._parse_xml_GetCapabilities(etree.fromstring("""<?xml version="1.0" encoding="UTF-8"?>
        <GetCapabilities xmlns="http://www.opengis.net/ows/1.1"
        xmlns:ows="http://www.opengis.net/ows/1.1"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.opengis.net/ows/1.1
        fragmentGetCapabilitiesRequest.xsd" service="WCS"
        updateSequence="XYZ123">

           <AcceptVersions>
              <Version>1.0.0</Version>
              <Version>0.8.3</Version>
           </AcceptVersions>
           <Sections>

Contents

           </Sections>
           <AcceptFormats>
              <OutputFormat>text/xml</OutputFormat>
           </AcceptFormats>
        </GetCapabilities>"""))
        self.assertEqual(req.cleaned_data['service'], 'WCS')
        self.assertEqual(req.cleaned_data['accepted_formats'], ['text/xml'])
        self.assertEqual(req.cleaned_data['accepted_versions'], ['1.0.0', '0.8.3'])

    def textExceptionPrinting(self):
        e = common.OWSException()
        print e.xml(extend=True)

class TestWFSHttpGet(TestCase):
    fixtures = ['wfs_test.json']

    def stdTestCall(self, request, parms={}, suffix='', path='/tests/wfs'):
        rq = tdict({"service" : "WFS", "version" : "2.0.0"})
        response = self.client.get(path, (rq + {"request" : request}) + parms)
        self.assertEqual(response.status_code, 200)
        _0, name = tempfile.mkstemp(dir='/Users/jeff/geoanalytics/tmp', prefix=request, suffix=suffix+".xml") #yes, I intend for this to not be deleted upon exit
        f = open(name,'w')
        f.write(response.content)
        f.close()
        print name
        return response

    def testGetCapabilities(self):
        self.stdTestCall("GetCapabilities")

    def testListStoredQueries(self):
        self.stdTestCall("ListStoredQueries")

    def testDescribeStoredQueries(self):
        self.stdTestCall('DescribeStoredQueries', {'storedqueryid' : 'GetFeatureById'})

    def testGetFeature(self):
        self.stdTestCall("GetFeature", suffix='-all', parms={
            'srs_name' : '4326',
            'count' : 1,
            'startindex' : 1,
            'outputformat' : 'GeoJSON',
            'typenames' : ['ga_ows:WFSPointTest'],
            'filter' : json.dumps({'state' : 'NC'}),
            'filterlanguage' : 'JSON',
            'bbox' : '-81,29,-76,36',
            'sortby' : 'state'
        })

    def testGetFeatureSimple(self):
        self.stdTestCall("GetFeature", suffix='-simple', parms={
            'srs_name' : '4326',
            'typenames' : ['ga_ows:WFSPointTest'],
            'bbox' : '-81,29,-76,36'
        })

    def testGetFeatureMercator(self):
        self.stdTestCall("GetFeature", suffix='-mercator', parms={
            'srs_name' : '3857',
            'typenames' : ['ga_ows:WFSPointTest'],
            'bbox' : '-9016878.75425516,3375646.0349193094,-8460281.300288793,4300621.372044271',
            'outputformat' : 'GeoJSON',
        })

    def testGetFeatureSortBy(self):
        self.stdTestCall("GetFeature", suffix='-sortby', parms={
            'srs_name' : '3857',
            'typenames' : ['ga_ows:WFSPointTest'],
            'bbox' : '-81,29,-76,36',
            'sortby' : 'state',
            'outputformat' : 'GeoJSON',
        })

    def testGetFeatureCount(self):
        self.stdTestCall("GetFeature", suffix='-count', parms={
            'srs_name' : '4326',
            'typenames' : ['ga_ows:WFSPointTest'],
            'bbox' : '-81,29,-76,36',
            'count' : 1,
            'outputformat' : 'GeoJSON',
        })

    def testGetFeatureMaxFeatures(self):
        self.stdTestCall("GetFeature", suffix='-maxfeatures', parms={
            'srs_name' : '4326',
            'typenames' : ['ga_ows:WFSPointTest'],
            'bbox' : '-81,29,-76,36',
            'maxfeatures' : 1,
            'outputformat' : 'GeoJSON',
        })

    def testGetFeatureStartIndex(self):
        self.stdTestCall("GetFeature", suffix='-startindex', parms={
            'srs_name' : '4326',
            'typenames' : ['ga_ows:WFSPointTest'],
            'bbox' : '-81,29,-76,36',
            'startindex' : 2,
            'outputformat' : 'GeoJSON',
        })

    def testDescribeFeatureTypeJSON(self):
        self.stdTestCall("DescribeFeatureType", parms={"typename" : "ga_ows:WFSPointTest", "outputformat" : "json"})

    def testDescribeFeatureTypeXml(self):
        self.stdTestCall("DescribeFeatureType", parms={"typename" : "ga_ows:WFSPointTest"})

    @unittest.skip("get property value not implemented yet")
    def testGetPropertyValue(self):
        self.stdTestCall("GetPropertyValue", parms={
            'srs_name' : '4326',
            'typenames' : ['ga_ows:WFSPointTest'],
            'bbox' : '-81,29,-76,36'
        })

    @unittest.skip("create stored query not implemented yet")
    def testCreateStoredQuery(self):
        self.stdTestCall("CreateStoredQuery")

    @unittest.skip("drop stored query not implemented yet.")
    def testDropStoredQuery(self):
        self.stdTestCall("DropStoredQuery")

@unittest.skip("Skipping XML POST as it's not supported yet")
class TestWFSHttpPostXML(TestCase):
    def testGetCapabilities(self):
        client = Client()

    def testListStoredQueries(self):
        client = Client()

    def testDescribeStoredQueries(self):
        client = Client()

    def testGetFeature(self):
        client = Client()

    def testDescribeFeatureType(self):
        client = Client()

    def testGetPropertyValue(self):
        client = Client()

    def testCreateStoredQuery(self):
        client = Client()

    def testDropStoredQuery(self):
        client = Client()

@unittest.skip("Skipping transactions as they're not supported yet.")
class TestWFSTHttpGet(TestCase):
    def testTransaction(self):
        client = Client()

    def testGetFeatureWithLock(self):
        client = Client()

    def testLockFeature(self):
        client = Client()

@unittest.skip("Skipping transactions via POST as they're not supported yet.")
class TestWFSTHttpPost(unittest.TestCase):
    def testTransaction(self):
        client = Client()

    def testGetFeatureWithLock(self):
        client = Client()

    def testLockFeature(self):
        client = Client()

@unittest.skip("Skipping transactions via XML post as they're not supported yet.")
class TestWFSHttpPostXML(unittest.TestCase):
    def testTransaction(self):
        client = Client()

    def testGetFeatureWithLock(self):
        client = Client()

    def testLockFeature(self):
        client = Client()


text:
namespace PyCuDNN {
    struct TensorDescriptor :
      RAII< cudnnTensorDescriptor_t,
            cudnnCreateTensorDescriptor,
            cudnnDestroyTensorDescriptor > {};
}

#endif // PYCUDNN_TENSOR_DESCRIPTOR_HPP


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 128: 78 (1972)

#### Original name
Eriomycopsis chorleyi Hansf.

### Remarks
null


text:
class ProgRuntimeHandler
{
	public:
		ProgRuntimeHandler(pid_t pid, int status, DeviceHandlerFactory &deviceHandlerFactory);

		bool Step();

	private:
		bool SpySyscallEnter();
		bool SpySyscallExit();

		bool HasZero(const unsigned long data);
		bool ReadRemoteText(long addr, char *out, int maxlen);

		const pid_t _pid;
		const int _status;
		const DeviceHandlerFactory &_deviceHandlerFactory;
		const Log _log;

		bool _exiting;
		int _syscall;
		char _openpath[256];
		DeviceHandlerRegistry _deviceHandlerRegistry;
		DeviceHandler *_currentDeviceHandler;
};


text:
namespace Urho3D
{

enum TrailType
{
    TT_FACE_CAMERA = 0,
    TT_BONE
};

class IndexBuffer;
class VertexBuffer;

/// Trail is consisting of series of tails. Two connected points make a tail.
struct URHO3D_API TrailPoint
{
    /// Construct a zero-initialized TrailPoint.
    TrailPoint() = default;
    /// Construct a TrailPoint with the given position and forward vector.
    TrailPoint(const Vector3& position, const Vector3& forward);
    /// Position.
    Vector3 position_;
    /// Forward vector.
    Vector3 forward_;
    /// Parent position. Trail bone type uses this.
    Vector3 parentPos_;
    /// Elapsed length inside the trail.
    float elapsedLength_{};
    /// Next point to make a tail.
    TrailPoint* next_{};
    /// Tail time to live.
    float lifetime_{};
    /// Distance for sorting.
    float sortDistance_{};
};

/// Drawable component that creates a tail.
class URHO3D_API RibbonTrail : public Drawable
{
    URHO3D_OBJECT(RibbonTrail, Drawable);

public:
    /// Construct.
    explicit RibbonTrail(Context* context);
    /// Destruct.
    ~RibbonTrail() override;
    /// Register object factory.
    /// @nobind
    static void RegisterObject(Context* context);
    /// Process octree raycast. May be called from a worker thread.
    void ProcessRayQuery(const RayOctreeQuery& query, Vector<RayQueryResult>& results) override;
    /// Handle enabled/disabled state change.
    void OnSetEnabled() override;
    /// Update before octree reinsertion. Is called from a main thread.
    void Update(const FrameInfo &frame) override;
    /// Calculate distance and prepare batches for rendering. May be called from worker thread(s), possibly re-entrantly.
    void UpdateBatches(const FrameInfo& frame) override;
    /// Prepare geometry for rendering. Called from a worker thread if possible (no GPU update).
    void UpdateGeometry(const FrameInfo& frame) override;
    /// Return whether a geometry update is necessary, and if it can happen in a worker thread.
    UpdateGeometryType GetUpdateGeometryType() override;

    /// Set material.
    /// @property
    void SetMaterial(Material* material);
    /// Set material attribute.
    void SetMaterialAttr(const ResourceRef& value);
    /// Set distance between points.
    /// @property
    void SetVertexDistance(float length);
    /// Set width of the tail. Only works for face camera trail type.
    /// @property
    void SetWidth(float width);
    /// Set vertex blended color for start of trail.
    /// @property
    void SetStartColor(const Color& color);
    /// Set vertex blended color for end of trail.
    /// @property
    void SetEndColor(const Color& color);
    /// Set vertex blended color for start of trail.
    /// @property
    void SetStartScale(float startScale);
    /// Set vertex blended scale for end of trail.
    /// @property
    void SetEndScale(float endScale);
    /// Set how the trail behave.
    /// @property
    void SetTrailType(TrailType type);
    /// Set base velocity applied to the trail.
    /// @property
    void SetBaseVelocity(const Vector3& baseVelocity);
    /// Set whether tails are sorted by distance. Default false.
    /// @property
    void SetSorted(bool enable);
    /// Set tail time to live.
    /// @property
    void SetLifetime(float time);
    /// Set whether trail should be emitting.
    /// @property
    void SetEmitting(bool emitting);
    /// Set whether to update when trail emitter are not visible.
    /// @property
    void SetUpdateInvisible(bool enable);
    /// Set number of column for every tails. Can be useful for fixing distortion at high angle.
    /// @property
    void SetTailColumn(unsigned tailColumn);
    /// Set animation LOD bias.
    /// @property
    void SetAnimationLodBias(float bias);
    /// Mark for bounding box and vertex buffer update. Call after modifying the trails.
    void Commit();

    /// Return material.
    /// @property
    Material* GetMaterial() const;

    /// Return material attribute.
    ResourceRef GetMaterialAttr() const;

    /// Get distance between points.
    /// @property
    float GetVertexDistance() const { return vertexDistance_;  }

    /// Get width of the trail.
    /// @property
    float GetWidth() const { return width_; }

    /// Get vertex blended color for start of trail.
    /// @property
    const Color& GetStartColor() const { return startColor_; }

    /// Get vertex blended color for end of trail.
    /// @property
    const Color& GetEndColor() const { return endColor_;  }

    /// Get vertex blended scale for start of trail.
    /// @property
    float GetStartScale() const { return startScale_; }

    /// Get vertex blended scale for end of trail.
    /// @property
    float GetEndScale() const { return endScale_; }

    /// Return whether tails are sorted.
    /// @property
    bool IsSorted() const { return sorted_; }

    /// Return tail time to live.
    /// @property
    float GetLifetime() const {return lifetime_;}

    /// Return animation LOD bias.
    /// @property
    float GetAnimationLodBias() const { return animationLodBias_; }

    /// Return how the trail behave.
    /// @property
    TrailType GetTrailType() const { return trailType_; }

    /// Return base trail velocity.
    /// @property
    const Vector3& GetBaseVelocity() const { return baseVelocity_; }

    /// Return number of column for tails.
    /// @property
    unsigned GetTailColumn() const { return tailColumn_; }

    /// Return whether is currently emitting.
    /// @property
    bool IsEmitting() const { return emitting_ ; }

    /// Return whether to update when trail emitter are not visible.
    /// @property
    bool GetUpdateInvisible() const { return updateInvisible_; }

protected:
    /// Handle node being assigned.
    void OnSceneSet(Scene* scene) override;
    /// Recalculate the world-space bounding box.
    void OnWorldBoundingBoxUpdate() override;
    /// Mark vertex buffer to need an update.
    void MarkPositionsDirty();
    /// Tails.
    Vector<TrailPoint> points_;
    /// Tails sorted flag.
    bool sorted_;
    /// Animation LOD bias.
    float animationLodBias_;
    /// Animation LOD timer.
    float animationLodTimer_;
    /// Trail type.
    TrailType trailType_;
    /// Base velocity applied to the trail.
    Vector3 baseVelocity_;

private:
    /// Handle scene post-update event.
    void HandleScenePostUpdate(StringHash eventType, VariantMap& eventData);

    /// Resize RibbonTrail vertex and index buffers.
    void UpdateBufferSize();
    /// Rewrite RibbonTrail vertex buffer.
    void UpdateVertexBuffer(const FrameInfo& frame);
    /// Update/Rebuild tail mesh only if position changed (called by UpdateBatches()).
    void UpdateTail(float timeStep);
    /// Geometry.
    SharedPtr<Geometry> geometry_;
    /// Vertex buffer.
    SharedPtr<VertexBuffer> vertexBuffer_;
    /// Index buffer.
    SharedPtr<IndexBuffer> indexBuffer_;
    /// Transform matrices for position and orientation.
    Matrix3x4 transforms_;
    /// Buffers need resize flag.
    bool bufferSizeDirty_;
    /// Vertex buffer needs rewrite flag.
    bool bufferDirty_;
    /// Previous position of tail.
    Vector3 previousPosition_;
    /// Distance between points. Basically is tail length.
    float vertexDistance_;
    /// Width of trail.
    float width_;
    /// Number of points.
    unsigned numPoints_;
    /// Color for start of trails.
    Color startColor_;
    /// Color for end of trails.
    Color endColor_;
    /// Scale for start of trails.
    float startScale_;
    /// End for start of trails.
    float endScale_;
    /// Last scene timestep.
    float lastTimeStep_;
    /// Lifetime.
    float lifetime_;
    /// Number of columns for every tails.
    unsigned tailColumn_;
    /// Rendering framenumber on which was last updated.
    i32 lastUpdateFrameNumber_;
    /// Need update flag.
    bool needUpdate_;
    /// Previous offset to camera for determining whether sorting is necessary.
    Vector3 previousOffset_;
    /// Trail pointers for sorting.
    Vector<TrailPoint*> sortedPoints_;
    /// Force update flag (ignore animation LOD momentarily).
    bool forceUpdate_;
    /// Currently emitting flag.
    bool emitting_;
    /// Update when invisible flag.
    bool updateInvisible_;

    /// End of trail point for smoother tail disappearance.
    TrailPoint endTail_;
    /// The time the tail become end of trail.
    float startEndTailTime_;
};

}


text:
// Karma configuration
// Generated on Tue Dec 02 2014 17:57:03 GMT+1100 (AEDT)

module.exports = function(config) {
  var configuration = {

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'sinon-chai'],

    // list of files / patterns to load in the browser
    files: [
      'src/static/bower_components/angular/angular.min.js',
      'src/static/bower_components/angular-mocks/angular-mocks.js',
      'src/static/bower_components/jquery/dist/jquery.min.js',
      'src/static/bower_components/knockout/dist/knockout.js',
      'node_modules/should/should.min.js',
      'src/static/js/*.js',
      'src/plugins/**/public/js/*.js',
      'src/plugins/**/public/tests/*.test.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/plugins/**/public/js/*.js': ['coverage']
    },

    coverageReporter: {
      // type : 'html',
      type : 'text-summary',
      dir : 'coverage/'
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    //browsers: ['Chrome', 'PhantomJS'],
    browsers: ['Chrome'],

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false

  };

  if(process.env.TRAVIS){
    configuration.browsers = ['Chrome_travis_ci'];
  }

  config.set(configuration);

};


text:
package org.pentaho.big.data.kettle.plugins.hdfs.vfs;

import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.pentaho.big.data.api.cluster.NamedClusterService;
import org.pentaho.big.data.plugins.common.ui.NamedClusterWidgetImpl;
import org.pentaho.runtime.test.RuntimeTester;
import org.pentaho.runtime.test.action.RuntimeTestActionService;
import org.pentaho.vfs.ui.VfsBrowser;
import org.pentaho.vfs.ui.VfsFileChooserDialog;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;

public class HadoopVfsFileChooserDialogTest {

  private HadoopVfsFileChooserDialog hadoopVfsFileChooserDialog = null;
  private static final Integer SELECTED_INDEX = -1;
  private static final String[] NAMED_CLUSTER_NAMES = {"name1", "name2", "name3"};

  @Before
  public void Initialization() {
    hadoopVfsFileChooserDialog = mock( HadoopVfsFileChooserDialog.class );
  }

  @After
  public void finalize() {
    hadoopVfsFileChooserDialog = null;
  }

  @Test
  public void testActivate() {
    doCallRealMethod().when( hadoopVfsFileChooserDialog ).activate();

    VfsFileChooserDialog vfsFileChooserDialog = mock( VfsFileChooserDialog.class );
    Combo combo = mock( Combo.class );
    Tree tree = mock( Tree.class );
    VfsBrowser vfsBrowser = mock( VfsBrowser.class );
    doNothing().when( combo ).setText( anyString() );
    vfsFileChooserDialog.openFileCombo = combo;
    doNothing().when( tree ).removeAll();
    vfsBrowser.fileSystemTree = tree;
    vfsFileChooserDialog.vfsBrowser = vfsBrowser;
    doCallRealMethod().when( vfsFileChooserDialog ).setRootFile( null );
    doCallRealMethod().when( vfsFileChooserDialog ).setInitialFile( null );
    hadoopVfsFileChooserDialog.vfsFileChooserDialog = vfsFileChooserDialog;

    NamedClusterWidgetImplExtend namedClusterWidgetImpl = mock( NamedClusterWidgetImplExtend.class );
    Combo namedClusterCombo = mock( Combo.class );
    when( namedClusterCombo.getSelectionIndex() ).thenReturn( SELECTED_INDEX );
    doNothing().when( namedClusterCombo ).removeAll();
    doNothing().when( namedClusterCombo ).setItems( any() );
    doNothing().when( namedClusterCombo ).select( SELECTED_INDEX );
    when( namedClusterWidgetImpl.getNameClusterCombo() ).thenReturn( namedClusterCombo );
    when( namedClusterWidgetImpl.getNamedClusterNames() ).thenReturn( NAMED_CLUSTER_NAMES );
    doCallRealMethod().when( namedClusterWidgetImpl ).initiate();
    doNothing().when( namedClusterWidgetImpl ).setSelectedNamedCluster( anyString() );
    when( hadoopVfsFileChooserDialog.getNamedClusterWidget() ).thenReturn( namedClusterWidgetImpl );

    hadoopVfsFileChooserDialog.activate();
    verify( namedClusterWidgetImpl, times( 1 ) ).initiate();
  }

  private class NamedClusterWidgetImplExtend extends NamedClusterWidgetImpl {
    public NamedClusterWidgetImplExtend( Composite parent, boolean showLabel, NamedClusterService namedClusterService, RuntimeTestActionService runtimeTestActionService, RuntimeTester clusterTester ) {
      super( parent, showLabel, namedClusterService, runtimeTestActionService, clusterTester );
    }

    /*Overriding for visibility change only*/
    @Override
    public String[] getNamedClusterNames() {
      return super.getNamedClusterNames();
    }
  }

}


text:
import Lseed.Data
import Lseed.Data.Functions
import Lseed.Grammar.Parse
import Lseed.Constants
import Lseed.Mainloop
import qualified Data.Map as M
import Control.Monad
import Debug.Trace
import System.Environment
import System.Time
import System.Random
import Text.Printf

parseFile filename = do
	content <- readFile filename
	let result = parseGrammar filename content
	return $ either (error.show) id result

readArgs doit = do
	args <- getArgs
	if null args
	  then	do
		putStrLn "L-Seed Demo application."
		putStrLn "Please pass L-Seed files on the command line."
	  else	do
		genomes <- mapM parseFile args
		doit (spread genomes)
  where	spread gs = zipWith (\g p ->
  		Planted ((fromIntegral p + 0.5) / l)
		        p
			(show p)
			g
			inititalPlant
		) gs [0..]
	  where l = fromIntegral (length gs)

scoringObs = nullObserver {
	obFinished = \garden -> do
		forM_ garden $ \planted -> do
			printf "Plant from %s (%d) at %.4f: Total size %.4f\n"
				(plantOwnerName planted)
				(plantOwner planted)
				(plantPosition planted)
				(plantLength (phenotype planted))
		let owernerscore = foldr (\p -> M.insertWith (+) (plantOwner p, plantOwnerName p)(plantLength (phenotype p))) M.empty garden
		forM_ (M.toList owernerscore) $ \((o,n),s) ->
			printf "Sum for %s (%d): %.4f\n" n o s
	}

main = readArgs $ \garden -> do
	lseedMainLoop False scoringObs (constGardenSource garden) 30


text:
class Mx < ActiveRecord::Base
	validates :question, presence: true
	validates :priority, presence: true, numericality: :only_integer
	validates :to_name, presence: true
end


text:
<?php

namespace TransformCore\PHE\ExporterBundle\Model\Helper;

use TransformCore\PHE\HayApi\PersistenceBundle\Entity\Questions\Smoking;

/**
 * Class SmokingHelper
 * @package TransformCore\PHE\ExporterBundle\Model\Helper
 */
class SmokingHelper
{
    /**
     * @param Smoking $smoking
     * @return array
     */
    public static function extractSmoking(Smoking $smoking)
    {
        return array(
            "smokingDoYouSmoke"        => $smoking->getDoYouSmoke(),
            "smokingCompleted"         => (true === $smoking->isCompleted()) ? "true" : "false",
            "smokingRag"               => $smoking->getRagScore()['rag'],
        );
    }
}


text:
<!DOCTYPE html>

		<title>Terms and Condition</title>
		<link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700italic,700' rel='stylesheet' type='text/css'>

Terms and Conditions

  					Paste Directory

      					Møllendalsveien 52B H0714
      					5009
      					Bergen, Norway

					alex@delexious.com

By using our service you are agreeing to the terms and conditions below, please read them carefully. These terms are produced to establish a set of guidelines and to protect our service and your privacy from abuse.

Copyright

The Software is owned by Delexious Software and is protected by copyright laws and by international treaty provisions. You should therefore treat the Software like any other copyrighted material (such as for example, books or musical recordings). Among other things, copyright laws prohibit You from making derivative works of the Software. You may, however, make copies of the Software solely for Your individual and personal use on multiple computers, provided that You include all copyright and proprietary rights notices on any copies.

Other Restrictions

You may not modify, reverse-engineer, decompile, or disassemble the Software for any purpose whatsoever.

You may not claim that the Software is yours, and you may not use the name Paste Directory (or variations thereof)  to endorse or promote products derived from the Software without prior written permission.

You may not use this software to store illegal information such as illegally procured documents, passwords, payment information, or other.

Privacy

Among the types of Personal Data that this Application collects, by itself or through third parties, there are: Email, First Name, Cookie and Usage Data.

					Other Personal Data collected may be described in other sections of this privacy policy or by dedicated explanation text contextually with the Data collection.

					The Personal Data may be freely provided by the User, or collected automatically when using this Application.

					Any use of Cookies - or of other tracking tools - by this Application or by the owners of third party services used by this Application, unless stated otherwise, serves to identify Users and remember their preferences, for the sole purpose of providing the service required by the User.

					Failure to provide certain Personal Data may make it impossible for this Application to provide its services.

The User assumes responsibility for the Personal Data of third parties published or shared through this Application and declares to have the right to communicate or broadcast them, thus relieving the Data Controller of all responsibility.

Methods of processing

					Paste Directory processes the Data of Users in a proper manner and shall take appropriate security measures to prevent unauthorized access, disclosure, modification or unauthorized destruction of the Data.

					The Data processing is carried out using computers and/or IT enabled tools, following organizational procedures and modes strictly related to the purposes indicated. In addition to Paste Directory, in some cases, the Data may be accessible to certain types of persons in charge, involved with the operation of the site (administration, legal, system administration) or external parties (such as third party technical service providers, mail carriers, hosting providers, IT companies, communications agencies) appointed, if necessary, as Data Processors by the Owner. The updated list of these parties may be requested from Paste Directory at any time.

Usage

The Data is kept for the time necessary to provide the service requested by the User, or stated by the purposes outlined in this document, and the User can always request that Paste Directory suspend or remove the data.

The Data concerning the User is collected to allow the Application to provide its services, as well as for contacting the user if necessary and providing statistics and analysis.

The Personal Data used for each purpose is outlined in the specific sections of this document.

Legal Action

					The User's Personal Data may be used for legal purposes by the Data Controller, in Court or in the stages leading to possible legal action arising from improper use of this Application or the related services.

					The User is aware of the fact that Paste Directory may be required to reveal personal data upon request of public authorities.

Additional information about User's Personal Data

In addition to the information contained in this privacy policy, this Application may provide the User with additional and contextual information concerning particular services or the collection and processing of Personal Data upon request.

System Logs and Maintenance

For operation and maintenance purposes, this Application and any third party services may collect files that record interaction with this Application (System Logs) or use for this purpose other Personal Data (such as IP Address).

Information not contained in this policy

More details concerning the collection or processing of Personal Data may be requested from Paste Directory at any time. Please see the contact information at the beginning of this document.

The rights of Users

Users have the right, at any time, to know whether their Personal Data has been stored and can consult Paste Directory to learn about their contents and origin, to verify their accuracy or to ask for them to be supplemented, cancelled, updated or corrected, or for their transformation into anonymous format or to block any data held in violation of the law, as well as to oppose their treatment for any and all legitimate reasons. Requests should be sent to Paste Directory at the contact information set out above.

This Application supports "Do Not Track" requests.

This application adheres to requests by the user to avoid using web technologies to store or use personal or identifiable data and/or information. The application may however employ third party services which does not. To determine whether any of the third party services it uses honor the "Do Not Track" requests, please read their privacy policies.

Changes to this privacy policy

Paste Directory reserves the right to make changes to this privacy policy at any time by giving notice to its Users on this page. It is strongly recommended to check this page often, referring to the date of the last modification listed at the bottom. If a User objects to any of the changes to the Policy, the User must cease using this Application and can request that the Paste Directory erase the Personal Data. Unless stated otherwise, the then-current privacy policy applies to all Personal Data Paste Directory has about Users.

Warranty and limitation of liability

In no event shall Paste Directory or anyone else involved in the creation, production, marketing, distribution or delivery of the service, be liable for any damages whatsoever; including, without limitation, damages for loss of data, service interruption, loss of information, or for other monetary loss, arising out of the use of the service  or the inability to use the service, even if you have been notified of the possibility of such damages.

In no event shall Paste Directory be liable for any special, indirect, or consequential damages, or for any damages whatsoever, whether in a  contract action, negligence, or other tort action, or other claim, or action, arising out of, or in connection with, the use or performance of the service and other information provided to you by us, or in the provision of, or failure to provide, such information.

Some states in the United States and some countries prohibit the limitation of liability, therefore the use of this software or service in these areas is restricted and we take no legal responsibility nor condone your actions if you choose to disregard this warning.

Termination

You may terminate this Agreement at any time. Paste Directory may immediately terminate this License Agreement if You breach any representation, warranty, agreement or obligation contained or referred to in this License Agreement. Upon termination, You must dispose of the Software and all copies or versions of the Software by destroying the Software.


text:
INDICATOR {{ vm.indicator }} *

            SHARE LEVEL

            UNKNOWN
            GREEN
            YELLOW
            RED

    <button ng-disabled="vm.origShareLevel == vm.share_level" class="btn btn-primary btn-sm" type="button" ng-click="vm.save()">OK</button>
    <button class="btn btn-warning btn-sm" type="button" ng-click="vm.cancel()">CANCEL</button>


text:
package com.linecorp.bot.client;

import static org.assertj.core.api.Assertions.assertThat;

import java.nio.charset.StandardCharsets;

import org.junit.Test;
import org.springframework.util.Base64Utils;

public class LineSignatureValidatorTest {
    private static final String channelSecret = "SECRET";

    @Test
    public void validateSignature() throws Exception {
        LineSignatureValidator lineSignatureValidator = new LineSignatureValidator(
                channelSecret.getBytes(StandardCharsets.UTF_8));

        String httpRequestBody = "{}";
        assertThat(lineSignatureValidator
                           .validateSignature(httpRequestBody.getBytes(StandardCharsets.UTF_8),
                                              "3q8QXTAGaey18yL8FWTqdVlbMr6hcuNvM4tefa0o9nA="))
                .isTrue();
        assertThat(lineSignatureValidator
                           .validateSignature(httpRequestBody.getBytes(StandardCharsets.UTF_8),
                                              "596359635963"))
                .isFalse();
    }

    @Test
    public void generateSignature() throws Exception {
        LineSignatureValidator lineSignatureValidator = new LineSignatureValidator(
                channelSecret.getBytes(StandardCharsets.UTF_8));

        String httpRequestBody = "{}";
        byte[] headerSignature = lineSignatureValidator
                .generateSignature(httpRequestBody.getBytes(StandardCharsets.UTF_8));

        assertThat(Base64Utils.encodeToString(headerSignature))
                .isEqualTo("3q8QXTAGaey18yL8FWTqdVlbMr6hcuNvM4tefa0o9nA=");
    }

}


text:
package org.springframework.http.converter;

import java.io.IOException;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.util.StreamUtils;

/**
 * Implementation of {@link HttpMessageConverter} that can read and write byte arrays.
 *
 *
By default, this converter supports all media types (*/*), and
 * writes with a {@code Content-Type} of {@code application/octet-stream}. This can be
 * overridden by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property.
 *
 * @author Arjen Poutsma
 * @author Juergen Hoeller
 * @since 3.0
 */
public class ByteArrayHttpMessageConverter extends AbstractHttpMessageConverter<byte[]> {

	/**
	 * Create a new instance of the {@code ByteArrayHttpMessageConverter}.
	 */
	public ByteArrayHttpMessageConverter() {
		super(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL);
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return byte[].class == clazz;
	}

	@Override
	public byte[] readInternal(Class<? extends byte[]> clazz, HttpInputMessage inputMessage) throws IOException {
		return inputMessage.getBody().readAllBytes();
	}

	@Override
	protected Long getContentLength(byte[] bytes, @Nullable MediaType contentType) {
		return (long) bytes.length;
	}

	@Override
	protected void writeInternal(byte[] bytes, HttpOutputMessage outputMessage) throws IOException {
		StreamUtils.copy(bytes, outputMessage.getBody());
	}

}


text:
/*
 This code is licensed under a Simplified BSD License. See LICENSE for details.
 If you find this code useful, please consider downloading a copy of the app that spawned it ( http://itunes.com/apps/VERVM ) and leaving a review.

 My thanks,
 -Joshua Emmons
 @jemmons

 */

#import <QuartzCore/QuartzCore.h>
@interface VCPageLayer : CALayer {
	NSString *imageName;
	NSString *path;
}
@property(nonatomic,copy)NSString *imageName;
@end


text:
package org.musicpd.android.tools;

import org.a0z.mpd.MPD;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.preference.PreferenceManager;

import org.musicpd.android.helpers.MPDAsyncHelper;

public class SettingsHelper implements OnSharedPreferenceChangeListener {
	private static final int DEFAULT_MPD_PORT = 6600;
	private static final int DEFAULT_STREAMING_PORT = 8000;

	private WifiManager mWifiManager;
	private SharedPreferences settings;
	private MPDAsyncHelper oMPDAsyncHelper;

	public SettingsHelper(ContextWrapper parent, MPDAsyncHelper MPDAsyncHelper) {
		// Get Settings and register ourself for updates
		settings = PreferenceManager.getDefaultSharedPreferences(parent);// getSharedPreferences("org.pmix", MODE_PRIVATE);
		settings.registerOnSharedPreferenceChangeListener(this);

		// get reference on WiFi service
		mWifiManager = (WifiManager) parent.getSystemService(Context.WIFI_SERVICE);

		oMPDAsyncHelper = MPDAsyncHelper;
	}

	public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
		updateSettings();
	}

	public boolean warningShown() {
		return getBooleanSetting("newWarningShown");
	}

	public void setHostname(String hostname, int port) {
		String wifiSSID = getCurrentSSID();
		settings
			.edit()
			.putString(getStringWithSSID("hostname", wifiSSID), hostname)
			.putString(getStringWithSSID("port", wifiSSID), "" + port)
			.commit();
	}

	public boolean updateSettings() {

		MPD.setSortByTrackNumber(settings.getBoolean("albumTrackSort", MPD.sortByTrackNumber()));
		MPD.setSortAlbumsByYear(settings.getBoolean("sortAlbumsByYear", MPD.sortAlbumsByYear()));
		MPD.setUseAlbumArtist(settings.getBoolean("albumartist", MPD.useAlbumArtist()));
		MPD.setShowAlbumTrackCount(settings.getBoolean("showAlbumTrackCount", MPD.showAlbumTrackCount()));
		// MPD.setShowArtistAlbumCount(settings.getBoolean("showArtistAlbumCount", MPD.showArtistAlbumCount()));

		return updateConnectionSettings();
	}

	public boolean updateConnectionSettings(){
		return updateConnectionSettings(getCurrentConfiguredSSID());
	}

	private boolean updateConnectionSettings(String wifiSSID) {
		if (getStringSetting(getStringWithSSID("hostname", wifiSSID)) == null)
			return false;

		oMPDAsyncHelper.getConnectionSettings().sServer				= getStringSetting(getStringWithSSID("hostname", wifiSSID));
		oMPDAsyncHelper.getConnectionSettings().iPort				= getIntegerSetting(getStringWithSSID("port", wifiSSID), DEFAULT_MPD_PORT);
		oMPDAsyncHelper.getConnectionSettings().sPassword			= getStringSetting(getStringWithSSID("password", wifiSSID));
		oMPDAsyncHelper.getConnectionSettings().sServerStreaming	= getStringSetting(getStringWithSSID("hostnameStreaming", wifiSSID));
		oMPDAsyncHelper.getConnectionSettings().iPortStreaming		= getIntegerSetting(getStringWithSSID("portStreaming", wifiSSID), DEFAULT_STREAMING_PORT);
		oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming = getStringSetting(getStringWithSSID("suffixStreaming", wifiSSID));
		if (oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming == null)
			oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming = "";

		return true;
	}

	private int getIntegerSetting(String name, int defaultValue) {
		try {
			return Integer.parseInt(settings.getString(name, Integer.toString(defaultValue)).trim());
		} catch (NumberFormatException e) {
			return DEFAULT_MPD_PORT;
		}
	}

	private String getStringSetting(String name) {
		String value = settings.getString(name, "").trim();

		if (value.equals(""))
			return null;
		else
			return value;
	}

	private boolean getBooleanSetting(String name) {
		return settings.getBoolean(name, false);
	}

	private String getCurrentConfiguredSSID() {
		String wifiSSID = getCurrentSSID();
		return
			getStringSetting(getStringWithSSID("hostname",  wifiSSID)) == null ? null :
			wifiSSID == null || wifiSSID.trim().equals("") ? null :
			wifiSSID;
	}

	private String getCurrentSSID() {
		WifiInfo info = mWifiManager.getConnectionInfo();
		final String ssid = info.getSSID();
		return ssid == null ? null : ssid.replace("\"", "");
	}

	private String getStringWithSSID(String param, String wifiSSID) {
		if (wifiSSID == null)
			return param;
		else
			return wifiSSID + param;
	}
}


text:
<?php

namespace App\Ui\Silex\Web\Controller\Api\Photos;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request as SilexRequest;
use Symfony\Component\HttpFoundation\JsonResponse as SilexResponse;
use Booothy\Photo\Application\Service\GetResource\Request;
use Booothy\Photo\Domain\Repository\Exception\NonExistingResource;

final class GetResource
{
    const USE_CASE = 'photo.application.service.get_resource';

    public function __invoke(SilexRequest $silex_request, Application $app)
    {
        $use_case = $app['container']->get(self::USE_CASE);
        $request = new Request($silex_request->get('id'));
        $response = $this->getResponse($use_case, $request);

        return new SilexResponse($response['content'], $response['status']);
    }

    private function getResponse($use_case, $request)
    {
        try {
            return [
                'content' => $use_case($request),
                'status' => 200,
            ];
        } catch (NonExistingResource $e) {
            return [
                'content' => ['error' => 'Non existing boooth ' . $request->id],
                'status' => 404,
            ];
        }
    }
}


text:
/**
 * Team
 *
 * The folks who make it happen. The team putting this Walk on.
 */
import { createElement as ce } from 'react';
import t from 'es2015-i18n-tag';
import { Form, Button, Icon } from 'antd';

import Leader from './Leader';
import Organizer from './Organizer';
import Voice from './Voice';
import Volunteer from './Volunteer';

// Map the types set in the store to their component
const typeMap = {
  leader: Leader,
  organizer: Organizer,
  voice: Voice,
  volunteer: Volunteer,
};

const buttonStyle = {
  type: 'dashed',
  style: {
    whiteSpace: 'normal',
    marginBottom: '5px',
    textAlign: 'left',
    display: 'block',
    width: '100%',
  },
};

const Team = ({ id, name, team, handlers }) => ce('section', { id, className: 'Lead__Option' },
  ce('h1', {}, name),
  team
  .filter(({ type }) => typeMap[type])
  .map((member, i) => ce(typeMap[member.type], {
    key: `${member.type}${i}`,
    member,
    handler: handlers.teamMember(member),
  })),
  ce(Form.Item, { label: t`Add members to your team` },
    ce(Button, { ...buttonStyle, onClick: handlers.teamAddLeader },
      ce('h5', {}, ce('i', { className: 'fa fa-bullhorn' }), '  ', t`Walk Leader`),
      ce('p', {}, t`A person presenting information, telling stories, and fostering discussion during the Jane's Walk.`)
    ),
    ce(Button, { ...buttonStyle, onClick: handlers.teamAddOrganizer },
      ce('h5', {}, ce('i', { className: 'fa fa-handshake-o' }), '  ', t`Organizer`),
      ce('p', {}, t`A person responsible for outreach to new and returning Walk Leaders and Community Voices.`)
    ),
    ce(Button, { ...buttonStyle, onClick: handlers.teamAddVolunteer },
      ce('h5', {}, ce(Icon, { type: 'pushpin-o' }), '  ', t`Volunteers`),
      ce('p', {}, t`People who are helping out on your Walk. They could be there to help take photos, set up and coordinate the Walk, or share stories and/or personal experiences.`)
    )
  )
);

export default Team;


text:
package model.google

import akka.japi.Option.Some
import com.byteslounge.slickrepo.meta.Entity

case class GoogleAuth(id: Option[String], displayName: String, userId: Int) extends Entity[GoogleAuth, String] {

  override def withId(id: String): GoogleAuth = this.copy(id = Some(id))
}


text:
package com.amazonaws.services.route53.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.route53.model.*;
import com.amazonaws.transform.Marshaller;

import com.amazonaws.util.StringUtils;

/**
 * ListQueryLoggingConfigsRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListQueryLoggingConfigsRequestMarshaller implements Marshaller<Request<ListQueryLoggingConfigsRequest>, ListQueryLoggingConfigsRequest> {

    public Request<ListQueryLoggingConfigsRequest> marshall(ListQueryLoggingConfigsRequest listQueryLoggingConfigsRequest) {

        if (listQueryLoggingConfigsRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<ListQueryLoggingConfigsRequest> request = new DefaultRequest<ListQueryLoggingConfigsRequest>(listQueryLoggingConfigsRequest, "AmazonRoute53");

        request.setHttpMethod(HttpMethodName.GET);

        String uriResourcePath = "/2013-04-01/queryloggingconfig";

        request.setResourcePath(uriResourcePath);

        if (listQueryLoggingConfigsRequest.getHostedZoneId() != null) {
            request.addParameter("hostedzoneid", StringUtils.fromString(listQueryLoggingConfigsRequest.getHostedZoneId()));
        }

        if (listQueryLoggingConfigsRequest.getNextToken() != null) {
            request.addParameter("nexttoken", StringUtils.fromString(listQueryLoggingConfigsRequest.getNextToken()));
        }

        if (listQueryLoggingConfigsRequest.getMaxResults() != null) {
            request.addParameter("maxresults", StringUtils.fromString(listQueryLoggingConfigsRequest.getMaxResults()));
        }

        return request;
    }

}


text:
using RestSharp;
using RestSharp.Authenticators;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;

namespace ScatterGatherLoadTest.Services
{
    public class SingleRequestService : IService<LoadTestRequest, LoadTestResponse>
    {
        public async Task<LoadTestResponse> Execute(LoadTestRequest request)
        {
            var response = new LoadTestResponse();

            var stopwatch = new Stopwatch();

            try
            {
                response.Start = DateTime.UtcNow;
                stopwatch.Start();
                response.Success = await MakeRequest(request) == HttpStatusCode.OK;
            }
            catch (Exception)
            {
                response.Success = false;
            }
            finally
            {
                stopwatch.Stop();
                response.Milliseconds = stopwatch.ElapsedMilliseconds;
                response.End = DateTime.UtcNow;
            }

            return response;
        }

        private static Task<HttpStatusCode> MakeRequest(LoadTestRequest request)
        {
            var client = new RestClient(request.Domain);
            if (request.Authentication.Enabled)
            {
                client.Authenticator = new HttpBasicAuthenticator(request.Authentication.Username, request.Authentication.Password);
            }

            var restRequest = new RestRequest(request.Resource, request.Method);

            foreach (KeyValuePair<string, string> parameter in request.Parameters)
            {
                restRequest.AddParameter(parameter.Key, parameter.Value);
            }

            foreach (KeyValuePair<string, string> header in request.Headers)
            {
                restRequest.AddHeader(header.Key, header.Value);
            }

            var taskCompletionSource = new TaskCompletionSource<HttpStatusCode>();
            client.ExecuteAsync(restRequest, (response) =>
            {
                taskCompletionSource.SetResult(response.StatusCode);
            });
            return taskCompletionSource.Task;
        }
    }
}


text:
package org.apache.calcite.rex;

import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.util.Litmus;

import java.util.List;

/**
 * Visitor which checks the validity of a {@link RexNode} expression.
 *
 *
There are two modes of operation:
 *
 *

 *
Usefail=true to throw an {@link AssertionError} as soon as
 * an invalid node is detected:
 *
 *
RexNode node;

 * RelDataType rowType;

 * assert new RexChecker(rowType, true).isValid(node);

 *
 * This mode requires that assertions are enabled.

 *
 *
Use fail=false to test for validity without throwing an
 * error.
 *
 *
RexNode node;

 * RelDataType rowType;

 * RexChecker checker = new RexChecker(rowType, false);

 * node.accept(checker);

 * if (!checker.valid) {

 *    ...

 * }

 *

 *

 *
 * @see RexNode
 */
public class RexChecker extends RexVisitorImpl<Boolean> {
  //~ Instance fields --------------------------------------------------------

  protected final RelNode.Context context;
  protected final Litmus litmus;
  protected final List<RelDataType> inputTypeList;
  protected int failCount;

  //~ Constructors -----------------------------------------------------------

  /**
   * Creates a RexChecker with a given input row type.
   *
   *
If fail is true, the checker will throw an
   * {@link AssertionError} if an invalid node is found and assertions are
   * enabled.
   *
   *
Otherwise, each method returns whether its part of the tree is valid.
   *
   * @param inputRowType Input row type
   * @param context Context of the enclosing {@link RelNode}, or null
   * @param litmus What to do if an invalid node is detected
   */
  public RexChecker(final RelDataType inputRowType, RelNode.Context context,
      Litmus litmus) {
    this(RelOptUtil.getFieldTypeList(inputRowType), context, litmus);
  }

  /**
   * Creates a RexChecker with a given set of input fields.
   *
   *
If fail is true, the checker will throw an
   * {@link AssertionError} if an invalid node is found and assertions are
   * enabled.
   *
   *
Otherwise, each method returns whether its part of the tree is valid.
   *
   * @param inputTypeList Input row type
   * @param context Context of the enclosing {@link RelNode}, or null
   * @param litmus What to do if an error is detected
   */
  public RexChecker(List<RelDataType> inputTypeList, RelNode.Context context,
      Litmus litmus) {
    super(true);
    this.inputTypeList = inputTypeList;
    this.context = context;
    this.litmus = litmus;
  }

  //~ Methods ----------------------------------------------------------------

  /**
   * Returns the number of failures encountered.
   *
   * @return Number of failures
   */
  public int getFailureCount() {
    return failCount;
  }

  @Override public Boolean visitInputRef(RexInputRef ref) {
    final int index = ref.getIndex();
    if ((index < 0) || (index >= inputTypeList.size())) {
      ++failCount;
      return litmus.fail("RexInputRef index {} out of range 0..{}",
          index, inputTypeList.size() - 1);
    }
    if (!ref.getType().isStruct()
        && !RelOptUtil.eq("ref", ref.getType(), "input",
            inputTypeList.get(index), litmus)) {
      ++failCount;
      return litmus.fail(null);
    }
    return litmus.succeed();
  }

  @Override public Boolean visitLocalRef(RexLocalRef ref) {
    ++failCount;
    return litmus.fail("RexLocalRef illegal outside program");
  }

  @Override public Boolean visitCall(RexCall call) {
    for (RexNode operand : call.getOperands()) {
      Boolean valid = operand.accept(this);
      if (valid != null && !valid) {
        return litmus.fail(null);
      }
    }
    return litmus.succeed();
  }

  @Override public Boolean visitFieldAccess(RexFieldAccess fieldAccess) {
    super.visitFieldAccess(fieldAccess);
    final RelDataType refType = fieldAccess.getReferenceExpr().getType();
    assert refType.isStruct();
    final RelDataTypeField field = fieldAccess.getField();
    final int index = field.getIndex();
    if ((index < 0) || (index > refType.getFieldList().size())) {
      ++failCount;
      return litmus.fail(null);
    }
    final RelDataTypeField typeField = refType.getFieldList().get(index);
    if (!RelOptUtil.eq(
        "type1",
        typeField.getType(),
        "type2",
        fieldAccess.getType(), litmus)) {
      ++failCount;
      return litmus.fail(null);
    }
    return litmus.succeed();
  }

  @Override public Boolean visitCorrelVariable(RexCorrelVariable v) {
    if (context != null
        && !context.correlationIds().contains(v.id)) {
      ++failCount;
      return litmus.fail("correlation id {} not found in correlation list {}",
          v, context.correlationIds());
    }
    return litmus.succeed();
  }

  /**
   * Returns whether an expression is valid.
   */
  public final boolean isValid(RexNode expr) {
    return expr.accept(this);
  }
}

// End RexChecker.java


text:
id: register
title: /api/client/register
---

> In order to access the client API endpoints you need to identify yourself. Unless you're using the `none` authentication method, you'll need to [create a CLIENT token](/how-to/how-to-create-api-tokens) and add an Authorization header using the token.

### Client registration {#client-registration}

`POST: http://unleash.host.com/api/client/register`

Registers a client instance with the unleash server. The client should send all fields specified.

```json
{
  "appName": "appName",
  "instanceId": "instanceId",
  "sdkVersion": "unleash-client-java:2.2.0",
  "strategies": ["default", "some-strategy-1"],
  "started": "2016-11-03T07:16:43.572Z",
  "interval": 10000
}
```

**Fields:**

- **appName** - Name of the application seen by unleash-server
- **instanceId** - Instance id for this application (typically hostname, podId or similar)
- **sdkVersion** - Optional field that describes the sdk version (name:version)
- **strategies** - List of strategies implemented by this application
- **started** - When this client started. Should be reported as [ISO8601](https://en.wikipedia.org/wiki/ISO_8601) time.
- **interval** - At which interval, in milliseconds, will this client be expected to send metrics


text:
local pels = ProbablyEngine.locale.set

ProbablyEngine.locale.new('frFR')

-- Buttons
pels('toggle', 'Bouton bascule')
pels('toggle_tooltip', 'Active ou désactive temporairement la rotation.')
pels('cooldowns', 'Cooldowns')
pels('cooldowns_tooltip', 'Active l\39utilisation des cooldowns à long temps de recharge.')
pels('multitarget', 'Multi-Cibles')
pels('multitarget_tooltip', 'Active l\39utilisation des techniques multi-cibles.')
pels('interrupt', 'Interruption')
pels('interrupt_tooltip', 'Active l\39utilisation des techniques d\39interruption.')
pels('drag_to_position', 'Faire glisser à la position')

-- Buttons Menu
pels('rtn_default', 'Rotation par défaut')
pels('rtn_custom', 'Rotation personnalisée')
pels('rtn_switch', 'Rotation active changée pour: ')
pels('rtn_nocustom', 'Aucune rotation personnalisée chargée.')

-- General
pels('left_click', 'Bouton gauche')
pels('right_click', 'Bouton droit')
pels('drag', 'Faire glisser')
pels('rotation_loaded', 'Rotation chargée!')

-- Minimap
pels('open_config', 'Ouvrir la configuration')
pels('unlock_buttons', 'Débloquer les boutons')
pels('move_minimap', 'Bouger le bouton de la minimap')

-- Combat Tracker
pels('est', 'Est.') -- Estimated
pels('na', 'n/d') -- not/available / non disponible
pels('k', 'k') -- Thousands postfix
pels('all_units', 'Toutes Unités')
pels('combat_tracker', 'Traqueur de combat')
pels('ttd', 'DAD') -- Time To Death shorthand / Délais Avant Décès
pels('hpr', 'PVR') -- Health Points Remaining shorthand / Points de Vie Restant

-- commands
pels('running_version', 'Vous utilisez la version')
pels('build', 'version')
pels('help_cycle', 'Démarrer manuellement la rotation.')
pels('help_toggle', 'Active/Désactive l\39addon.')
pels('help_ct', 'Affiche/Cache le traqueur de combat.')
pels('help_al', 'Affiche/Cache la trace des actions.')
pels('help_version', 'Affiche le numéro de version.')
pels('help_help', 'Affiche ce message.')
pels('help_turbo', 'Active/Désactive le mode turbo.')
pels('unknown_type', 'Commande inconnue.')

pels('turbo_enable', 'Mode Turbo activé!')
pels('turbo_disable', 'Mode Turbo désactivé!')

-- classes
pels('arcane_mage', 'Mage Arcane')
pels('fire_mage', 'Mage Feu')
pels('frost_mage', 'Mage Givre')
pels('holy_paladin', 'Paladin Sacré')
pels('protection_paladin', 'Paladin Protection')
pels('retribution_paladin', 'Paladin Vindicte')
pels('arms_warrior', 'Guerrier Armes')
pels('furry_warrior', 'Guerrier Fureur')
pels('protection_warrior', 'Guerrier Protection')
pels('balance_druid', 'Druide Équilibre')
pels('feral_combat_druid', 'Druide Farouche')
pels('guardian_druid', 'Druide Gardien')
pels('restoration_druid', 'Druide Restauration')
pels('blood_death_knight', 'Chevalier de la mort Sang')
pels('frost_death_knight', 'Chevalier de la mort Givre')
pels('unholy_death_knight', 'Chevalier de la mort Impie')
pels('beast_mastery_hunter', 'Chasseur Maîtrise des bêtes')
pels('marksmanship_hunter', 'Chasseur Précision')
pels('survival_hunter', 'Chasseur Survie')
pels('discipline_priest', 'Prêtre Discipline')
pels('holy_priest', 'Prêtre Sacré')
pels('shadow_priest', 'Prêtre Ombre')
pels('assassination_rogue', 'Voleur Assassinat')
pels('combat_rogue', 'Voleur Combat')
pels('subtlety_rogue', 'Voleur Finesse')
pels('elemental_shaman', 'Chaman Élémentaire')
pels('enhancement_shaman', 'Chaman Amélioration')
pels('restoration_shaman', 'Chaman Restauration')
pels('affliction_warlock', 'Démoniste Affliction')
pels('demonology_warlock', 'Démoniste Démonologie')
pels('destruction_warlock', 'Démoniste Destruction')
pels('brewmaster_monk', 'Moine Maître brasseur')
pels('windwalker_monk', 'Moine Marche-vent')
pels('mistweaver_monk', 'Moine Tisse-brume')


text:
require 'thread'

require "bundler/parallel_workers/worker"

module Bundler
  module ParallelWorkers
    autoload :ThreadWorker, "bundler/parallel_workers/thread_worker"

    def self.worker_pool(size, job)
      ThreadWorker.new(size, job)
    end
  end
end


text:
package org.javaswift.joss.command.shared.account;

import org.javaswift.joss.command.shared.core.Command;
import org.javaswift.joss.information.AccountInformation;

public interface AccountInformationCommand extends Command<AccountInformation> {
}


text:
/**
 *
 */
package cn.remex.web.service;

import cn.remex.RemexConstants;
import cn.remex.RemexConstants.UserType;

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

import static cn.remex.RemexConstants.UserType.ADMIN;

/**
 * @author liuhengyang
 * @date 2014-12-9 上午11:42:49
 * @version 版本号码
 * @TODO 描述
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD,ElementType.TYPE})
public @interface BusinessService {
    String name() default "";
    ServiceType type() default ServiceType.normal;
	boolean withMultiPart() default false;
    boolean requestBody() default false;
    String bodyParamName() default "";
    String desc() default "";
    boolean needAuth() default true;
    UserType authLevel() default ADMIN;

	enum ServiceType {
		normal,AsyncService
	}
}


text:
package pl.themolka.arcade.environment;

import org.bukkit.event.Listener;
import pl.themolka.arcade.ArcadePlugin;
import pl.themolka.arcade.dom.Node;

public class Environment extends SimpleEnvironmentListener implements Listener {
    public static final EnvironmentType DEFAULT_TYPE = EnvironmentType.DEVELOPMENT;

    private ArcadePlugin plugin;

    private boolean loaded = false;
    private final Node options;
    private final EnvironmentType type;

    public Environment(Node options, EnvironmentType type) {
        this.options = options;
        this.type = type;
    }

    public final void initialize(ArcadePlugin plugin) {
        if (this.isLoaded()) {
            return;
        }

        this.loaded = true;
        this.plugin = plugin;

        plugin.getLogger().info("This server is starting in the " + this.type.toString() + " mode...");

        plugin.registerCommandObject(this);
        plugin.registerListenerObject(this);
    }

    public Node getOptions() {
        return this.options;
    }

    public ArcadePlugin getPlugin() {
        return this.plugin;
    }

    public EnvironmentType getType() {
        return this.type;
    }

    public boolean isLoaded() {
        return this.loaded;
    }
}


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

The latest release of this document can be found
[here](http://releases.k8s.io/release-1.3/docs/proposals/selinux.md).

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

## Abstract

A proposal for enabling containers in a pod to share volumes using a pod level SELinux context.

## Motivation

Many users have a requirement to run pods on systems that have SELinux enabled.  Volume plugin
authors should not have to explicitly account for SELinux except for volume types that require
special handling of the SELinux context during setup.

Currently, each container in a pod has an SELinux context.  This is not an ideal factoring for
sharing resources using SELinux.

We propose a pod-level SELinux context and a mechanism to support SELinux labeling of volumes in a
generic way.

Goals of this design:

1.  Describe the problems with a container SELinux context
2.  Articulate a design for generic SELinux support for volumes using a pod level SELinux context
    which is backward compatible with the v1.0.0 API

## Constraints and Assumptions

1.  We will not support securing containers within a pod from one another
2.  Volume plugins should not have to handle setting SELinux context on volumes
3.  We will not deal with shared storage

## Current State Overview

### Docker

Docker uses a base SELinux context and calculates a unique MCS label per container.  The SELinux
context of a container can be overridden with the `SecurityOpt` api that allows setting the different
parts of the SELinux context individually.

Docker has functionality to relabel bind-mounts with a usable SElinux and supports two different
use-cases:

1.  The `:Z` bind-mount flag, which tells Docker to relabel a bind-mount with the container's
    SELinux context
2.  The `:z` bind-mount flag, which tells Docker to relabel a bind-mount with the container's
    SElinux context, but remove the MCS labels, making the volume shareable between containers

We should avoid using the `:z` flag, because it relaxes the SELinux context so that any container
(from an SELinux standpoint) can use the volume.

### rkt

rkt currently reads the base SELinux context to use from `/etc/selinux/*/contexts/lxc_contexts`
and allocates a unique MCS label per pod.

### Kubernetes

There is a [proposed change](https://github.com/kubernetes/kubernetes/pull/9844) to the
EmptyDir plugin that adds SELinux relabeling capabilities to that plugin, which is also carried as a
patch in [OpenShift](https://github.com/openshift/origin).  It is preferable to solve the problem
in general of handling SELinux in kubernetes to merging this PR.

A new `PodSecurityContext` type has been added that carries information about security attributes
that apply to the entire pod and that apply to all containers in a pod.  See:

1.  [Skeletal implementation](https://github.com/kubernetes/kubernetes/pull/13939)
1.  [Proposal for inlining container security fields](https://github.com/kubernetes/kubernetes/pull/12823)

## Use Cases

1.  As a cluster operator, I want to support securing pods from one another using SELinux when
    SELinux integration is enabled in the cluster
2.  As a user, I want volumes sharing to work correctly amongst containers in pods

#### SELinux context: pod- or container- level?

Currently, SELinux context is specifiable only at the container level.  This is an inconvenient
factoring for sharing volumes and other SELinux-secured resources between containers because there
is no way in SELinux to share resources between processes with different MCS labels except to
remove MCS labels from the shared resource.  This is a big security risk: _any container_ in the
system can work with a resource which has the same SELinux context as it and no MCS labels.  Since
we are also not interested in isolating containers in a pod from one another, the SELinux context
should be shared by all containers in a pod to facilitate isolation from the containers in other
pods and sharing resources amongst all the containers of a pod.

#### Volumes

Kubernetes volumes can be divided into two broad categories:

1.  Unshared storage:
    1.  Volumes created by the kubelet on the host directory: empty directory, git repo, secret,
        downward api.  All volumes in this category delegate to `EmptyDir` for their underlying
        storage.
    2.  Volumes based on network block devices: AWS EBS, iSCSI, RBD, etc, *when used exclusively
        by a single pod*.
2.  Shared storage:
    1.  `hostPath` is shared storage because it is necessarily used by a container and the host
    2.  Network file systems such as NFS, Glusterfs, Cephfs, etc.
    3.  Block device based volumes in `ReadOnlyMany` or `ReadWriteMany` modes are shared because
        they may be used simultaneously by multiple pods.

For unshared storage, SELinux handling for most volumes can be generalized into running a `chcon` operation on the volume directory after running the volume plugin's `Setup` function.  For these
volumes, the Kubelet can perform the `chcon` operation and keep SELinux concerns out of the volume
plugin code.  Some volume plugins may need to use the SELinux context during a mount operation in
certain cases.  To account for this, our design must have a way for volume plugins to state that
a particular volume should or should not receive generic label management.

For shared storage, the picture is murkier.  Labels for existing shared storage will be managed
outside Kubernetes and administrators will have to set the SELinux context of pods correctly.
The problem of solving SELinux label management for new shared storage is outside the scope for
this proposal.

## Analysis

The system needs to be able to:

1.  Model correctly which volumes require SELinux label management
1.  Relabel volumes with the correct SELinux context when required

### Modeling whether a volume requires label management

#### Unshared storage: volumes derived from `EmptyDir`

Empty dir and volumes derived from it are created by the system, so Kubernetes must always ensure
that the ownership and SELinux context (when relevant) are set correctly for the volume to be
usable.

#### Unshared storage: network block devices

Volume plugins based on network block devices such as AWS EBS and RBS can be treated the same way
as local volumes.  Since inodes are written to these block devices in the same way as `EmptyDir`
volumes, permissions and ownership can be managed on the client side by the Kubelet when used
exclusively by one pod.  When the volumes are used outside of a persistent volume, or with the
`ReadWriteOnce` mode, they are effectively unshared storage.

When used by multiple pods, there are many additional use-cases to analyze before we can be
confident that we can support SELinux label management robustly with these file systems.  The right
design is one that makes it easy to experiment and develop support for ownership management with
volume plugins to enable developers and cluster operators to continue exploring these issues.

#### Shared storage: hostPath

The `hostPath` volume should only be used by effective-root users, and the permissions of paths
exposed into containers via hostPath volumes should always be managed by the cluster operator.  If
the Kubelet managed the SELinux labels for `hostPath` volumes, a user who could create a `hostPath`
volume could affect changes in the state of arbitrary paths within the host's filesystem.  This
would be a severe security risk, so we will consider hostPath a corner case that the kubelet should
never perform ownership management for.

#### Shared storage: network

Ownership management of shared storage is a complex topic.  SELinux labels for existing shared
storage will be managed externally from Kubernetes.  For this case, our API should make it simple to
express whether a particular volume should have these concerns managed by Kubernetes.

We will not attempt to address the concerns of new shared storage in this proposal.

When a network block device is used as a persistent volume in `ReadWriteMany` or `ReadOnlyMany`
modes, it is shared storage, and thus outside the scope of this proposal.

#### API requirements

From the above, we know that label management must be applied:

1.  To some volume types always
2.  To some volume types never
3.  To some volume types *sometimes*

Volumes should be relabeled with the correct SELinux context.  Docker has this capability today; it
is desirable for other container runtime implementations to provide similar functionality.

Relabeling should be an optional aspect of a volume plugin to accommodate:

1.  volume types for which generalized relabeling support is not sufficient
2.  testing for each volume plugin individually

## Proposed Design

Our design should minimize code for handling SELinux labelling required in the Kubelet and volume
plugins.

### Deferral: MCS label allocation

Our short-term goal is to facilitate volume sharing and isolation with SELinux and expose the
primitives for higher level composition; making these automatic is a longer-term goal.  Allocating
groups and MCS labels are fairly complex problems in their own right, and so our proposal will not
encompass either of these topics.  There are several problems that the solution for allocation
depends on:

1.  Users and groups in Kubernetes
2.  General auth policy in Kubernetes
3.  [security policy](https://github.com/kubernetes/kubernetes/pull/7893)

### API changes

The [inline container security attributes PR (12823)](https://github.com/kubernetes/kubernetes/pull/12823)
adds a `pod.Spec.SecurityContext.SELinuxOptions` field.  The change to the API in this proposal is
the addition of the semantics to this field:

* When the `pod.Spec.SecurityContext.SELinuxOptions` field is set, volumes that support ownership
management in the Kubelet have their SELinuxContext set from this field.

```go
package api

type PodSecurityContext struct {
    // SELinuxOptions captures the SELinux context for all containers in a Pod.  If a container's
    // SecurityContext.SELinuxOptions field is set, that setting has precedent for that container.
    //
    // This field will be used to set the SELinux of volumes that support SELinux label management
    // by the kubelet.
    SELinuxOptions *SELinuxOptions `json:"seLinuxOptions,omitempty"`
}
```

The V1 API is extended with the same semantics:

```go
package v1

type PodSecurityContext struct {
    // SELinuxOptions captures the SELinux context for all containers in a Pod.  If a container's
    // SecurityContext.SELinuxOptions field is set, that setting has precedent for that container.
    //
    // This field will be used to set the SELinux of volumes that support SELinux label management
    // by the kubelet.
    SELinuxOptions *SELinuxOptions `json:"seLinuxOptions,omitempty"`
}
```

#### API backward compatibility

Old pods that do not have the `pod.Spec.SecurityContext.SELinuxOptions` field set will not receive
SELinux label management for their volumes.  This is acceptable since old clients won't know about
this field and won't have any expectation of their volumes being managed this way.

The existing backward compatibility semantics for SELinux do not change at all with this proposal.

### Kubelet changes

The Kubelet should be modified to perform SELinux label management when required for a volume.  The
criteria to activate the kubelet SELinux label management for volumes are:

1.  SELinux integration is enabled in the cluster
2.  SELinux is enabled on the node
3.  The `pod.Spec.SecurityContext.SELinuxOptions` field is set
4.  The volume plugin supports SELinux label management

The `volume.Mounter` interface should have a new method added that indicates whether the plugin
supports SELinux label management:

```go
package volume

type Builder interface {
    // other methods omitted
    SupportsSELinux() bool
}
```

Individual volume plugins are responsible for correctly reporting whether they support label
management in the kubelet.  In the first round of work, only `hostPath` and `emptyDir` and its
derivations will be tested with ownership management support:

| Plugin Name             | SupportsOwnershipManagement   |
|-------------------------|-------------------------------|
| `hostPath`              | false                         |
| `emptyDir`              | true                          |
| `gitRepo`               | true                          |
| `secret`                | true                          |
| `downwardAPI`           | true                          |
| `gcePersistentDisk`     | false                         |
| `awsElasticBlockStore`  | false                         |
| `nfs`                   | false                         |
| `iscsi`                 | false                         |
| `glusterfs`             | false                         |
| `persistentVolumeClaim` | depends on underlying volume and PV mode |
| `rbd`                   | false                         |
| `cinder`                | false                         |
| `cephfs`                | false                         |

Ultimately, the matrix will theoretically look like:

| Plugin Name             | SupportsOwnershipManagement   |
|-------------------------|-------------------------------|
| `hostPath`              | false                         |
| `emptyDir`              | true                          |
| `gitRepo`               | true                          |
| `secret`                | true                          |
| `downwardAPI`           | true                          |
| `gcePersistentDisk`     | true                          |
| `awsElasticBlockStore`  | true                          |
| `nfs`                   | false                         |
| `iscsi`                 | true                          |
| `glusterfs`             | false                         |
| `persistentVolumeClaim` | depends on underlying volume and PV mode |
| `rbd`                   | true                          |
| `cinder`                | false                         |
| `cephfs`                | false                         |

In order to limit the amount of SELinux label management code in Kubernetes, we propose that it be a
function of the container runtime implementations.  Initially, we will modify the docker runtime
implementation to correctly set the `:Z` flag on the appropriate bind-mounts in order to accomplish
generic label management for docker containers.

Volume types that require SELinux context information at mount must be injected with and respect the
enablement setting for the labeling for the volume type.  The proposed `VolumeConfig` mechanism
will be used to carry information about label management enablement to the volume plugins that have
to manage labels individually.

This allows the volume plugins to determine when they do and don't want this type of support from
the Kubelet, and allows the criteria each plugin uses to evolve without changing the Kubelet.

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/proposals/selinux.md?pixel)]()


text:
"""trumpcrawler URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from crawl.views import get_home, get_tweets, get_articles

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^crawl/main$', get_home, name='home'),
    url(r'^crawl/twitter$', get_tweets, name='tweet'),
    url(r'^crawl/cnn$', get_articles, name='article'),
]


text:
layout: organization
category: local

title: National MS Society
impact_area: Health
keywords:
location_services:
location_offices:
website: nationalmssociety.org

description:
mission: |
  The National MS Society is a collective of passionate individuals who want to do something about MS now—to move together toward a world free of multiple sclerosis. MS stops people from moving. We exist to make sure it doesn't.

  We help each person address the challenges of living with MS through our 50-state network of chapters. The Society helps people affected by MS by funding cutting-edge research, driving change through advocacy, facilitating professional education, and providing programs and services that help people with MS and their families move their lives forward.

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: Uniondale
state: NY
address: |
  PO Box 10123
  Uniondale NY 11553
lat: 40.704884
lng: -73.591014
phone: 718-698-0600
ext:
fax:
email:
preferred_contact:
contact_person_intro:
---


text:
<?php

use OvertureLabs\SEO\SEO;

/**
 * Class SEOTest
 */
class SEOTest extends PHPUnit_Framework_TestCase {

}


text:
template <class T>
struct matrix_traits<DenseMatrix<T>>
{
    typedef T value_type;
    typedef size_t size_type;
    typedef ptrdiff_t difference_type;
    typedef T& reference;
    typedef const T& const_reference;
    typedef T* pointer;
    typedef const T* const_pointer;

    typedef DenseMatrixIterator<T, false> iterator;
    typedef DenseMatrixIterator<T, true> const_iterator;
};

template <class T = double>
class DenseMatrix : public Matrix<DenseMatrix<T>>
{
    friend class Matrix<DenseMatrix<T>>;
    template <class> friend class DenseMatrix;
    friend class DenseMatrixIterator<T, false>;
    friend class DenseMatrixIterator<T, true>;

public:
    typedef typename matrix_traits<DenseMatrix>::value_type value_type;
    typedef typename matrix_traits<DenseMatrix>::size_type size_type;
    typedef typename matrix_traits<DenseMatrix>::difference_type difference_type;
    typedef typename matrix_traits<DenseMatrix>::reference reference;
    typedef typename matrix_traits<DenseMatrix>::const_reference const_reference;
    typedef typename matrix_traits<DenseMatrix>::pointer pointer;
    typedef typename matrix_traits<DenseMatrix>::const_pointer const_pointer;

    typedef typename matrix_traits<DenseMatrix>::iterator iterator;
    typedef typename matrix_traits<DenseMatrix>::const_iterator const_iterator;

public:
    DenseMatrix(size_type rows, size_type columns, T value = T());

    DenseMatrix(const DenseMatrix& rhs);

    template <class D>
    DenseMatrix(const DenseMatrix<D>& rhs);

    template <class D>
    DenseMatrix(const Matrix<D>& rhs);

    DenseMatrix& operator=(const DenseMatrix& rhs);

    template <class D>
    DenseMatrix& operator=(const DenseMatrix<D>& rhs);

    template <class D>
    DenseMatrix& operator=(const Matrix<D>& rhs);

protected:
    void doClear();
    DenseMatrix doTranspose() const;

private:
    std::vector<T> m_values;
};

template <class T>
DenseMatrix<T>::DenseMatrix(size_type rows, size_type columns, T value):
    Matrix<DenseMatrix>(rows, columns),
    m_values(rows * columns, value)
{
    assert(rows && columns);
}

template <class T>
DenseMatrix<T>::DenseMatrix(const DenseMatrix& rhs):
    Matrix<DenseMatrix>(rhs.rows(), rhs.columns()),
    m_values(rhs.m_values)
{}

template <class T>
template <class D>
DenseMatrix<T>::DenseMatrix(const DenseMatrix<D>& rhs):
    Matrix<DenseMatrix>(rhs.rows(), rhs.columns()),
    m_values(rhs.m_values.size())
{
    for(size_type i = 0; i < rhs.m_values.size(); ++i)
    {
        m_values[i] = rhs.m_values[i];
    }
}

template <class T>
template <class D>
DenseMatrix<T>::DenseMatrix(const Matrix<D>& rhs):
    Matrix<DenseMatrix>(rhs.rows(), rhs.columns()),
    m_values(this->rows() * this->columns())
{
    typename Matrix<D>::const_iterator beg = rhs.begin();
    typename Matrix<D>::const_iterator end = rhs.end();
    for(; beg != end; beg.nextNonZero())
    {
        *(this)[beg.row()][beg.column()] = *beg;
    }
}

template <class T>
DenseMatrix<T>& DenseMatrix<T>::operator=(const DenseMatrix& rhs)
{
    assert(this->rows() == rhs.rows() && this->columns() == rhs.columns());
    m_values = rhs.m_values;
    return *this;
}

template <class T>
template <class D>
DenseMatrix<T>& DenseMatrix<T>::operator=(const DenseMatrix<D>& rhs)
{
    assert(this->rows() == rhs.rows() && this->columns() == rhs.columns());
    for(size_type i = 0; i < rhs.m_values.size(); ++i)
    {
        m_values[i] = rhs.m_values[i];
    }
    return *this;
}

template <class T>
template <class D>
DenseMatrix<T>& DenseMatrix<T>::operator=(const Matrix<D>& rhs)
{
    assert(this->rows() == rhs.rows() && this->columns() == rhs.columns());
    this->clear();
    typename Matrix<D>::const_iterator beg = rhs.begin();
    typename Matrix<D>::const_iterator end = rhs.end();
    for(; beg != end; beg.nextNonZero())
    {
        *(this)[beg.row()][beg.column()] = *beg;
    }
    return *this;
}

template <class T>
void DenseMatrix<T>::doClear()
{
    std::fill(m_values.begin(), m_values.end(), T());
}

template <class T>
DenseMatrix<T> DenseMatrix<T>::doTranspose() const
{
    DenseMatrix<T> t(this->columns(), this->rows());

    for(size_type i = 0; i < this->rows(); ++i)
    {
        for(size_type j = 0; j < this->columns(); ++j)
        {
            t.m_values[(j * this->rows()) + i] = m_values[(i * this->columns()) + j];
        }
    }

    return t;
}

#endif


text:
/* OneUI 2.1 bug fix */
.lotusSection h2 {
	margin: 0px;
}

.lotusTitleBar {
	border-bottom:0px;
}

.lotusMain {
	border-top:0px;
}

.lotusTitleBar h2 {
	margin: 0px;
	font-weight: bold;
}

.lotusPlaceBar h2 {
	margin: 0px;
}

/* add the xpages logo */
.lotusLogo {
	background-image: url("xpagesdk_logo.png");
	width: 200px;
	height: 40px;
	margin-left: 3px !important;
}

/* Form layout */
.lotusContent h1 {
	margin-bottom: 20px;
	text-transform:uppercase;
}

.fileViewer{
	font-family:Consolas,"Courier New";
	overflow:auto;
	white-space:pre-wrap;
}

.tip th {
	text-align: left;
}

.fileSelector {
	margin-top:4px;
	margin-left:10px;
}

.fileSelector ul {
	list-style-type:none;
	margin:0;
	padding:0;
}
.fileSelector li {
	display:inline;
}

.fileSelector li + li{
	border-left: 2px solid gray;
	padding-left: 5px;
	margin-left:5px;
}

.fileSelector .current {
	color:gray;
	font-weight:bold;
}

/* list on about page */
.pipelist ul {
	list-style-type: none;
	margin: 0 0 0 10px;
	padding: 0;
	display: inline;
}

.pipelist li {
	display: inline;
}

.pipelist li + li:before{
    content: " | ";
    padding: 0 5px;
	margin-top:4px;
	margin-left:5px;
}

/* table on the about page */
.lotusTable th {
	background-color: gray;
	color: white;
	font-weight: bold;
}

.lotusTable th a, .lotusTable th a:hover  {
	color: white;
	}

.lotusTable td,.lotusTable th {
	padding: 2px 5px 2px 5px;
}

.lotusTable {
	margin-bottom: 20px;
}

.simpleTable td {
	padding:0 5px 0 0 ;
	margin:0;
	border:0;
}

/* Junit */
#junit h2 {
	margin: 0 0 20px 0;
}

/* Download link */

.downloadLink{
	color:red;
	background-image: url('download.png');
background-position: center right;
background-repeat: no-repeat;
padding-right:13px;
}

/* Error messages */
.messages .xspMessage {
	margin:4px;
	padding:3px;
}


text:
<?php
    $this->layout ($layout);
    $this->textdomain ('catlab.accounts'); ?>

	<?php foreach ($authenticators as $authenticator) { ?>
		<?php if ($authenticator instanceof \CatLab\Accounts\Authenticators\Password) { ?>
			<?php echo $authenticator->getForm (); ?>
		<?php } ?>
	<?php } ?>

<?php if (isset ($cancel)) { ?>

<a href="<?php echo $cancel; ?>"><?php echo $this->gettext ('I don\'t want to login right now'); ?>

<?php } ?>

Sign in with:

    <?php foreach ($authenticators as $authenticator) { ?>
        <?php if (! ($authenticator instanceof \CatLab\Accounts\Authenticators\Password)) { ?>
            <?php echo $authenticator->getInlineForm (); ?>
        <?php } ?>
    <?php } ?>