text:
import React from 'react'
import {
  Card,
  CardHeader,
  CardText,
  CardActions,
  FlatButton,
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHeaderColumn,
  TableRowColumn,
} from 'material-ui'
import numeral from 'numeral'
import {graphql, gql} from 'react-apollo'
import {compose} from 'recompose'
import {connect} from 'react-redux'
import {get, map, isEmpty} from 'lodash'
import {humanize} from 'inflection'
import moment from 'moment'
import {showNotification} from '../../actions'

const Colors = {
  new: 'green',
  shipped: '#c7ca00',
  completed: 'blue',
  default: '#ccc',
}

class Order extends React.Component {
  getOrderSubtitle({billingAddress: d}) {
    return (
      {d.name} <{d.email}> ({d.phone}), {d.city} {d.postalCode} {d.streetAddress}
    )
  }

  setStatus(newStatus) {
    this.props.mutate({
      variables: {order: this.props.order.id, status: newStatus},
      refetchQueries: ['orders']
    }).then(() => {
      this.props.showNotification(`Order marked as ${newStatus}`)
    }).catch(e => {
      console.log(e);
      this.props.showNotification(`Ooos, something went wrong.`)
    })
  }

  render() {
    const {order} = this.props
    const finiteStatus = ['completed', 'canceled'].includes(order.status)
    return (
      <Card style={{marginBottom: 20}} containerStyle={{borderTopStyle: 'solid', borderTopWidth: 4, borderColor: get(Colors, order.status, Colors.default)}}>
        <CardHeader
          title={#{order.number} {moment(order.createdAt).format('ll LT')}}
          subtitle={this.getOrderSubtitle(order)}
          actAsExpander
          showExpandableButton
          style={{display: 'flex'}}
        >

            {humanize(order.status).toUpperCase()}

            {numeral(order.total).format('0.00')} ({humanize((order.paymentStatus || 'not-paid').replace('-', '_'))})

        </CardHeader>
        <CardText expandable={true}>

            <TableHeader displaySelectAll={false} adjustForCheckbox={false} enableSelectAll={false}>
              <TableRow>
                <TableHeaderColumn>Name</TableHeaderColumn>
                <TableHeaderColumn>Quantity</TableHeaderColumn>
                <TableHeaderColumn>Price</TableHeaderColumn>
                <TableHeaderColumn style={{textAlign: 'right'}}>Total</TableHeaderColumn>
              </TableRow>
            </TableHeader>
            <TableBody displayRowCheckbox={false}>
              {map(order.lines, item => (<TableRow key={item.product.id} hoverable>
                <TableRowColumn>{isEmpty(item.name) ? get(item, 'product.data.name', 'DELETED') : item.name}</TableRowColumn>
                <TableRowColumn>{item.count}</TableRowColumn>
                <TableRowColumn>{numeral(item.price).format('0.00')}</TableRowColumn>
                <TableRowColumn style={{textAlign: 'right'}}>{numeral(item.price * item.count).format('0.00')}</TableRowColumn>
              </TableRow>))}
              <TableRow>
                <TableRowColumn style={{textAlign: 'right', fontSize: 18}} colSpan={4}>
                  Delivery - {order.delivery.label}: {numeral(order.delivery.cost).format('0.00')}
                </TableRowColumn>
              </TableRow>
              {order.processingFee &&
                <TableRow>
                  <TableRowColumn style={{textAlign: 'right', fontSize: 18}} colSpan={4}>
                    Processing fee: {numeral(order.processingFee).format('0.00')}
                  </TableRowColumn>
                </TableRow>
              }
              <TableRow>
                <TableRowColumn style={{textAlign: 'right', fontSize: 18}} colSpan={4}>
                  Order total: {numeral(order.total).format('0.00')}
                </TableRowColumn>
              </TableRow>
            </TableBody>

        </CardText>
        <CardActions expandable>
          {!finiteStatus && order.status !== 'shipped' &&
            <FlatButton icon={} label="Ship" onClick={() => this.setStatus('shipped')} />
          }
          {!finiteStatus &&
            <FlatButton icon={} label="Complete" onClick={() => this.setStatus('completed')} />
          }
          {!finiteStatus &&
            <FlatButton style={{float: 'right'}} secondary label="Cancel" onClick={() => this.setStatus('canceled')} />
          }
          {order.paymentMethod === 'paypal' &&
            <FlatButton
              icon={}
              style={{float: 'right'}}
              label="View receipt"
              onClick={() => window.open(get(order.receipt, 'url'), get(order.receipt, 'id'), {toolbar: false})} />
          }
          {order.paymentMethod === 'braintree' &&
            <FlatButton
              icon={}
              style={{float: 'right'}}
              label="View receipt"
              onClick={() => window.open(get(order.receipt, 'url'), get(order.receipt, 'id'), {toolbar: false})} />
          }
        </CardActions>
      </Card>
    )
  }
}

const updateOrderStatus = gql`
  mutation updateOrderStatus($order: ID!, $status: OrderStatus!) {
    updateOrderStatus(order: $order, status: $status) { id }
  }
`

const e = compose(
  graphql(updateOrderStatus),
  connect(() => ({}), {showNotification})
)

export default e(Order)


text:
use serde::Deserialize;
use std::cmp::PartialEq;

#[derive(Deserialize, PartialEq, Debug)]
#[serde(tag = "type", content = "value")]
pub enum Stmt {
    #[serde(rename = "query")]
    Query(String),
    #[serde(rename = "procedure")]
    Procedure(String),
}

#[derive(Deserialize, PartialEq, Debug)]
pub enum Param {
    S(String),
    NS(String),
    I(isize),
}

#[derive(Deserialize, PartialEq, Debug)]
#[serde(rename = "request")]
pub struct Request {
    pub stmt: Stmt,
    #[serde(rename = "params")]
    pub params: Vec<Param>,
}

pub fn parse_json_request(req_str: &str) -> Result<Request, std::io::Error> {
    Ok(serde_json::de::from_str(req_str)?)
}

pub fn parse_xml_request(req_str: &str) -> Result<Request, serde_xml_rs::Error> {
    Ok(serde_xml_rs::de::from_str(req_str)?)
}

#[cfg(test)]
mod tests {
    #[test]
    fn json1() {
        use super::{parse_json_request, Request, Stmt, Param};

        let req1 = r###"{
            "stmt": {
                "type": "query",
                "value": "SELECT TOP 1 Id, CountryCode, Registered FROM UserProfileDb.dbo.UserCountries WHERE Id = ?"
            },
            "params": [
                { "S": "random guid" }
            ]
        }"###;

        let parsed = parse_json_request(req1).unwrap();
        assert_eq!(parsed, Request{
            stmt: Stmt::Query("SELECT TOP 1 Id, CountryCode, Registered FROM UserProfileDb.dbo.UserCountries WHERE Id = ?".to_owned()),
            params: vec![
                Param::S("random guid".to_owned())
            ]
        });
    }

    #[test]
    fn xml1() {
        use super::{parse_xml_request, Request, Stmt, Param};

        let req1 = r###"
            <request>
                <stmt type="query">
                    <value>SELECT TOP 1 Id, CountryCode, Registered FROM UserProfileDb.dbo.UserCountries WHERE Id = ?</value>
                </stmt>
                <params>
                    <S>random guid</S>
                </params>
            </request>
        "###;

        let parsed = parse_xml_request(req1).unwrap();
        assert_eq!(parsed, Request{
            stmt: Stmt::Query("SELECT TOP 1 Id, CountryCode, Registered FROM UserProfileDb.dbo.UserCountries WHERE Id = ?".to_owned()),
            params: vec![
                Param::S("random guid".to_owned())
            ]
        });

    }
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import { Alert, Button, Grid, Row, Col, Panel, Table } from 'react-bootstrap';
import CircularProgressbar from 'react-circular-progressbar';
import Spinner from 'react-spinkit';
import TimeAgo from 'react-timeago';
import { BadJobNotice, cfURLRoot } from './CommonComponents';

async function getJobStatus(jobId) {
  let res = await fetch(cfURLRoot + '/getJobStatus', {
    accept: 'application/json',
    method: 'POST',
    body: JSON.stringify({
      jobid: jobId
    }),
    headers: {
      'Content-Type': 'application/json'
    }
  });
  checkStatus(res);
  return res.json();
}

// @TODO: dup, factor.
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  console.log('Bad response: ', response);
  const error = new Error(`HTTP Error ${response.statusText}`);
  error.status = response.statusText;
  error.response = response;
  console.log(error);
  throw error;
}

// @TODO: dup, factor.
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// @TODO: dup, factor.
function tsToDate(ts) {
  return ts && new Date(parseInt(ts, 10));
}

class JobStatus extends Component {
  loadingString = (

      <Spinner id="spinner" color="inherit" name="three-bounce" fadeIn="none" />

  );

  constructor(props) {
    super(props);
    this.state = {
      progress: 0,
      status: this.loadingString,
      boardName: this.loadingString,
      createdTime: this.loadingString,
      startedTime: undefined,
      pollCount: 0,
      pollDelay: 500,
      donePolling: false,
      alertArea: null,
      sequentialErrorCount: 0
    };
  }

  async updateJobState() {
    let completed = false;
    let updatePollingInterval = false;
    let newState = {
      pollDelay: 1000,
      pollCount: this.state.pollCount + 1,
      donePolling: false,
      sequentialErrorCount: 0
    };
    try {
      const result = await getJobStatus(this.props.jobId);
      console.log(result);
      if (result.code) {
        console.log('Server error getting job state', result.code);
        newState.sequentialErrorCount = this.state.sequentialErrorCount + 1;
      } else {
        Object.assign(newState, {
          progress: result.progress || 0,
          status: result.state,
          createdTime: tsToDate(result.jobCreatedTime),
          startedTime: tsToDate(result.jobStartedTime),
          boardName: result.boardName
        });
        if (result.state === 'Completed' || result.state === 'Failed') {
          completed = true;
        }
      }
    } catch (err) {
      console.log('Server error getting job state', err);
      newState.sequentialErrorCount = this.state.sequentialErrorCount + 1;
    }

    let jobAge = 0;
    if (newState.createdTime instanceof Date) {
      jobAge = (new Date() - newState.createdTime) / 1000;
    }
    if (newState.sequentialErrorCount > 3) {
      newState.donePolling = true;
      updatePollingInterval = true;
      newState.alertArea = (

          <Alert bsStyle="danger">
            Too many server errors in a row. Please refresh the page to check on
            the status at a later time.
          </Alert>
          <BadJobNotice />

      );
    } else if (newState.pollCount > 45 || jobAge > 120) {
      newState.donePolling = true;
      updatePollingInterval = true;
      newState.alertArea = (

          <Alert bsStyle="danger">
            The job is taking much longer than expected. Please refresh the page
            to check on the status at a later time.
          </Alert>
          <BadJobNotice />

      );
    } else if (newState.pollCount > 40 || jobAge > 50) {
      newState.pollDelay = 10000;
      newState.alertArea = (

          <Alert bsStyle="warning">
            This is taking quite a bit longer than usual, there may be a problem
            with the servers.
          </Alert>
          <BadJobNotice />

      );
    } else if (newState.pollCount > 30 || jobAge > 30) {
      newState.pollDelay = 2000;
      newState.alertArea = (
        <Alert bsStyle="warning">
          This is taking longer than usual, please be patient.
        </Alert>
      );
    }

    if (newState.pollDelay !== this.state.pollDelay) {
      updatePollingInterval = true;
    }

    this.setState(newState);

    if (updatePollingInterval && !completed) {
      clearInterval(this.timerID);
      if (!newState.donePolling) {
        this.setupPollingTimer(newState.pollDelay);
      }
    }

    return completed;
  }

  async setupPollingTimer(pollDelay) {
    this.timerID = setInterval(async () => {
      const completed = await this.updateJobState();
      if (completed) {
        clearInterval(this.timerID);
        await sleep(1500); // Give the user a chance to see the job completed.
        this.props.history.replace(`/results/${this.props.jobId}`);
      }
    }, pollDelay);
  }

  async componentDidMount() {
    window.scrollTo(0, 0);
    this.setupPollingTimer(this.state.pollDelay);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  render() {
    return (

        <Row>
          <Col sm={4}>

              <CircularProgressbar
                percentage={this.state.progress | 0}
                initialAnimation
                classForPercentage={pct => (pct < 100 ? '' : 'complete')}
              />

          </Col>
          <Col sm={8}>

                  Board
                  {this.state.boardName}

                  Job Id
                  {this.props.jobId}

                {!this.state.startedTime && (

                    Created

                      <TimeAgo
                        date={this.state.createdTime}
                        title={this.state.createdTime}
                      />

                )}
                {this.state.startedTime && (

                    Started

                      <TimeAgo
                        date={this.state.startedTime}
                        title={this.state.startedTime}
                      />

                )}

                  Status
                  {this.state.status}

          </Col>
        </Row>
        <Row>
          <Col sm={8} smOffset={2}>
            {this.state.alertArea}
          </Col>
        </Row>

    );
  }
}

class JobExecutionPage extends Component {
  constructor(props) {
    super(props);
    this.handleCancelJob = this.handleCancelJob.bind(this);
  }

  handleCancelJob(e) {
    console.log('@TODO: impl job cancellation!');
    // @TODO: just nav back? Try to delete the message from the queue? Mark the job as cancelled?
    e.preventDefault();
  }

  render() {
    const title =
MonkeyCAM Job Status
;

    return (
      <Grid>
        <Row>
          <Col sm={8} smOffset={2}>
            <Panel header={title} bsStyle="primary">
              <JobStatus
                jobId={this.props.match.params.jobId}
                history={this.props.history}
              />
            </Panel>
          </Col>
        </Row>
        <Row>
          <Col sm={8} smOffset={2}>

              <Button bsStyle="primary" onClick={this.handleCancelJob}>
                Cancel Job
              </Button>

          </Col>
        </Row>
      </Grid>
    );
  }
}

export default JobExecutionPage;


text:
package io.cattle.platform.simple.allocator;

import com.netflix.config.DynamicLongProperty;

import io.cattle.platform.archaius.util.ArchaiusUtil;
import io.cattle.platform.lock.definition.AbstractLockDefinition;
import io.cattle.platform.lock.definition.BlockingLockDefinition;

public class SimpleAllocatorLock extends AbstractLockDefinition implements BlockingLockDefinition {

    public static final DynamicLongProperty WAIT = ArchaiusUtil.getLong("simple.allocator.lock.wait");

    public SimpleAllocatorLock() {
        super("SIMPLE.ALLOCATOR.LOCK");
    }

    @Override
    public long getWait() {
        return WAIT.get();
    }

}


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('quotedb', '0001_initial'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='quote',
            options={'ordering': ('-created',), 'verbose_name': 'quote', 'verbose_name_plural': 'quotes'},
        ),
        migrations.AlterField(
            model_name='quote',
            name='approved',
            field=models.BooleanField(default=False, verbose_name='approved'),
        ),
        migrations.AlterField(
            model_name='quote',
            name='body',
            field=models.TextField(verbose_name='body'),
        ),
        migrations.AlterField(
            model_name='quote',
            name='created',
            field=models.DateTimeField(auto_now_add=True, verbose_name='created'),
        ),
        migrations.AlterField(
            model_name='quote',
            name='owner',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='owner'),
        ),
    ]


text:
import cloneDeep from 'lodash.clonedeep'

const linkMock = {
  id: 'linkid',
  type: 'Link',
  linkType: 'linkType'
}

const sysMock = {
  type: 'Type',
  id: 'id',
  space: cloneDeep(linkMock),
  createdAt: 'createdatdate',
  updatedAt: 'updatedatdate'
}

const spaceMock = {
  sys: Object.assign(cloneDeep(sysMock), { type: 'Space' }),
  name: 'name',
  locales: ['en-US']
}

const contentTypeMock = {
  sys: Object.assign(cloneDeep(sysMock), { type: 'ContentType' }),
  name: 'name',
  description: 'desc',
  displayField: 'displayfield',
  fields: [
    {
      id: 'fieldid',
      name: 'fieldname',
      type: 'Text',
      localized: true,
      required: false
    }
  ]
}

const entryMock = {
  sys: Object.assign(cloneDeep(sysMock), {
    type: 'Entry',
    contentType: Object.assign(cloneDeep(linkMock), { linkType: 'ContentType' }),
    locale: 'locale'
  }),
  fields: {
    field1: 'str'
  }
}
const editorInterfaceMock = {
  sys: Object.assign(cloneDeep(sysMock), {
    type: 'EditorInterface',
    contentType: { sys: Object.assign(cloneDeep(linkMock), { linkType: 'ContentType' }) },
    space: Object.assign(cloneDeep(linkMock), { linkType: 'Space' })
  }),
  controls: [
    {
      fieldId: 'fieldId',
      widgetId: 'singleLine'
    }
  ]
}
const assetMock = {
  sys: Object.assign(cloneDeep(sysMock), {
    type: 'Asset',
    locale: 'locale'
  }),
  fields: {
    field1: 'str'
  }
}

const assetWithFilesMock = {
  sys: Object.assign(cloneDeep(sysMock), {
    type: 'Asset',
    locale: 'locale'
  }),
  fields: {
    files: {
      locale: {
        contentType: 'image/svg',
        fileName: 'filename.svg',
        uploadFrom: {
          sys: {
            type: 'Link',
            linkType: 'Upload',
            id: 'some_random_id'
          }
        }
      },
      locale2: {
        contentType: 'image/svg',
        fileName: 'filename.svg',
        uploadFrom: {
          sys: {
            type: 'Link',
            linkType: 'Upload',
            id: 'some_random_id'
          }
        }
      }
    }
  }
}

const uploadMock = {
  sys: Object.assign(cloneDeep(sysMock), {
    type: 'Upload',
    id: 'some_random_id'
  })
}

const localeMock = {
  sys: Object.assign(cloneDeep(sysMock), {
    type: 'Locale'
  }),
  name: 'English',
  code: 'en',
  contentDeliveryApi: true,
  contentManagementApi: true,
  default: true
}

const webhookMock = {
  sys: Object.assign(cloneDeep(sysMock), { type: 'WebhookDefinition' })
}

const spaceMembershipMock = {
  sys: Object.assign(cloneDeep(sysMock), { type: 'SpaceMembership' })
}

const roleMock = {
  sys: Object.assign(cloneDeep(sysMock), { type: 'Role' })
}

const apiKeyMock = {
  sys: Object.assign(cloneDeep(sysMock), { type: 'ApiKey' })
}

const errorMock = {
  config: {
    url: 'requesturl',
    headers: {}
  },
  data: {},
  response: {
    status: 404,
    statusText: 'Not Found'
  }
}

const mocks = {
  link: linkMock,
  sys: sysMock,
  contentType: contentTypeMock,
  editorInterface: editorInterfaceMock,
  entry: entryMock,
  asset: assetMock,
  locale: localeMock,
  webhook: webhookMock,
  spaceMembership: spaceMembershipMock,
  role: roleMock,
  apiKey: apiKeyMock,
  error: errorMock,
  upload: uploadMock
}

function cloneMock (name) {
  return cloneDeep(mocks[name])
}

function mockCollection (entityMock) {
  return {
    total: 1,
    skip: 0,
    limit: 100,
    items: [entityMock]
  }
}

function setupEntitiesMock (rewiredModuleApi) {
  const entitiesMock = {
    space: {
      wrapSpace: jest.fn(),
      wrapSpaceCollection: jest.fn()
    },
    contentType: {
      wrapContentType: jest.fn(),
      wrapContentTypeCollection: jest.fn()
    },
    entry: {
      wrapEntry: jest.fn(),
      wrapEntryCollection: jest.fn()
    },
    asset: {
      wrapAsset: jest.fn(),
      wrapAssetCollection: jest.fn()
    },
    locale: {
      wrapLocale: jest.fn(),
      wrapLocaleCollection: jest.fn()
    },
    webhook: {
      wrapWebhook: jest.fn(),
      wrapWebhookCollection: jest.fn()
    },
    spaceMembership: {
      wrapSpaceMembership: jest.fn(),
      wrapSpaceMembershipCollection: jest.fn()
    },
    role: {
      wrapRole: jest.fn(),
      wrapRoleCollection: jest.fn()
    },
    apiKey: {
      wrapApiKey: jest.fn(),
      wrapApiKeyCollection: jest.fn()
    },
    editorInterface: {
      wrapEditorInterface: jest.fn()
    },
    upload: {
      wrapUpload: jest.fn()
    }
  }
  rewiredModuleApi.__Rewire__('entities', entitiesMock)

  return entitiesMock
}

export {
  linkMock,
  sysMock,
  spaceMock,
  contentTypeMock,
  editorInterfaceMock,
  entryMock,
  assetMock,
  assetWithFilesMock,
  localeMock,
  webhookMock,
  spaceMembershipMock,
  roleMock,
  apiKeyMock,
  errorMock,
  cloneMock,
  mockCollection,
  setupEntitiesMock,
  uploadMock
}


text:
/**
 * UI.Slider Designer
 *
 */
UI.Slider_Designer = function(control) {
    arguments.callee.superClass.constructor.apply(this, arguments);
    //    this.defaultWidth = 0;
    this.defaultHeight = 36;
};

extend(UI.Slider_Designer, UI.Designer);
UI.Slider_Designer.prototype.meta = UI.extendMeta(UI.Slider_Designer.prototype.meta, {
    type: "UI.Slider",
    props: {

        "height": {
            datatype: "String",
            readOnly: true,
            designable: false,
        },

        "width": {
            datatype: "String",
            readOnly: true,
            designable: false,
        },

        theme: {
            datatype: "String",
            editType: "Theme",
            designable: false,
            defaultValue: "C",
            valueRange: UI.THEMES
        },

        "min": {
            datatype: "Int",
            defaultValue: 0
        },

        "max": {
            datatype: "Int",
            defaultValue: 100
        },

        "value": {
            datatype: "Float",
            defaultValue: 50
        }
    },

    events: {
        onChange: {
            params: [ "value" ],
            icon: "controls/eventicon/change.png",
            alias: "onChange"
        }
    },

    methods: {

        _getValue: {alias: "getValue", params: [], output: true},
        _setValue: {alias: "setValue", params: [
            {name: "value", alias: "value"}
        ]},
        _getMin: {alias: "getMin", params: [], output: true}, _setMin: {alias: "setMin", params: [
            {name: "minValue", alias: "minValue"}
        ]},
        _getMax: {alias: "getMax", params: [], output: true}, _setMax: {alias: "setMax", params: [
            {name: "maxValue", alias: "maxValue"}
        ]}

    },

    defaultProperty: "value",
    defaultEvent: "onChange"
});

//register
UI.Slider.prototype.designerType = "UI.Slider_Designer";
MetaHub.register(UI.Slider_Designer.prototype.meta);


text:
/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */
package org.ligoj.bootstrap.core.model;

import java.io.IOException;

import org.springframework.data.domain.Persistable;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

/**
 * Serialize entities with their identifier.
 */
public class ToIdSerializer extends StdSerializer<Persistable<?>> {

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

	/**
	 * JAX-RS serializer instance.
	 */
	public static final ToIdSerializer INSTANCE = new ToIdSerializer();

	/**
	 * Default constructor.
	 */
	protected ToIdSerializer() {
		super(Persistable.class, false);
	}

	@Override
	public void serialize(final Persistable<?> bean, final JsonGenerator generator, final SerializerProvider provider)
			throws IOException {
		if (bean.getId() instanceof Number n) {
			// Numeric, but no decimal accepted
			generator.writeNumber(n.longValue());
		} else {
			// Consider ID as a String (not failsafe)
			generator.writeString((String) bean.getId());
		}
	}

}


text:
package com.intel.hadoop.graphbuilder.test.partition;

import java.io.IOException;

import com.intel.hadoop.graphbuilder.partition.mapreduce.vrecord.VrecordIngressMR;

/**
 * A runnable VrecordIngress Mapreduce taking arguments from commandline.
 * Example: hadoop jar target/graphbuilder-0.0.1-SNAPSHOT-hadoop-job.jar
 * com.intel.hadoop.graphbuilder.test.partition.VrecordIngressTest 8 input
 * output
 *
 * @author Haijie Gu
 */
public class VrecordMapReduceTest {
  public static void main(String[] args) throws IOException {

    (new VrecordIngressMR()).run(Integer.valueOf(args[0]), args[1], args[2]);
  }
}


text:
package com.rethinkdb.net;

import com.rethinkdb.Mapifier;
import com.rethinkdb.gen.exc.ReqlDriverError;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;

public class Util {
    public static String bufferToString(ByteBuffer buf) {
        // This should only be used on ByteBuffers we've created by
        // wrapping an array
        return new String(buf.array(), StandardCharsets.UTF_8);
    }

    @SuppressWarnings("unchecked")
    public static <T, P> T convertToPojo(Object value, Optional<Class<P>> pojoClass) {
        return !pojoClass.isPresent() || !(value instanceof Map)
                ? (T) value
                : (T) toPojo(pojoClass.get(), (Map<String, Object>) value);
    }

    public static long deadline(long timeout) {
        return System.currentTimeMillis() + timeout;
    }

    public static String fromUTF8(byte[] ba) {
        return new String(ba, StandardCharsets.UTF_8);
    }

    public static ByteBuffer leByteBuffer(int capacity) {
        // Creating the ByteBuffer over an underlying array makes
        // it easier to turn into a string later.
        byte[] underlying = new byte[capacity];
        return ByteBuffer.wrap(underlying)
                .order(ByteOrder.LITTLE_ENDIAN);
    }

    public static JSONObject toJSON(String str) {
        return (JSONObject) JSONValue.parse(str);
    }

    public static JSONObject toJSON(ByteBuffer buf) {
        InputStreamReader codepointReader =
                new InputStreamReader(new ByteArrayInputStream(buf.array()));
        return (JSONObject) JSONValue.parse(codepointReader);
    }

    public static byte[] toUTF8(String s) {
        return s.getBytes(StandardCharsets.UTF_8);
    }

    private static <T> T toPojo(Class<T> pojoClass, Map<String, Object> map) {
        try {
            if (map == null) {
                return null;
            }

            return Mapifier.fromMap(pojoClass, map);
        } catch (IllegalArgumentException e) {
            throw new ReqlDriverError("Can't convert %s to a POJO: %s", map, e.getMessage());
        }
    }
}


text:
<TITLE>Review for Room for Romeo Brass, A (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Room for Romeo Brass, A (1999)

reviewed by
Ian Waldron-Mantgani

A Room for Romeo Brass      **

Rated on a 4-star scale
Screening venue: Cornerhouse (Manchester)
Released in the UK by Alliance Atlantis on February 4, 2000; certificate 15;
90 minutes; countries of origin Canada/UK; aspect ratio 1.85:1

Directed by Shane Meadows; produced by George Faber, Charles Pattinson.
Written by Paul Fraser, Shane Meadows.
Photographed by Ashley Rowe; edited by Paul Tothill.

CAST.....
Andrew Shim..... Romeo Brass
Ben Marshall..... Gavin 'Knock Knock' Woolley
Paddy Considine..... Morell
Vicky McClure..... Ladine Brass
Frank Harper..... Joseph Brass
Julia Ford..... Sandra Woolley
James Higgins..... Bill Woolley
Bob Hoskins..... Steven Laws

"A Room for Romeo Brass" is alternately a tender suburban comedy and a harsh
cautionary tale about a violent psychopath. Yes, that is as weird as it
sounds. On my way out of the screening, I glanced over a synopsis which
described the movie as a "tender coming-of-age tale". Thank goodness that's
an inaccurate description -- if coming-of-age were as unsettling as this
movie, most people would commit suicide before getting out of high school.

The movie takes place in Nottingham, where we meet two schoolchildren, Romeo
(Andrew Shim) and Gavin (Ben Marhsall). The two exchange playful insults, but
are close, really, spending every day together and depending on each other's
moral support to get through their hardships: Romeo has been abandoned by his
father, except for occasional visits which provoke huge family rows; Gavin is
awaiting a serious back operation.

Early in the story, the boys are involved in a fight with two older lads,
which is broken up by the quaint Morell (Paddy Considine), a scruffy chap who
tells odd stories and seems somewhat clueless as to how most people behave.
When dropping Romeo home, he meets the lad's sister Ladine (Vicky McClure),
is instantly attracted to her and proceeds to pester her for a date.

Feeling sorry for this social misfit, Ladine eventually agrees, which is a
mistake, as it makes him a permanent fixture around the neighbourhood. He
befriends Romeo, but secretly obsesses over Ladine and threatens Gavin's
family, in sinister scenes which reveal Morell to be an angry, disturbed
individual. But at times his phoney accent, conversational tangents and
shifty body language are presented as comic. I wouldn't have minded if the
film had started in this vain and then gradually become serious, but even
after the introduction of danger, the film still feels able to dart in and
out of tomfoolery.

At first this is embarrassing; it goes on long enough to be repellent. Things
get confusing, too, in terms of the characters' interaction with each other.
We never see Romeo and Gavin fall out, for example, but halfway through the
movie they suddenly start avoiding each other, then start speaking awkwardly,
and finally become mates again. Eh?

Each scene is involving in itself, whether funny, creepy, or whatever, but
the movie as a put-together whole doesn't go anywhere or make a whole lot of
sense. Is there a point to this juxtaposition of dark terror and light
humour? The director is Shane Meadows, whose feature debut was the excellent
"TwentyFourSeven" (1998), a straightforward, moving story of a boxing
instructor helping the kids in his area stay on the straight and narrow.
We'll have to take "A Room for Romeo Brass" as a case of the Sophomore Slump
-- the jinx that often affects directors of terrific first films, making
their second ones muddled and odd.

COPYRIGHT(c) 2000 Ian Waldron-Mantgani

Please visit, and encourage others to visit, the UK Critic's website, which
is located at http://members.aol.com/ukcritic

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Grammar.Repeatable.Maximal (Alternet Parsing 1.0 API)</title>
<meta name="date" content="2020-01-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

ml.alternet.parser

Interface Grammar.Repeatable.Maximal

All Known Implementing Classes:

Grammar.AtMost, Grammar.Bounds, Grammar.Optional

Enclosing class:

Grammar.Repeatable

public static interface Grammar.Repeatable.Maximal

For repeatable rules that must be repeated a maximal number of times.

Author:

Philippe Poulard

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

int
getMaximal()

Get the maximal number of repetition.

Method Detail

getMaximal

int getMaximal()

Get the maximal number of repetition.

Returns:

An int greater than 2, or 0 (by default, a rule occurs 1).

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2020 Alternet. All rights reserved.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace MangaReader.PicLoadMethods {
    public abstract class PicLoadMethod {

        protected bool isTouched; //A simple flag which tells if one of the windows has requested a picture from the preloader.

        abstract public Image getImage(int position); //Responsible for returning Image.
        abstract public void LoadImages(int postion); //Is the initialization procedure some methods choose to use to load in some images first.

        public bool isTouch {
            get {
                return isTouched;
            }
        }
    }
}


text:
"""
Generates a shiny new IOTA address that you can use for transfers!
"""

from argparse import ArgumentParser
from getpass import getpass as secure_input
from sys import argv
from typing import Optional, Text

from iota import Iota, __version__
from iota.crypto.addresses import AddressGenerator
from iota.crypto.types import Seed

def main(uri, index, count, security, checksum):
    # type: (Text, int, Optional[int], Optional[int], bool) -> None
    seed = get_seed()

    # Create the API instance.
    # Note: If ``seed`` is null, a random seed will be generated.
    api = Iota(uri, seed)

    # If we generated a random seed, then we need to display it to the
    # user, or else they won't be able to use their new addresses!
    if not seed:
        print('A random seed has been generated. Press return to see it.')
        output_seed(api.seed)

    print('Generating addresses.  This may take a few minutes...')
    print('')

    # Here's where all the magic happens!
    api_response = api.get_new_addresses(index, count, security, checksum)
    for addy in api_response['addresses']:
        print(bytes(addy).decode('ascii'))

    print('')

def get_seed():
    # type: () -> bytes
    """
    Prompts the user securely for their seed.
    """
    print(
        'Enter seed and press return (typing will not be shown).  '
        'If empty, a random seed will be generated and displayed on the screen.'
    )
    seed = secure_input('')  # type: Text
    return seed.encode('ascii')

def output_seed(seed):
    # type: (Seed) -> None
    """
    Outputs the user's seed to stdout, along with lots of warnings
    about security.
    """
    print(
        'WARNING: Anyone who has your seed can spend your IOTAs! '
        'Clear the screen after recording your seed!'
    )
    input('')
    print('Your seed is:')
    print('')
    print(bytes(seed).decode('ascii'))
    print('')

    print(
        'Clear the screen to prevent shoulder surfing, '
        'and press return to continue.'
    )
    print('https://en.wikipedia.org/wiki/Shoulder_surfing_(computer_security)')
    input('')

if __name__ == '__main__':
    parser = ArgumentParser(
        description=__doc__,
        epilog='PyOTA v{version}'.format(version=__version__),
    )

    parser.add_argument(
        '--uri',
        type=str,
        default='http://localhost:14265/',

        help=(
            'URI of the node to connect to '
            '(defaults to http://localhost:14265/).'
        ),
    )

    parser.add_argument(
        '--index',
        type=int,
        default=0,
        help='Index of the key to generate.',
    )

    parser.add_argument(
        '--count',
        type=int,
        default=None,

        help=(
            'Number of addresses to generate. '
            'If not specified, the first unused address will be returned.'
        ),
    )

    parser.add_argument(
        '--security',
        type=int,
        default=AddressGenerator.DEFAULT_SECURITY_LEVEL,
        help=(
            'Security level to be used for the private key / address. '
            'Can be 1, 2 or 3'
        ),
    )

    parser.add_argument(
        '--with-checksum',
        action='store_true',
        default=False,
        dest='checksum',
        help='List the address with the checksum.',
    )

    main(**vars(parser.parse_args(argv[1:])))


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kernel_alpha.x86.Intrinsic;

namespace Kernel_alpha.x86
{
    public static class PIC
    {
        private const byte PIC1_Command = 0x20;
        private const byte PIC2_Command = 0xA0;

        private const byte PIC1_Data = 0x21;
        private const byte PIC2_Data = 0xA1;

        private const byte ICW1_ICW4 = 0x01;
        private const byte ICW1_SingleCascadeMode = 0x02;
        private const byte ICW1_Interval4 = 0x04;
        private const byte ICW1_LevelTriggeredEdgeMode = 0x08;
        private const byte ICW1_Initialization = 0x10;
        private const byte ICW2_MasterOffset = 0x20;
        private const byte ICW2_SlaveOffset = 0x28;
        private const byte ICW4_8086 = 0x01;
        private const byte ICW4_AutoEndOfInterrupt = 0x02;
        private const byte ICW4_BufferedSlaveMode = 0x08;
        private const byte ICW4_BufferedMasterMode = 0x0C;
        private const byte ICW4_SpecialFullyNested = 0x10;

        private const byte EOI = 0x20;

        public static void Setup()
        {
            Remap(0x20, 0xF9, 0x28, 0xFF);
        }

        private static void Remap(byte masterStart, byte masterMask, byte slaveStart, byte slaveMask)
        {
            Native.Out8(PIC1_Command, ICW1_Initialization + ICW1_ICW4);
            Native.Wait();
            Native.Out8(PIC2_Command, ICW1_Initialization + ICW1_ICW4);
            Native.Wait();
            Native.Out8(PIC1_Data, masterStart);
            Native.Wait();
            Native.Out8(PIC2_Data, slaveStart);
            Native.Wait();

            Native.Out8(PIC1_Data, 4);
            Native.Wait();
            Native.Out8(PIC2_Data, 2);
            Native.Wait();

            // set modes:
            Native.Out8(PIC1_Data, ICW4_8086);
            Native.Wait();
            Native.Out8(PIC2_Data, ICW4_8086);
            Native.Wait();

            // set masks:
            Native.Out8(PIC1_Data, masterMask);
            Native.Wait();
            //Native.Out8(PIC2_Data, slaveMask);
            //Native.Wait();
        }

        public static void SendEndOfInterrupt(byte irq)
        {
            if (irq >= 40) // or untranslated IRQ >= 8
                Native.Out8(PIC2_Command, EOI);

            Native.Out8(PIC1_Command, EOI);
        }

        public static void ClearMask(ushort IRQline)
        {
            ushort port;
            byte value;

            if (IRQline < 8)
            {
                port = 0x20 + 1;
            }
            else
            {
                port = 0xA0 + 1;
                IRQline -= 8;
            }
            value = (byte)(Native.In8(port) & ~(1 << IRQline));
            Native.Out8(port, value);
        }
    }
}


text:
//
// Rest.xaml.cpp
// Implementation of the Rest class
//

#include "pch.h"
#include "Rest.xaml.h"

using namespace CrossCppWPApp;
using namespace RestApiSpace;

using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

Rest::Rest()
{
	InitializeComponent();
	SetValue(_defaultViewModelProperty, ref new Platform::Collections::Map<String^, Object^>(std::less<String^>()));
	auto navigationHelper = ref new Common::NavigationHelper(this);
	SetValue(_navigationHelperProperty, navigationHelper);
	navigationHelper->LoadState += ref new Common::LoadStateEventHandler(this, &Rest::LoadState);
	navigationHelper->SaveState += ref new Common::SaveStateEventHandler(this, &Rest::SaveState);

	rest = new RestApi();
	publisher = ref new Publisher();

	publisher->FireEvent +=
		ref new CustomEventHandler(
			this,
			&Rest::MyEventHandler);
}

DependencyProperty^ Rest::_defaultViewModelProperty =
DependencyProperty::Register("DefaultViewModel",
TypeName(IObservableMap<String^, Object^>::typeid), TypeName(Rest::typeid), nullptr);

/// <summary>
/// Used as a trivial view model.
/// </summary>
IObservableMap<String^, Platform::Object^>^ Rest::DefaultViewModel::get()
{
	return safe_cast<IObservableMap<String^, Object^>^>(GetValue(_defaultViewModelProperty));
}

DependencyProperty^ Rest::_navigationHelperProperty =
DependencyProperty::Register("NavigationHelper",
TypeName(Common::NavigationHelper::typeid), TypeName(Rest::typeid), nullptr);

/// <summary>
/// Gets an implementation of <see cref="NavigationHelper"/> designed to be
/// used as a trivial view model.
/// </summary>
Common::NavigationHelper^ Rest::NavigationHelper::get()
{
	return safe_cast<Common::NavigationHelper^>(GetValue(_navigationHelperProperty));
}

#pragma region Navigation support

/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
///
/// Page specific logic should be placed in event handlers for the
/// <see cref="NavigationHelper::LoadState"/>
/// and <see cref="NavigationHelper::SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.

void Rest::OnNavigatedTo(NavigationEventArgs^ e)
{
	NavigationHelper->OnNavigatedTo(e);
}

void Rest::OnNavigatedFrom(NavigationEventArgs^ e)
{
	NavigationHelper->OnNavigatedFrom(e);
}

#pragma endregion

/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
void Rest::LoadState(Object^ sender, Common::LoadStateEventArgs^ e)
{
	(void) sender;	// Unused parameter
	(void) e;	// Unused parameter
}

/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache.  Values must conform to the serialization
/// requirements of <see cref="SuspensionManager::SessionState"/>.
/// </summary>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
void Rest::SaveState(Object^ sender, Common::SaveStateEventArgs^ e){
	(void) sender;	// Unused parameter
	(void) e; // Unused parameter
}

void Rest::MyEventHandler(Publisher^ mc, size_t nativeClassPtr)
{
	void *ptr = (void*)nativeClassPtr;
	Event* evnt = (Event*)ptr;
	switch (evnt->type)
	{
	case Event::EventType::PostComment:
		rest->PostComment(dynamic_cast<PostCommentEvent*>(evnt)->getComment());
		break;
		/*case Event::EventType::LastTweetLoaded:
		string str = dynamic_cast<LastTweetLoadedEvent*>(evnt)->getTweet();
		wstring wid_str = wstring(str.begin(), str.end());
		const wchar_t* w_char = wid_str.c_str();
		Platform::String^ p_string = ref new Platform::String(w_char);
		break;*/
	}
}

void CrossCppWPApp::Rest::btnPost_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
	publisher->PostComment(txtComment->Text, txtEmail->Text);
}


text: A JavaScript tool to animate SVG paths drawing.


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /var/www/symfony2/src/Blogger/BlogBundle</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../../css/bootstrap.min.css" rel="stylesheet">
  <link href="../../css/style.css" rel="stylesheet">

/var/www/symfony2/src

Blogger

BlogBundle

(Dashboard)

Code Coverage

Lines

Functions and Methods

Classes and Traits

      Total

           52.22% covered (warning)

52.22%

212 / 406

           68.42% covered (warning)

68.42%

52 / 76

           33.33% covered (danger)

33.33%

5 / 15

       Controller

           90.14% covered (success)

90.14%

64 / 71

           50.00% covered (warning)

50.00%

4 / 8

           0.00% covered (danger)

0.00%

0 / 3

       DataFixtures

           0.00% covered (danger)

0.00%

0 / 152

           0.00% covered (danger)

0.00%

0 / 4

           0.00% covered (danger)

0.00%

0 / 2

       DependencyInjection

           0.00% covered (danger)

0.00%

0 / 11

           0.00% covered (danger)

0.00%

0 / 2

           0.00% covered (danger)

0.00%

0 / 2

       Entity

           75.00% covered (warning)

75.00%

66 / 88

           72.92% covered (warning)

72.92%

35 / 48

           33.33% covered (danger)

33.33%

1 / 3

       Form

           100.00% covered (success)

100.00%

13 / 13

           100.00% covered (success)

100.00%

5 / 5

           100.00% covered (success)

100.00%

2 / 2

       Repository

           100.00% covered (success)

100.00%

47 / 47

           100.00% covered (success)

100.00%

6 / 6

           100.00% covered (success)

100.00%

2 / 2

       Twig

           91.67% covered (success)

91.67%

22 / 24

           66.67% covered (warning)

66.67%

2 / 3

           0.00% covered (danger)

0.00%

0 / 1

Legend

     Low: 0% to 50%
     Medium: 50% to 90%
     High: 90% to 100%

     Generated by PHP_CodeCoverage 2.0.10 using PHP 5.5.9-1ubuntu4.3 and PHPUnit 4.2.0 at Sun Aug 17 18:20:54 EEST 2014.


text:
typedef struct
{
	double value;
	int index;
}INDEXED_FLOAT;

//Quicksort an array in real values, in ascending order
void QuicksortF(double *a, int lo, int hi);

//Quicksort an indexed array, in ascending order
void QuicksortIndexedArray(INDEXED_FLOAT *a, int lo, int hi);

//BTreeSearchingF: Searching value in array, which was organized in ascending order previously
int  bTreeSearchingF(double value, double *a, int lo, int hi);

//Rank the values in a float array and store the rank values in an integer array
void Ranking(int *rank, double *values, int sampleNum);

//Normal score transform
int NormalTransform(double *destA, int *rank, int sampleNum);

//Compute distance correlation. dim: number of samples; inputNum: number of variables in the input; input: the input array with inputNum*dim items; output: the output array
double ComputeDistanceCorrelation(double *input, double *output, int inputNum, int dim);

//Pearson correlation
double PearsonCorrel(double *a, double *b, int dim);

//Partial correlation
double PartialCorrel(double *a, double *b, double *control, int dim);

//Randomly permute an array of float values
void PermuteFloatArrays(double *a, int size);

//Compute CDF of a non-central beta distribution. when lambda is 0.0, it's cpf of beta distribution
double BetaNoncentralCdf(double a, double b, double lambda, double x, double error_max);


text:
    <link href="http://cdnjs.cloudflare.com/ajax/libs/foundicons/3.0.0/foundation-icons.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="../assets/css/foundation.css" rel="stylesheet" />

Responsive Menu - Accordion (with submenu toggle) to Dropdown:

                Item 1 (external)

Item 1A (external)

                    Item 1B

                Item 2

Item 2A

                    Item 2B

Item 2BA (external)

                      Item 2BB


text:
#region BSD License

#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;

/// <summary>
/// Helpers for easily invoking via the <see cref="Dispatcher"/> using
/// an <see cref="Action"/> or a <see cref="Func{T}"/> delegate or lambda.
/// </summary>
///	<nuget id="netfx-System.Windows.Threading.DispatcherInvokeExtensions" />
internal static partial class DispatcherInvokeExtensions
{
	/// <summary>
	/// Executes the specified delegate asynchronously with the specified arguments
	///	on the thread that the System.Windows.Threading.Dispatcher was created on.
	/// </summary>
	/// <param name="dispatcher" this="true">The dispatcher to invoke the action on.</param>
	/// <param name="action">The action to execute via the dispatcher.</param>
	public static void BeginInvoke(this Dispatcher dispatcher, Action action)
	{
		Guard.NotNull(() => dispatcher, dispatcher);
		Guard.NotNull(() => action, action);

		dispatcher.BeginInvoke((Delegate)action);
	}

	/// <summary>
	/// Executes the specified delegate asynchronously with the specified arguments
	/// on the thread that the System.Windows.Threading.Dispatcher was created on.
	/// </summary>
	/// <param name="dispatcher" this="true">The dispatcher to invoke the action on.</param>
	/// <param name="action">The action to execute via the dispatcher.</param>
	/// <param name="priority">The priority to execute the action with.</param>
	public static void BeginInvoke(this Dispatcher dispatcher, Action action, DispatcherPriority priority)
	{
		Guard.NotNull(() => dispatcher, dispatcher);
		Guard.NotNull(() => action, action);

		dispatcher.BeginInvoke((Delegate)action, priority);
	}

	/// <summary>
	/// Executes the specified delegate with the specified arguments synchronously
	///	on the thread the System.Windows.Threading.Dispatcher is associated with.
	/// </summary>
	/// <param name="dispatcher" this="true">The dispatcher to invoke the action on.</param>
	/// <param name="action">The action to execute via the dispatcher.</param>
	public static void Invoke(this Dispatcher dispatcher, Action action)
	{
		Guard.NotNull(() => dispatcher, dispatcher);
		Guard.NotNull(() => action, action);

		dispatcher.Invoke((Delegate)action);
	}

	/// <summary>
	/// Executes the specified delegate with the specified arguments synchronously
	///	on the thread the System.Windows.Threading.Dispatcher is associated with.
	/// </summary>
	/// <param name="dispatcher" this="true">The dispatcher to invoke the action on.</param>
	/// <param name="action">The action to execute via the dispatcher.</param>
	/// <param name="priority">The priority to execute the action with.</param>
	public static void Invoke(this Dispatcher dispatcher, Action action, DispatcherPriority priority)
	{
		Guard.NotNull(() => dispatcher, dispatcher);
		Guard.NotNull(() => action, action);

		dispatcher.Invoke((Delegate)action, priority);
	}

	/// <summary>
	/// Executes the specified delegate with the specified arguments synchronously
	///	on the thread the System.Windows.Threading.Dispatcher is associated with.
	/// </summary>
	/// <param name="dispatcher" this="true">The dispatcher to invoke the action on.</param>
	/// <param name="action">The action to execute via the dispatcher.</param>
	/// <returns>The return value from the delegate being invoked</returns>
	public static T Invoke<T>(this Dispatcher dispatcher, Func<T> action)
	{
		Guard.NotNull(() => dispatcher, dispatcher);
		Guard.NotNull(() => action, action);

		return (T)dispatcher.Invoke((Delegate)action);
	}

	/// <summary>
	/// Executes the specified delegate with the specified arguments synchronously
	///	on the thread the System.Windows.Threading.Dispatcher is associated with.
	/// </summary>
	/// <param name="dispatcher" this="true">The dispatcher to invoke the action on.</param>
	/// <param name="action">The action to execute via the dispatcher.</param>
	/// <param name="priority">The priority to execute the action with.</param>
	/// <returns>The return value from the delegate being invoked</returns>
	public static T Invoke<T>(this Dispatcher dispatcher, Func<T> action, DispatcherPriority priority)
	{
		Guard.NotNull(() => dispatcher, dispatcher);
		Guard.NotNull(() => action, action);

		return (T)dispatcher.Invoke((Delegate)action, priority);
	}
}


text:
package com.amazonaws.services.ec2.model;

/**
 *

 * The SpotDatafeedSubscriptionType data type.
 *

 */
public class SpotDatafeedSubscription {

    /**
     * Specifies the AWS account ID of the account.
     */
    private String ownerId;

    /**
     * Specifies the Amazon S3 bucket where the Spot Instance data feed is
     * located.
     */
    private String bucket;

    /**
     * Contains the prefix that is prepended to data feed files.
     */
    private String prefix;

    /**
     * Specifies the state of the Spot Instance request.
     */
    private String state;

    /**
     * Specifies a fault code for the Spot Instance request, if present.
     */
    private SpotInstanceStateFault fault;

    /**
     * Specifies the AWS account ID of the account.
     *
     * @return Specifies the AWS account ID of the account.
     */
    public String getOwnerId() {
        return ownerId;
    }

    /**
     * Specifies the AWS account ID of the account.
     *
     * @param ownerId Specifies the AWS account ID of the account.
     */
    public void setOwnerId(String ownerId) {
        this.ownerId = ownerId;
    }

    /**
     * Specifies the AWS account ID of the account.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param ownerId Specifies the AWS account ID of the account.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public SpotDatafeedSubscription withOwnerId(String ownerId) {
        this.ownerId = ownerId;
        return this;
    }

    /**
     * Specifies the Amazon S3 bucket where the Spot Instance data feed is
     * located.
     *
     * @return Specifies the Amazon S3 bucket where the Spot Instance data feed is
     *         located.
     */
    public String getBucket() {
        return bucket;
    }

    /**
     * Specifies the Amazon S3 bucket where the Spot Instance data feed is
     * located.
     *
     * @param bucket Specifies the Amazon S3 bucket where the Spot Instance data feed is
     *         located.
     */
    public void setBucket(String bucket) {
        this.bucket = bucket;
    }

    /**
     * Specifies the Amazon S3 bucket where the Spot Instance data feed is
     * located.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param bucket Specifies the Amazon S3 bucket where the Spot Instance data feed is
     *         located.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public SpotDatafeedSubscription withBucket(String bucket) {
        this.bucket = bucket;
        return this;
    }

    /**
     * Contains the prefix that is prepended to data feed files.
     *
     * @return Contains the prefix that is prepended to data feed files.
     */
    public String getPrefix() {
        return prefix;
    }

    /**
     * Contains the prefix that is prepended to data feed files.
     *
     * @param prefix Contains the prefix that is prepended to data feed files.
     */
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    /**
     * Contains the prefix that is prepended to data feed files.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param prefix Contains the prefix that is prepended to data feed files.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public SpotDatafeedSubscription withPrefix(String prefix) {
        this.prefix = prefix;
        return this;
    }

    /**
     * Specifies the state of the Spot Instance request.
     *
     * @return Specifies the state of the Spot Instance request.
     */
    public String getState() {
        return state;
    }

    /**
     * Specifies the state of the Spot Instance request.
     *
     * @param state Specifies the state of the Spot Instance request.
     */
    public void setState(String state) {
        this.state = state;
    }

    /**
     * Specifies the state of the Spot Instance request.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param state Specifies the state of the Spot Instance request.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public SpotDatafeedSubscription withState(String state) {
        this.state = state;
        return this;
    }

    /**
     * Specifies a fault code for the Spot Instance request, if present.
     *
     * @return Specifies a fault code for the Spot Instance request, if present.
     */
    public SpotInstanceStateFault getFault() {
        return fault;
    }

    /**
     * Specifies a fault code for the Spot Instance request, if present.
     *
     * @param fault Specifies a fault code for the Spot Instance request, if present.
     */
    public void setFault(SpotInstanceStateFault fault) {
        this.fault = fault;
    }

    /**
     * Specifies a fault code for the Spot Instance request, if present.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param fault Specifies a fault code for the Spot Instance request, if present.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public SpotDatafeedSubscription withFault(SpotInstanceStateFault fault) {
        this.fault = fault;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("OwnerId: " + ownerId + ", ");
        sb.append("Bucket: " + bucket + ", ");
        sb.append("Prefix: " + prefix + ", ");
        sb.append("State: " + state + ", ");
        sb.append("Fault: " + fault + ", ");
        sb.append("}");
        return sb.toString();
    }

}


text:
// Copyright (c) 2010-2015, Shane Jarych
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of lib65oh2 nor the names of its contributors may be used
//   to endorse or promote products derived from this software without specific
//   prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef ABSOLUTEYFETCHPOLICY_H
#define ABSOLUTEYFETCHPOLICY_H

#include "Core.h"
#include "MemoryController.h"
#include "OperandFetchPolicy.h"
#include "CPUTypes.h"
#include "BitUtils.h"

/**
 * @class  AbsoluteYFetchPolicy
 * @brief  A FetchPolicy implementation for absolute addressing by way of
 *         the Y register
 *
 * @tparam FetchedDataType  The type of the data fetched
 *
 * @author Shane Jarych
 */
template <class FetchedDataType>
class AbsoluteYFetchPolicy
    : public OperandFetchPolicy<data16_t>
{
public:
    AbsoluteYFetchPolicy()
        : OperandFetchPolicy<data16_t>()
    {
    }

    /**
     * @brief  Using the operand as a base address, perform an absolute
     *         fetch using Y as an offset to the low byte of the operand
     *         address.
     *
     * @param[in]   core         The Core reference for obtaining cpu values
     * @param[in]   memory       The MemoryController reference for obtaining data
     * @param[out]  fetchedData  The fetched data
     * @return                   The number of cycles to perform the operation
     */
    int fetch(Core& core, MemoryController& memory, FetchedDataType** fetchedData)
    {
        // fetch the 16bit operand
        const data16_t* operand = fetchOperand(core, memory);

        // absolutely fetch the data, indexed by Y
        addr16_t calcAddr = 0;

        const addr8_t lowOp = BitUtils::getAddr8(*operand, BitUtils::LOW);
        const addr8_t adjLowOp = lowOp + core.getY();
        BitUtils::setAddr8(calcAddr, adjLowOp, BitUtils::LOW);

        const addr8_t highOp = BitUtils::getAddr8(*operand, BitUtils::HIGH);
        const addr8_t carry = (adjLowOp < lowOp) ? 1 : 0;
        BitUtils::setAddr8(calcAddr, highOp + carry, BitUtils::HIGH);

        *fetchedData = reinterpret_cast<FetchedDataType*>(memory.get(calcAddr));

        return carry;
    }
};

#endif // ABSOLUTEYFETCHPOLICY_H


text:
function(modal) {
    modal.respond('embedVideoChosen', {{ embed_video_json|safe }});
    modal.close();
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/netwerk/socket/nsISocketProviderService.idl
 */

#ifndef __gen_nsISocketProviderService_h__
#define __gen_nsISocketProviderService_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsISocketProvider; /* forward declaration */

/* starting interface:    nsISocketProviderService */
#define NS_ISOCKETPROVIDERSERVICE_IID_STR "8f8a23d0-5472-11d3-bbc8-0000861d1237"

#define NS_ISOCKETPROVIDERSERVICE_IID \
  {0x8f8a23d0, 0x5472, 0x11d3, \
    { 0xbb, 0xc8, 0x00, 0x00, 0x86, 0x1d, 0x12, 0x37 }}

/**
 * nsISocketProviderService
 *
 * Provides a mapping between a socket type and its associated socket provider
 * instance.  One could also use the service manager directly.
 */
class NS_NO_VTABLE NS_SCRIPTABLE nsISocketProviderService : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISOCKETPROVIDERSERVICE_IID)

  /* nsISocketProvider getSocketProvider (in string socketType); */
  NS_SCRIPTABLE NS_IMETHOD GetSocketProvider(const char *socketType, nsISocketProvider **_retval NS_OUTPARAM) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsISocketProviderService, NS_ISOCKETPROVIDERSERVICE_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISOCKETPROVIDERSERVICE \
  NS_SCRIPTABLE NS_IMETHOD GetSocketProvider(const char *socketType, nsISocketProvider **_retval NS_OUTPARAM);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISOCKETPROVIDERSERVICE(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetSocketProvider(const char *socketType, nsISocketProvider **_retval NS_OUTPARAM) { return _to GetSocketProvider(socketType, _retval); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISOCKETPROVIDERSERVICE(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetSocketProvider(const char *socketType, nsISocketProvider **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSocketProvider(socketType, _retval); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsSocketProviderService : public nsISocketProviderService
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSISOCKETPROVIDERSERVICE

  nsSocketProviderService();

private:
  ~nsSocketProviderService();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsSocketProviderService, nsISocketProviderService)

nsSocketProviderService::nsSocketProviderService()
{
  /* member initializers and constructor code */
}

nsSocketProviderService::~nsSocketProviderService()
{
  /* destructor code */
}

/* nsISocketProvider getSocketProvider (in string socketType); */
NS_IMETHODIMP nsSocketProviderService::GetSocketProvider(const char *socketType, nsISocketProvider **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsISocketProviderService_h__ */


text:
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)

package edu.wustl.catissuecore.domainobject.impl;

import edu.wustl.catissuecore.domainobject.*;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.*;

// Referenced classes of package edu.wustl.catissuecore.domainobject.impl:
//            SpecimenEventParametersImpl

public class DistributionImpl extends SpecimenEventParametersImpl
    implements Serializable, Distribution
{

    public DistributionImpl()
    {
        distributedItemCollection = new HashSet();
    }

    public String getActivityStatus()
    {
        return activityStatus;
    }

    public void setActivityStatus(String s)
    {
        activityStatus = s;
    }

    public Collection getDistributedItemCollection()
    {

        return distributedItemCollection;
    }

    public void setDistributedItemCollection(Collection collection)
    {
        distributedItemCollection = collection;
    }

    public DistributionProtocol getDistributionProtocol()
    {

        return distributionProtocol;
    }

    public void setDistributionProtocol(DistributionProtocol distributionprotocol)
    {
        distributionProtocol = distributionprotocol;
    }

    public Site getToSite()
    {

        return toSite;
    }

    public void setToSite(Site site)
    {
        toSite = site;
    }

    public boolean equals(Object obj)
    {
        boolean flag = false;
        if(obj instanceof Distribution)
        {
            Distribution distribution = (Distribution)obj;
            Long long1 = getId();
            if(long1 != null && long1.equals(distribution.getId()))
                flag = true;
        }
        return flag;
    }

    public int hashCode()
    {
        int i = 0;
        if(getId() != null)
            i += getId().hashCode();
        return i;
    }

    private static final long serialVersionUID = 0x499602d2L;
    protected String activityStatus;
    private Collection distributedItemCollection;
    private DistributionProtocol distributionProtocol;
    private Site toSite;
}


text:
using SmartSql.Abstractions.DbSession;
using System;
using System.Collections.Generic;
using System.Text;

namespace SmartSql.Abstractions.DataSource
{
    /// <summary>
    /// 数据源筛选器
    /// </summary>
    public interface IDataSourceFilter
    {
        IDataSource Elect(RequestContext context);
    }
}


text:
module Tokaido
  module DNS
    class Table
      def initialize
        @table = Hash.new { |h,k| h[k] = {} }
      end

      def add(type, domain, *payload)
        @table[type][domain] = payload
      end

      def remove(type, domain)
        type = normalize(type)
        @table[type].delete(domain)
      end

      def lookup(type, domain)
        type = normalize(type)
        @table[type][domain]
      end

    private
      def normalize(type)
        return type if type.is_a?(String)

        TYPES[type]
      end
    end
  end
end


text:
module Gitlab
  module Graphql
    StandardGraphqlError = Class.new(StandardError)

    def self.enabled?
      Feature.enabled?(:graphql, default_enabled: true)
    end
  end
end


text:
package model

type Pull struct {
	SeasonID int64 `json:"season_id"`
	Ts       int64 `json:"ts"`
}


text:
if [ -z "$containers" ]; then
 # info "     * No containers running, skipping Section 5"
./docker-bench-security-logging.sh "$check" "$check_description" "info" "No containers running, skipping Check Section No 5"
	else
  # Make the loop separator be a new-line in POSIX compliant fashion
  set -f; IFS=$'
'
  # 5.1
  check_5_1="5.1  - Verify AppArmor Profile, if applicable"
  check=$(echo $check_5_1 | cut -d "-" -f 1)
  check_description=$(echo $check_5_1 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    policy=$(docker inspect --format 'AppArmorProfile={{ .AppArmorProfile }}' "$c")

    if [ "$policy" = "AppArmorProfile=" -o "$policy" = "AppArmorProfile=[]" -o "$policy" = "AppArmorProfile=<no value>" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
        ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "No AppArmorProfile Found: $c"
#	warn "$check_5_1"
#        warn "     * No AppArmorProfile Found: $c"
        fail=1
      else
        ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "No AppArmorProfile Found: $c"
#        warn "     * No AppArmorProfile Found: $c"
      fi
    fi
  done
 # We went through all the containers and found none without AppArmor
  if [ $fail -eq 0 ]; then
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "All containers are running with AppArmorProfile"
 #  pass "$check_5_1"
  fi

# 5.2
  check_5_2="5.2  - Verify SELinux security options, if applicable"
  check=$(echo $check_5_2 | cut -d "-" -f 1)
  check_description=$(echo $check_5_2 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    policy=$(docker inspect --format 'SecurityOpt={{ .HostConfig.SecurityOpt }}' "$c")

    if [ "$policy" = "SecurityOpt=" -o "$policy" = "SecurityOpt=[]" -o "$policy" = "SecurityOpt=<no value>" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
   #     warn "$check_5_2"
   #     warn "     * No SecurityOptions Found: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "No SecurityOptions Found: $c"
   fail=1
      else
   #     warn "     * No SecurityOptions Found: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "No SecurityOptions Found: $c"
      fi
    fi
  done
  # We went through all the containers and found none without SELinux
  if [ $fail -eq 0 ]; then
#      pass "$check_5_2"
./docker-bench-security-logging.sh "$check" "$check_description" "pass"  "All containers are running with SELinux security options"
 fi

 # 5.3
  check_5_3="5.3  - Verify that containers are running only a single main process"
  check=$(echo $check_5_3 | cut -d "-" -f 1)
  check_description=$(echo $check_5_3 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
#  printcheck=0
  for c in $containers; do
    processes=$(docker exec "$c" ps -el 2>/dev/null | tail -n +2 | grep -c -v "ps -el")
    if [ "$processes" -gt 1 ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
      #  warn "$check_5_3"
     #   warn "     * Too many proccesses running: $c"
      ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Too many proccesses running: $c"
	  fail=1
 #       printcheck=1
      else
      #  warn "     * Too many proccesses running: $c"
      ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Too many proccesses running: $c"
	fi
    fi

    exec_check=$(docker exec "$c" ps -el 2>/dev/null)
    if [ $? -eq 255 ]; then
#        if [ $printcheck -eq 0 ]; then
#          warn "$check_5_3"
#          printcheck=1
#        fi
    #  warn "     * Docker exec fails: $c"
    ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Docker exec fails: $c"
	  fail=1
    fi

  done
  # We went through all the containers and found none with toom any processes
  if [ $fail -eq 0 ]; then
    #  pass "$check_5_3"
  ./docker-bench-security-logging.sh "$check" "$check_description" "pass" "All containers are running only a single main process"
	fi

# 5.4
  check_5_4="5.4  - Restrict Linux Kernel Capabilities within containers"
   check=$(echo $check_5_4 | cut -d "-" -f 1)
  check_description=$(echo $check_5_4 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

 fail=0
  for c in $containers; do
    caps=$(docker inspect --format 'CapAdd={{ .HostConfig.CapAdd}}' "$c")

    if [ "$caps" != 'CapAdd=' -a "$caps" != 'CapAdd=[]' -a "$caps" != 'CapAdd=<no value>' -a "$caps" != 'CapAdd=<nil>' ]; then
      # If it's the first container, fail the test
  #    if [ $fail -eq 0 ]; then
    #    warn "$check_5_4"
    #    warn "     * Capabilities added: $caps to $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Capabilities added: $caps $c"
        fail=1
 #     else
 #       warn "     * Capabilities added: $caps to $c"
#	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Capabilities added: $caps $c"
  #    fi
    fi
  done
  # We went through all the containers and found none with extra capabilities
  if [ $fail -eq 0 ]; then
      # pass "$check_5_4"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "All containers are running by defaul Capabilities"
  fi

# 5.5
  check_5_5="5.5  - Do not use privileged containers"
check=$(echo $check_5_5 | cut -d "-" -f 1)
  check_description=$(echo $check_5_5 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    privileged=$(docker inspect --format '{{ .HostConfig.Privileged }}' "$c")

    if [ "$privileged" = "true" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
     #   warn "$check_5_5"
     #   warn "     * Container running in Privileged mode: $c"
      ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running in Privileged mode: $c"
	  fail=1
      else
     #   warn "     * Container running in Privileged mode: $c"
     ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running in Privileged mode: $c"
	 fi
    fi
  done
  # We went through all the containers and found no privileged containers
  if [ $fail -eq 0 ]; then
   #   pass "$check_5_5"
  ./docker-bench-security-logging.sh "$check" "$check_description" "pass" "No container is running in Privileged mode"
	fi

 # 5.6
  check_5_6="5.6  - Do not mount sensitive host system directories on containers"
  check=$(echo $check_5_6 | cut -d "-" -f 1)
  check_description=$(echo $check_5_6 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  # List of sensitive directories to test for. Script uses new-lines as a separator.
  # Note the lack of identation. It needs it for the substring comparison.
  sensitive_dirs='etc
boot
dev
lib
proc
sys
usr
.*'
  fail=0
#  containersq=$(docker ps -q | sed '1d' | awk '{print $NF}')
  for c in $containers; do
    volumes=$(docker inspect --format "{{ .Config.Volumes }}" "$c")
    # Go over each directory in sensitive dir and see if they exist in the volumes
    for v in $sensitive_dirs; do
      sensitive=0
      contains "$volumes" "$v:" && sensitive=1
      if [ $sensitive -eq 1 ]; then
        # If it's the first container, fail the test
        if [ $fail -eq 0 ]; then
      #    warn "$check_5_6"
      #    warn "     * Sensitive directory $v mounted in: $c"
       ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Sensitive directory $v mounted in: $c"
	   fail=1
        else
      #    warn "     * Sensitive directory $v mounted in: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Sensitive directory $v mounted in: $c"
        fi
      fi
    done
  done
  # We went through all the containers and found none with sensitive mounts
  if [ $fail -eq 0 ]; then
    #  pass "$check_5_6"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "No container has mount sensitive host system directories"
  fi

# 5.7
  check_5_7="5.7  - Do not run ssh within containers"
  check=$(echo $check_5_7 | cut -d "-" -f 1)
  check_description=$(echo $check_5_7 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  printcheck=0
  for c in $containers; do

    processes=$(docker exec "$c" ps -el 2>/dev/null | grep -c sshd | awk '{print $1}')
    if [ "$processes" -ge 1 ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
      #  warn "$check_5_7"
      #  warn "     * Container running sshd: $c"
       ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running sshd: $c"
	 fail=1
        printcheck=1
      else
     #   warn "     * Container running sshd: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running sshd: $c"
      fi
    fi

    exec_check=$(docker exec "$c" ps -el 2>/dev/null)
    if [ $? -eq 255 ]; then
        if [ $printcheck -eq 0 ]; then
      #    warn "$check_5_7"
          printcheck=1
        fi
   #   warn "     * Docker exec fails: $c"
     ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Docker exec fails: $c"
	  fail=1
    fi

  done
  # We went through all the containers and found none with sshd
  if [ $fail -eq 0 ]; then
   #   pass "$check_5_7"
  ./docker-bench-security-logging.sh "$check" "$check_description" "pass" "No container has sshd"
	fi

# 5.8
  check_5_8="5.8  - Do not map privileged ports within containers"
  check=$(echo $check_5_8 | cut -d "-" -f 1)
  check_description=$(echo $check_5_8 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    # Port format is private port -> ip: public port
    ports=$(docker port "$c" | awk '{print $0}' | cut -d ':' -f2)

    # iterate through port range (line delimited)
    for port in $ports; do
    if [ ! -z "$port" ] && [ "0$port" -lt 1024 ]; then
        # If it's the first container, fail the test
        if [ $fail -eq 0 ]; then
       #   warn "$check_5_8"
       #   warn "     * Privileged Port in use: $port in $c"
        ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Privileged Port in use: $port in $c"
	  fail=1
        else
        #  warn "     * Privileged Port in use: $port in $c"
        ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Privileged Port in use: $port in $c"
	fi
      fi
    done
  done
  # We went through all the containers and found no privileged ports
  if [ $fail -eq 0 ]; then
  #    pass "$check_5_8"
  ./docker-bench-security-logging.sh "$check" "$check_description" "pass" "No container has Privileged Port mapped"
	fi

# 5.9
  check_5_9="5.9 - Do not use host network mode on container"
  check=$(echo $check_5_9 | cut -d "-" -f 1)
  check_description=$(echo $check_5_9 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    mode=$(docker inspect --format 'NetworkMode={{ .HostConfig.NetworkMode }}' "$c")

    if [ "$mode" = "NetworkMode=host" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
     #   warn "$check_5_9"
     #   warn "     * Container running with networking mode 'host': $c"
     ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running with networking mode 'host': $c"
	   fail=1
      else
    #    warn "     * Container running with networking mode 'host': $c"
     ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running with networking mode 'host': $c"
	 fi
    fi
  done
  # We went through all the containers and found no Network Mode host
  if [ $fail -eq 0 ]; then
    #  pass "$check_5_9"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "No container uses host network mode"
  fi

# 5.10
  check_5_10="5.10 - Limit memory usage for container"
  check=$(echo $check_5_10 | cut -d "-" -f 1)
  check_description=$(echo $check_5_10 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    memory=$(docker inspect --format '{{ .HostConfig.Memory }}' "$c")

    if [ "$memory" = "0" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
     #   warn "$check_5_10"
     #   warn "     * Container running without memory restrictions: $c"
      ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running without memory restrictions: $c"
	  fail=1
      else
     #   warn "     * Container running without memory restrictions: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running without memory restrictions: $c"
      fi
    fi
  done
  # We went through all the containers and found no lack of Memory restrictions
  if [ $fail -eq 0 ]; then
   #   pass "$check_5_10"
  ./docker-bench-security-logging.sh "$check" "$check_description" "pass" "All containers are running with memory restrictions"
  fi

# 5.11
  check_5_11="5.11 - Set container CPU priority appropriately"
  check=$(echo $check_5_11 | cut -d "-" -f 1)
  check_description=$(echo $check_5_11 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    shares=$(docker inspect --format '{{ .HostConfig.CpuShares }}' "$c")

    if [ "$shares" = "0" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
    #    warn "$check_5_11"
    #    warn "     * Container running without CPU restrictions: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running without CPU restrictions: $c"
   fail=1
      else
     #   warn "     * Container running without CPU restrictions: $c"
      ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running without CPU restrictions: $c"
	fi
    fi
  done
  # We went through all the containers and found no lack of CPUShare restrictions
  if [ $fail -eq 0 ]; then
    #  pass "$check_5_11"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "All containers are running with proper CPU setting"
  fi

# 5.12
  check_5_12="5.12 - Mount container's root filesystem as read only"
  check=$(echo $check_5_12 | cut -d "-" -f 1)
  check_description=$(echo $check_5_12 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
   read_status=$(docker inspect --format '{{ .HostConfig.ReadonlyRootfs }}' "$c")

    if [ "$read_status" = "false" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
     #   warn "$check_5_12"
     #   warn "     * Container running with root FS mounted R/W: $c"
      ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running with root FS mounted R/W: $c"
        fail=1
      else
      #  warn "     * Container running with root FS mounted R/W: $c"
      ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container running with root FS mounted R/W: $c"
	fi
    fi
  done
  # We went through all the containers and found no R/W FS mounts
  if [ $fail -eq 0 ]; then
   #   pass "$check_5_12"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "All containers have container's root filesystem mounted as read only"
  fi

# 5.13
  check_5_13="5.13 - Bind incoming container traffic to a specific host interface"
  check=$(echo $check_5_13 | cut -d "-" -f 1)
  check_description=$(echo $check_5_13 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    for ip in $(docker port "$c" | awk '{print $3}' | cut -d ':' -f1); do
      if [ "$ip" = "0.0.0.0" ]; then
        # If it's the first container, fail the test
        if [ $fail -eq 0 ]; then
        #  warn "$check_5_13"
        #  warn "     * Port being bound to wildcard IP: $ip in $c"
        ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Port being bound to wildcard IP: $ip in $c"
	 fail=1
        else
      #    warn "     * Port being bound to wildcard IP: $ip in $c"
       ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Port being bound to wildcard IP: $ip in $c"
	 fi
      fi
    done
  done
  # We went through all the containers and found no ports bound to 0.0.0.0
  if [ $fail -eq 0 ]; then
    #  pass "$check_5_13"
    ./docker-bench-security-logging.sh "$check" "$check_description" "pass" "All containers are running without any bind to a specific host interface"
  fi

# 5.14
  check_5_14="5.14 - Do not set the 'on-failure' container restart policy to always"
  check=$(echo $check_5_14 | cut -d "-" -f 1)
  check_description=$(echo $check_5_14 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    policy=$(docker inspect --format 'RestartPolicyName={{ .HostConfig.RestartPolicy.Name }}' "$c")

    if [ "$policy" = "RestartPolicyName=always" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
     #   warn "$check_5_14"
     #   warn "     * Restart Policy set to always: $c"
        ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Restart Policy set to always: $c"
	fail=1
      else
     #   warn "     * Restart Policy set to always: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Restart Policy set to always: $c"
      fi
    fi
  done
  # We went through all the containers and found none with restart policy always
  if [ $fail -eq 0 ]; then
   #   pass "$check_5_14"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "All containers are running without restart policy"
  fi

 # 5.15
  check_5_15="5.15 - Do not share the host's process namespace"
  check=$(echo $check_5_15 | cut -d "-" -f 1)
  check_description=$(echo $check_5_15 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    mode=$(docker inspect --format 'PidMode={{.HostConfig.PidMode }}' "$c")

    if [ "$mode" = "PidMode=host" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
     #   warn "$check_5_15"
     #   warn "     * Host PID namespace being shared with: $c"
        ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Host PID namespace being shared with: $c"
	fail=1
      else
     #   warn "     * Host PID namespace being shared with: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Host PID namespace being shared with: $c"
      fi
    fi
  done
  # We went through all the containers and found none with PidMode as host
  if [ $fail -eq 0 ]; then
    #  pass "$check_5_15"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "No container is sharing host PID"
  fi

 # 5.16
  check_5_16="5.16 - Do not share the host's IPC namespace"
  check=$(echo $check_5_16 | cut -d "-" -f 1)
  check_description=$(echo $check_5_16 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    mode=$(docker inspect --format 'IpcMode={{.HostConfig.IpcMode }}' "$c")

    if [ "$mode" = "IpcMode=host" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
      #  warn "$check_5_16"
      #  warn "     * Host IPC namespace being shared with: $c"
       ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Host IPC namespace being shared with: $c"
	 fail=1
      else
      #  warn "     * Host IPC namespace being shared with: $c"
      ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Host IPC namespace being shared with: $c"
	fi
    fi
  done
  # We went through all the containers and found none with IPCMode as host
  if [ $fail -eq 0 ]; then
   #   pass "$check_5_16"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "No container is sharing the host's IPC namespace"
  fi

 # 5.17
  check_5_17="5.17 - Do not directly expose host devices to containers"
  check=$(echo $check_5_17 | cut -d "-" -f 1)
  check_description=$(echo $check_5_17 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  fail=0
  for c in $containers; do
    devices=$(docker inspect --format 'Devices={{ .HostConfig.Devices }}' "$c")

    if [ "$devices" != "Devices=" -a "$devices" != "Devices=[]" -a "$devices" != "Devices=<no value>" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
      #  info "$check_5_17"
     #   info "     * Container has devices exposed directly: $c"
       ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container has devices exposed directly: $c"
	 fail=1
      else
      #  info "     * Container has devices exposed directly: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container has devices exposed directly: $c"
      fi
    fi
  done
  # We went through all the containers and found none with devices
  if [ $fail -eq 0 ]; then
   #   pass "$check_5_17"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "No container has host devices exposed in directly"
  fi

 # 5.18
  check_5_18="5.18 - Override default ulimit at runtime only if needed"
  check=$(echo $check_5_18 | cut -d "-" -f 1)
  check_description=$(echo $check_5_18 | cut -d "-" -f 2,3 | sed -e 's/^[ \t]*//')

  # List all the running containers, ouput their ID and host devices
  fail=0
  for c in $containers; do
    ulimits=$(docker inspect --format 'Ulimits={{ .HostConfig.Ulimits }}' "$c")

    if [ "$ulimits" = "Ulimits=" -o "$ulimits" = "Ulimits=[]" -o "$ulimits" = "Ulimits=<no value>" ]; then
      # If it's the first container, fail the test
      if [ $fail -eq 0 ]; then
      #  info "$check_5_18"
      #  info "     * Container no default ulimit override: $c"
     ./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container no default ulimit override: $c"
	   fail=1
      else
      #  info "     * Container no default ulimit override: $c"
	./docker-bench-security-logging.sh "$check" "$check_description" "warn" "Container no default ulimit override: $c"
      fi
    fi
  done
  # We went through all the containers and found none without Ulimits
  if [ $fail -eq 0 ]; then
    #  pass "$check_5_18"
	./docker-bench-security-logging.sh "$check" "$check_description" "pass" "All containers have default ulimit"
  fi

fi


text:
package models;

public class Tweet {

	public int tweet_id;
	public int compte_id;
	public  java.sql.Timestamp datetweet;
	public int tweet_nb_retweet;
	public String tweet_description;

	public Tweet(int idtweet,int idcompte,java.sql.Timestamp datetweet,int nbretweet,String strtweet)
	{
		this.tweet_id=idtweet;
		this.compte_id=idcompte;
		this.datetweet=datetweet;
		this.tweet_nb_retweet=nbretweet;
		this.tweet_description=strtweet;
	}
	public Tweet(int idtweet,int nbretweet,String strtweet)
	{
		this.tweet_id=idtweet;
		this.tweet_nb_retweet=nbretweet;
		this.tweet_description=strtweet;
	}

}


text:
**Grade	25.0 (max 25.0)**

### Set-Up
* Create a new project in your Eclipse workspace named:  `Lab07`
* In the src folder, create a package named:  `edu.ilstu.it275.lab03.<ulid>`
* Import into this new package all of the following `.java` files
  - `DivideTwo.java`

### Part 1 – if/else Statement

Open the file `DivideTwo.java`.  The Java source code is shown below:

```java
package edu.ilstu;
import java.util.Scanner;

public class DivideTwo {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int numerator = 0;
        int denominator = 0;
        double quotient = 0;

        System.out.println("This program divides two numbers.");
        System.out.print("Enter the numerator:  ");
        numerator = keyboard.nextInt();

        System.out.print("Enter the denominator:  ");
        denominator = keyboard.nextInt();
        quotient = (double) numerator / denominator;

        System.out.println(numerator + "/" + denominator
+ " = " + quotient);

        keyboard.close();
    }

}
```

Compile and run `DivideTwo.java`, and observe the output.  The program prompts the user for two integers that represent the numerator and the denominator of a fraction.  The `Scanner` object named `keyboard` is used to read the integers provided by the user.

Modify the program to include an `if/else` statement to check for division by zero.  If the denominator is not equal to zero, display the result of the division, otherwise display a message to the user that division by zero is not allowed.

### Part 2 – Switch Statement

Open the provided file `SwitchErrors.java`.  The Java source code is shown below.  The program evaluates an integer entered by the user and displays the color assigned to the integer.  Compile the program.  The program has several syntax and logic errors.  Fix the syntax errors and compile and run the program.  Does the program run as you expected?  Locate and correct the errors in the program logic.  Be sure to make use of the debugger available in Eclipse to help identify errors.

```java
package edu.ilstu;

import java.util.Scanner;

public class SwitchErrors {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.out);

        System.out.println("Key:  1=blue, 2=red, 3=green");
        System.out.print("Enter a number and I'll return ");
        System.out.print(" the corresponding color.  ");
        number = keyboard.nextInt();

        switch(number) {
            case 1:
                System.out.println("You chose red!");
                break;
            case 2:
                System.out.println("You chose blue!");
                break;
            case 3:
                System.out.println("You chose green!");
            default:
                System.out.println("Color not available!");
                break;
        }
    }

}
```

### Part 3 while Loop
Open the provided file `ConvertLoop.java`

Convert the following code so that it uses nested while statements instead of for statements.  Place the new code at the end of the code in `ConvertLoop.java`.

```java
int s = 0;
int t = 1;

for (int i = 0; i < 5; i++) {
    s = s + i;
    for (int j = i; j > 0; j--)
    {
        t = t + (j-1);
    }
    s = s + t;
    System.out.println("T is " + t);
}
System.out.println("S is " + s);
```

### Part 4 – Loops from scratch

Create a class called `OddIntegers` with a main method.  Write the code that will compute the sum of the first `n` positive odd integers.  For example, if `n` is 5 you should compute 1 + 3 + 5 + 7 + 9.  Read the value for `n` from the user and display the result to the screen with an appropriate label.


text:
layout: posts.liquid

title:  All date variables
published_date:  2015-05-03 01:05:20 +0100
permalink:  /{{year}}/{{month}}/{{i_month}}/{{day}}/{{i_day}}/{{hour}}/{{minute}}/{{second}}/
---
# {{ page.title }}

This checks that all date variables are interpolated correctly into the path.


text:
'''
Created on Nov 6, 2013

@author: Ricardo Silva
'''
from pagseguro.api.v2.objects.payment_request import PaymentRequest
from pagseguro.tests.checkout import CheckoutTestCase
from unittest.case import TestCase

class PaymentRequestTestCase(TestCase):

    def setUp(self):
        payment_request = PaymentRequest()
        payment_request.email = 'vendedor@nada.com'
        payment_request.token = '12345678901234567890123456789012'

        checkout = CheckoutTestCase.build_checkout()
        payment_request.checkout = checkout
        self.payment_request = payment_request

    def test__payment(self):
        self.payment_request.validate()