text:
'use strict';

var CodestreamClientManager = (function CodestreamClientManager() {
    function CodestreamClientManager(options) {
        var serverRequestsLimit = options.serverRequestsLimit || 5;

        this._codestreamClient = new JpipCodestreamClient();
        this._showLog = options.showLog;
        this._sizesCalculator = null;

        var serverRequestScheduler = jpipImageHelperFunctions.createScheduler(
            options.showLog,
            options.serverRequestPrioritizer,
            'serverRequest',
            createServerRequestDummyResource,
            serverRequestsLimit);

        this._serverRequestPrioritizer = serverRequestScheduler.prioritizer;

        this._requestManager = new ScheduledRequestManager(
            this._codestreamClient, serverRequestScheduler.scheduler);
    }

    CodestreamClientManager.prototype = {
        setStatusCallback: function setStatusCallback(statusCallback) {
            this._codestreamClient.setStatusCallback(statusCallback);
        },

        open : function open(url) {
            this._codestreamClient.open(url);
        },

        close: function close(closedCallback) {
            this._codestreamClient.close(closedCallback);
        },

        getSizesParams: function getSizesParams() {
            var sizesParams = this._codestreamClient.getSizesParams();
            return sizesParams;
        },

        setIsProgressiveRequest: function setIsProgressiveRequest(
            requestId, isProgressive) {

            var contextVars = this._requestManager.getContextVars(requestId);
            if (contextVars !== null) {
                contextVars.isProgressive = isProgressive;
            }
        },

        createMovableRequestHandle: function createMovableRequestHandle(
            createdCallback) {

            var requestHandle = this._requestManager.createMovableRequestHandle();
            createdCallback(requestHandle);
        },

        moveRequest: function moveRequest(
            movableRequestHandle, codestreamPartParams) {

            this._requestManager.moveRequest(
                movableRequestHandle, codestreamPartParams);
        },

        createRequest: function createRequest(
            fetchParams,
            callbackThis,
            callback,
            terminatedCallback,
            isOnlyWaitForData,
            requestId) {

            var contextVars = {
                progressiveStagesDone: 0,
                isProgressive: false,
                isLastCallbackCalledWithoutLowQualityLayerLimit: false,
                callbackThis: callbackThis,
                callback: callback,
                terminatedCallback: terminatedCallback
            };

            this._requestManager.createRequest(
                fetchParams,
                contextVars,
                internalCallback,
                internalTerminatedCallback,
                isOnlyWaitForData,
                requestId);
        },

        manualAbortNonMovableRequest: function manualAbortNonMovableRequest(
            requestId) {

            this._requestManager.manualAbortNonMovableRequest(requestId);
        },

        reconnect: function reconnect() {
            this._codestreamClient.reconnect();
        },

        setServerRequestPrioritizerData :
            function setServerRequestPrioritizerData(prioritizerData) {
                if (this._serverRequestPrioritizer === null) {
                    throw 'No serverRequest prioritizer has been set';
                }

                if (this._showLog) {
                    console.log('setServerRequestPrioritizerData(' + prioritizerData + ')');
                }

                prioritizerData.image = this;
                this._serverRequestPrioritizer.setPrioritizerData(prioritizerData);
            },

        getLevelWidth: function getLevelWidth(numResolutionLevelsToCut) {
            validateSizesCalculator(this);
            var width = this._sizesCalculator.getLevelWidth(
                numResolutionLevelsToCut);

            return width;
        },

        getLevelHeight: function getLevelHeight(numResolutionLevelsToCut) {
            validateSizesCalculator(this);
            var height = this._sizesCalculator.getLevelHeight(
                numResolutionLevelsToCut);

            return height;
        },

        getDefaultNumResolutionLevels: function getDefaultNumResolutionLevels() {
            validateSizesCalculator(this);
            var numLevels = this._sizesCalculator.getDefaultNumResolutionLevels();

            return numLevels;
        }
    };

    function internalCallback(contextVars, requestContext) {
        var isLimitToLowQualityLayer =
            contextVars.progressiveStagesDone === 0;

        // See comment at internalTerminatedCallback method
        contextVars.isLastCallbackCalledWithoutLowQualityLayerLimit |=
            contextVars.isProgressive &&
            !isLimitToLowQualityLayer;

        if (!contextVars.isProgressive) {
            return;
        }

        var maxNumQualityLayers =
            isLimitToLowQualityLayer ? 1 : undefined;

        ++contextVars.progressiveStagesDone;

        extractDataAndCallCallback(
            contextVars, requestContext, maxNumQualityLayers);
    }

    function internalTerminatedCallback(contextVars, requestContext, isAborted) {
        if (!contextVars.isLastCallbackCalledWithoutLowQualityLayerLimit) {
            // This condition come to check if another decoding should be done.
            // One situation it may happen is when the request is not
            // progressive, then the decoding is done only on termination.
            // Another situation is when only the first stage has been reached,
            // thus the callback was called with only the first quality layer
            // (for performance reasons). Thus another decoding should be done.

            extractDataAndCallCallback(contextVars, requestContext);
        }

        contextVars.terminatedCallback.call(
            contextVars.callbackThis, isAborted);
    }

    function extractDataAndCallCallback(
        contextVars, requestContext, maxNumQualityLayers) {

        var packetsData = requestContext.getAllCodeblocksData(
            maxNumQualityLayers);

        var headersCodestream = requestContext.createCodestream(
            /*isOnlyHeadersWithoutBitstream=*/true);

        headersCodestream.codestream =
            convertToTypedArray(headersCodestream.codestream);

        contextVars.callback.call(
            contextVars.callbackThis, packetsData, headersCodestream);
    }

    function createServerRequestDummyResource() {
        return {};
    }

    function validateSizesCalculator(self) {
        if (self._sizesCalculator !== null) {
            return;
        }

        self._imageParams = self.getSizesParams();
        self._sizesCalculator = new JpipCodestreamSizesCalculator(
            self._imageParams);
    }

    function convertToTypedArray(array) {
        // NOTE: This can be done more efficiently within reconstruction,
        // if the array is lazily built from the databin parts and then
        // copied to a new arrayBuffer directly

        var typedArray = new Uint8Array(array.length);
        for (var i = 0; i < array.length; ++i) {
            typedArray[i] = array[i];
        }

        return typedArray;
    }

    return CodestreamClientManager;
})();


text:
module ActiveRecord
  module Uuid
    class Railtie < Rails::Railtie
      config.active_record.schema_format = :sql # For UUID columns and other PGSQL goodness.
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2019 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<task oid="ef22bf7b-5d28-4a57-b3a5-6fa58491eeb3"
    xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
    xmlns:ext="http://midpoint.evolveum.com/xml/ns/public/model/extension-3"
    xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3">

    <name>Live Sync Interrupted: Batched</name>

    <extension>
        <ext:objectclass>ri:AccountObjectClass</ext:objectclass>
        <ext:liveSyncBatchSize>10</ext:liveSyncBatchSize>
        <ext:retryLiveSyncErrors>false</ext:retryLiveSyncErrors>
    </extension>

    <taskIdentifier>ef22bf7b-5d28-4a57-b3a5-6fa58491eeb3</taskIdentifier>
    <ownerRef oid="00000000-0000-0000-0000-000000000002"/>
    <executionStatus>runnable</executionStatus>

    <handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/synchronization/task/live-sync/handler-3</handlerUri>
    <objectRef oid="7a58233a-1cfb-46d1-a404-08cdf4626ebb" type="ResourceType"/>
    <recurrence>single</recurrence>
</task>


text:
/**
 * Utility class for sorting an array using Selection Sort algorithm. Selection
 * Sort is a basic algorithm for sorting with O(n^2) time complexity. Basic idea
 * of this algorithm is to find a local minimum, which is the minimum value from
 * (i+1) to length of the array [i+1, arr.length), and swap it with the current
 * working index (i).
 *
 * @author Kongpon Charanwattanakit
 *
 */
public class SelectionSort {

	/**
	 * Sort an array using Selection Sort algorithm.
	 *
	 * @param arr
	 *            is an array to be sorted
	 */
	public static void sort(int[] arr) {
		for (int i = 0; i < arr.length; i++) {
			int min = i;
			for (int j = i + 1; j < arr.length; j++) {
				/* find local min */
				if (arr[j] < arr[min]) {
					min = j;
				}
			}
			swap(arr, i, min);
		}
	}

	/**
	 * Utility method for swapping elements in an array.
	 *
	 * @param arr
	 *            is an array to be swapped
	 * @param i
	 *            is index of first element
	 * @param j
	 *            is index of second element
	 */
	private static void swap(int[] arr, int i, int j) {
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}
}


text:
import sys
import os
reload(sys)
sys.setdefaultencoding("utf-8")
import yaml
from sqlalchemy import Table,literal_column,select
import csv

def importVolumes(connection,metadata,sourcePath):

    invVolumes = Table('invVolumes',metadata)
    invTypes = Table('invTypes',metadata)
    with open(os.path.join(sourcePath,'invVolumes1.csv'), 'r') as groupVolumes:
        volumereader=csv.reader(groupVolumes, delimiter=',')
        for group in volumereader:
            connection.execute(invVolumes.insert().from_select(['typeID','volume'],select([invTypes.c.typeID,literal_column(group[0])]).where(invTypes.c.groupID == literal_column(group[1]))))
    with open(os.path.join(sourcePath,'invVolumes2.csv'), 'r') as groupVolumes:
        volumereader=csv.reader(groupVolumes, delimiter=',')
        for group in volumereader:
            connection.execute(invVolumes.insert(),typeID=group[1],volume=group[0])


text:
from ._elink import elink_external_model
from ._easic import elink_asic_model


text:
package com.mendeley.api.model;

public class Point {
    public final double x;
    public final double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Point point = (Point) o;

        if (Double.compare(point.x, x) != 0) return false;
        if (Double.compare(point.y, y) != 0) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result;
        long temp;
        temp = Double.doubleToLongBits(x);
        result = (int) (temp ^ (temp >>> 32));
        temp = Double.doubleToLongBits(y);
        result = 31 * result + (int) (temp ^ (temp >>> 32));
        return result;
    }
}


text:
namespace Figlut.Server.Toolkit.Extensions.DataBox.Managers
{
    public delegate void OnDataBoxPropertiesChanged(object sender, DataBoxPropertiesChangedArgs e);
}


text:
#import "TGAlertSoundController.h"

#import "TGHeaderCollectionItem.h"
#import "TGVariantCollectionItem.h"
#import "TGCheckCollectionItem.h"
#import "TGCommentCollectionItem.h"

#import "TGAppDelegate.h"

@interface TGAlertSoundController ()
{
    NSArray *_soundInfoList;
}

@end

@implementation TGAlertSoundController

- (id)initWithTitle:(NSString *)title soundInfoList:(NSArray *)soundInfoList
{
    self = [super init];
    if (self != nil)
    {
        [self setTitleText:title];
        [self setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:TGLocalized(@"Common.Cancel") style:UIBarButtonItemStylePlain target:self action:@selector(cancelPressed)]];
        [self setRightBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:TGLocalized(@"Common.Done") style:UIBarButtonItemStyleDone target:self action:@selector(donePressed)]];

        _soundInfoList = soundInfoList;

        NSMutableArray *alertTonesSectionItems = [[NSMutableArray alloc] init];
        [alertTonesSectionItems addObject:[[TGHeaderCollectionItem alloc] initWithTitle:TGLocalized(@"Notifications.AlertTones")]];

        NSMutableArray *classicTonesSectionItems = [[NSMutableArray alloc] init];
        [classicTonesSectionItems addObject:[[TGHeaderCollectionItem alloc] initWithTitle:TGLocalized(@"Notifications.ClassicTones")]];

        for (int groupId = 0; groupId < 2; groupId++)
        {
            int index = -1;
            for (NSDictionary *desc in _soundInfoList)
            {
                index++;

                if ([desc[@"groupId"] intValue] != groupId)
                    continue;

                TGCheckCollectionItem *checkItem = [[TGCheckCollectionItem alloc] initWithTitle:desc[@"title"] action:@selector(alertTonePressed:)];

                if (index == 1)
                    checkItem.requiresFullSeparator = true;

                [checkItem setIsChecked:[desc[@"selected"] boolValue]];

                if (groupId == 0)
                    [alertTonesSectionItems addObject:checkItem];
                else
                    [classicTonesSectionItems addObject:checkItem];
            }
        }

        TGCollectionMenuSection *alertTonesSection = [[TGCollectionMenuSection alloc] initWithItems:alertTonesSectionItems];

        UIEdgeInsets topSectionInsets = alertTonesSection.insets;
        topSectionInsets.top = 32.0f;
        alertTonesSection.insets = topSectionInsets;
        [self.menuSections addSection:alertTonesSection];

        if (classicTonesSectionItems.count > 1)
        {
            TGCollectionMenuSection *classicTonesSection = [[TGCollectionMenuSection alloc] initWithItems:classicTonesSectionItems];
            [self.menuSections addSection:classicTonesSection];
        }
    }
    return self;
}

- (void)cancelPressed
{
    [self.presentingViewController dismissViewControllerAnimated:true completion:nil];
}

- (void)donePressed
{
    int soundId = [self _selectedSoundId];

    if (soundId != -1)
    {
        id<TGAlertSoundControllerDelegate> delegate = _delegate;
        if ([delegate respondsToSelector:@selector(alertSoundController:didFinishPickingWithSoundInfo:)])
            [delegate alertSoundController:self didFinishPickingWithSoundInfo:_soundInfoList[soundId]];
    }

    [self.presentingViewController dismissViewControllerAnimated:true completion:nil];
}

- (void)alertTonePressed:(TGCheckCollectionItem *)checkCollectionItem
{
    NSIndexPath *indexPath = [self indexPathForItem:checkCollectionItem];
    if (indexPath != nil)
    {
        [self _selectItem:checkCollectionItem];
        [self _playSoundWithId:[self soundIdFromItemIndexPath:indexPath]];
    }
}

- (int)soundIdFromItemIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.section == 0 ? (indexPath.row - 1) : (indexPath.row - 1 + ((TGCollectionMenuSection *)self.menuSections.sections[0]).items.count - 1);
}

- (int)_selectedSoundId
{
    for (int sectionIndex = 0; sectionIndex < (int)self.menuSections.sections.count; sectionIndex++)
    {
        int index = -1;
        for (id item in ((TGCollectionMenuSection *)self.menuSections.sections[sectionIndex]).items)
        {
            index++;

            if ([item isKindOfClass:[TGCheckCollectionItem class]])
            {
                if (((TGCheckCollectionItem *)item).isChecked)
                    return [self soundIdFromItemIndexPath:[NSIndexPath indexPathForItem:index inSection:sectionIndex]];
            }
        }
    }

    return -1;
}

- (void)_selectItem:(TGCheckCollectionItem *)checkCollectionItem
{
    for (int sectionIndex = 0; sectionIndex < (int)self.menuSections.sections.count; sectionIndex++)
    {
        for (id item in ((TGCollectionMenuSection *)self.menuSections.sections[sectionIndex]).items)
        {
            if ([item isKindOfClass:[TGCheckCollectionItem class]])
            {
                if (item == checkCollectionItem)
                    [(TGCheckCollectionItem *)item setIsChecked:true];
                else
                    [(TGCheckCollectionItem *)item setIsChecked:false];
            }
        }
    }
}

- (void)_playSoundWithId:(int)soundId
{
    if (soundId != 0 && [(NSString *)_soundInfoList[soundId][@"soundName"] length] != 0)
    {
        [TGAppDelegateInstance playNotificationSound:_soundInfoList[soundId][@"soundName"]];
    }
}

@end


text:
.. _api_ref:

API reference
=============

.. currentmodule:: seaborn.objects

.. _objects_api:

Objects interface
-----------------

Plot object
~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :template: plot
    :nosignatures:

    Plot

Mark objects
~~~~~~~~~~~~

.. rubric:: Dot marks

.. autosummary::
    :toctree: generated/
    :template: object
    :nosignatures:

    Dot
    Dots

.. rubric:: Line marks

.. autosummary::
    :toctree: generated/
    :template: object
    :nosignatures:

    Line
    Lines
    Path
    Paths
    Dash
    Range

.. rubric:: Bar marks

.. autosummary::
    :toctree: generated/
    :template: object
    :nosignatures:

    Bar
    Bars

.. rubric:: Fill marks

.. autosummary::
    :toctree: generated/
    :template: object
    :nosignatures:

    Area
    Band

.. rubric:: Text marks

.. autosummary::
    :toctree: generated/
    :template: object
    :nosignatures:

    Text

Stat objects
~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :template: object
    :nosignatures:

    Agg
    Est
    Count
    Hist
    KDE
    Perc
    PolyFit

Move objects
~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :template: object
    :nosignatures:

    Dodge
    Jitter
    Norm
    Stack
    Shift

Scale objects
~~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :template: scale
    :nosignatures:

    Continuous
    Nominal
    Temporal

Base classes
~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :template: object
    :nosignatures:

    Mark
    Stat
    Move
    Scale

.. currentmodule:: seaborn

Function interface
------------------

.. _relational_api:

Relational plots
~~~~~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :nosignatures:

    relplot
    scatterplot
    lineplot

.. _distribution_api:

Distribution plots
~~~~~~~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :nosignatures:

    displot
    histplot
    kdeplot
    ecdfplot
    rugplot
    distplot

.. _categorical_api:

Categorical plots
~~~~~~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :nosignatures:

    catplot
    stripplot
    swarmplot
    boxplot
    violinplot
    boxenplot
    pointplot
    barplot
    countplot

.. _regression_api:

Regression plots
~~~~~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :nosignatures:

    lmplot
    regplot
    residplot

.. _matrix_api:

Matrix plots
~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :nosignatures:

    heatmap
    clustermap

.. _grid_api:

Multi-plot grids
----------------

Facet grids
~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :nosignatures:

    FacetGrid

Pair grids
~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :nosignatures:

    pairplot
    PairGrid

Joint grids
~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :nosignatures:

    jointplot
    JointGrid

.. _style_api:

Themeing
--------

.. autosummary::
    :toctree: generated/
    :nosignatures:

    set_theme
    axes_style
    set_style
    plotting_context
    set_context
    set_color_codes
    reset_defaults
    reset_orig
    set

.. _palette_api:

Color palettes
--------------

.. autosummary::
    :toctree: generated/
    :nosignatures:

    set_palette
    color_palette
    husl_palette
    hls_palette
    cubehelix_palette
    dark_palette
    light_palette
    diverging_palette
    blend_palette
    xkcd_palette
    crayon_palette
    mpl_palette

Palette widgets
~~~~~~~~~~~~~~~

.. autosummary::
    :toctree: generated/
    :nosignatures:

    choose_colorbrewer_palette
    choose_cubehelix_palette
    choose_light_palette
    choose_dark_palette
    choose_diverging_palette

Utility functions
-----------------

.. autosummary::
    :toctree: generated/
    :nosignatures:

    despine
    move_legend
    saturate
    desaturate
    set_hls_values
    load_dataset
    get_dataset_names
    get_data_home


text:
<?php
namespace Http\Actions;

use Slim\Http\Response;

use Slim\Views\Twig;

class Responder
{
    public const HTTP_STATUS_CODE_OK = 200;
    public const HTTP_STATUS_CODE_CREATED = 201;
    public const HTTP_STATUS_CODE_NOT_FOUND = 404;

    public const STATUS_SUCCESS = 'success';
    public const STATUS_ERROR = 'error';

    public const TEMPLATE = '';

    private $twig;
    private $response;
    private $output = [];
    private $template;

    public function __construct($twig)
    {
        $this->twig = $twig;
    }

    public function setResponse(Response $response)
    {
        $this->response = $response;
    }

    public function setTemplate(string $template)
    {
        $this->template = $template;
    }

    public function setOutput($output)
    {
        $this->output = (array) $output;
    }

    public function toHtml()
    {
        return $this->twig->render(
            $this->response,
            static::TEMPLATE,
            $this->output
        );
    }

    public function toJson()
    {
        return $this->response
            ->withStatus($this::HTTP_STATUS_CODE_OK)
            ->withHeader("Content-Type", "application/json")
            ->withJson([
                'status' => $this::STATUS_SUCCESS,
                'data' => $this->output,
            ]);
    }
}


text:
require("@nomiclabs/hardhat-truffle5");
require(__dirname + "/../plugins/nomiclabs.plugin");

module.exports = {
  solidity: {
    version: "0.7.6"
  },
  logger: process.env.SILENT ? { log: () => {} } : console,
};


text:
<!DOCTYPE html>

	    <meta charset="utf-8">
	    <meta http-equiv="X-UA-Compatible" content="IE=edge">
	    <meta name="viewport" content="width=device-width, initial-scale=1">
		<title><?php echo $titulo; ?></title>

		<link rel="stylesheet" href="<?php echo base_url('assets/css/bootstrap.min.css');?>">
        <link href="<?php echo base_url('assets/css/style.css');?>" rel="stylesheet">

            <link rel="stylesheet" href="<?php echo base_url('assets/css/dataTables.bootstrap.min.css');?>">

					    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
					      Toggle navigation

					    </button>
					    CIET
					    <a  href="<?= site_url('loginController/logout') ?>">

							         Dashboard

<a href="<?= site_url('crawlerController') ?>">Crawler

<a href="<?= site_url('vagaController') ?>">Vagas cadastradas

<a href="<?= site_url('areaDeTrabalhoController') ?>">Área de trabalho

								     Cadastro

<a href="<?= site_url('empresaController') ?>">Empregadores

<a href="<?= site_url('usuarioController') ?>">Usuários

<a href="<?= site_url('perfilController') ?>">Perfis de usuários

								     Gráficos

<a href="<?= site_url('vagaController/PVagaAbertaFechada') ?>">Vagas abertas e fechadas

<a href="<?= site_url('vagaController/PVagaPEscolaridade') ?>">Vagas Abertas e fechadas POR escolaridade

<a href="<?= site_url('vagaController/PVagaPFaixaEtaria') ?>">Vagas Abertas e fechadas Faixa Etária

<a href="<?= site_url('vagaController/PVagaPSexo') ?>">Vagas Abertas e fechadas por sexo

<a href="<?= site_url('vagaController/PVagaPTipo') ?>">Forma de contratação

<a href="<?= site_url('vagaController/PVagaPRanking') ?>">Ranking de empresas

								     Relatórios

<a href="<?= site_url('empresaController/PEmpregador') ?>">Empregadores

<a href="<?= site_url('vagaController/PEmpregadorVaga') ?>">Empresas com mais vagas

<a href="<?= site_url('vagaController/PVaga') ?>">Vagas cadastradas

		    <?php
		    	if(isset($_SESSION)) {
		        	echo $this->session->flashdata('flash_data');
		    	}
		    ?>
                <?php echo $body; ?>


text:
package de.hshannover.f4.trust.visitmeta.ifmap.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import de.hshannover.f4.trust.ifmapj.IfmapJ;
import de.hshannover.f4.trust.ifmapj.binding.IfmapStrings;
import de.hshannover.f4.trust.ifmapj.metadata.Cardinality;
import de.hshannover.f4.trust.ifmapj.metadata.EnforcementAction;
import de.hshannover.f4.trust.ifmapj.metadata.EventType;
import de.hshannover.f4.trust.ifmapj.metadata.LocationInformation;
import de.hshannover.f4.trust.ifmapj.metadata.Significance;
import de.hshannover.f4.trust.ifmapj.metadata.StandardIfmapMetadataFactory;
import de.hshannover.f4.trust.ifmapj.metadata.WlanSecurityType;

/**
 *
 * @author Marcel Reichenbach
 *
 */
public class MetadataMock {

	public static final String XMLNS_PREFIX = "xmlns:";

	public static final String TIMESTAMP = "ifmap-timestamp";

	public static final String TIMESTAMP_FRACTION = "ifmap-timestamp-fraction";

	public static final String IFMAP_PUBLISHER_ID = "ifmap-publisher-id";

	private static final SimpleDateFormat XSD_DATE_TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

	private static final SimpleDateFormat XSD_DATETIME_TIMEZONE_FORMATTER = new SimpleDateFormat("Z");

	private static final StandardIfmapMetadataFactory IFMAP_METADATA_FACTORY = IfmapJ.createStandardMetadataFactory();

	public static final String mPublisherID = "IfmapjMock";

	/**
	 * Simulated the irond(v. 0.5.1) and set default metadata attributes.
	 *
	 * @param doc
	 * @param timestamp
	 */
	private static void setDocumentXmlAttributes(Document doc, Date timestamp) {
		String timezone = XSD_DATETIME_TIMEZONE_FORMATTER.format(timestamp);
		String timeValue = XSD_DATE_TIME_FORMATTER.format(timestamp) + timezone.substring(0, 3) + ":"
				+ timezone.substring(3);

		Element mXmlElement = (Element) doc.getFirstChild();

		mXmlElement.setAttribute(XMLNS_PREFIX + IfmapStrings.STD_METADATA_PREFIX, IfmapStrings.STD_METADATA_NS_URI);
		mXmlElement.setAttribute(IFMAP_PUBLISHER_ID, mPublisherID);
		mXmlElement.setAttribute(TIMESTAMP_FRACTION, getSecondFraction(timestamp) + "");
		mXmlElement.setAttribute(TIMESTAMP, timeValue);
	}

	/**
	 * Copied from the irond(v. 0.5.1) sources (de.hshannover.f4.trust.iron.mapserver.utils.TimestampFraction)
	 *
	 * Return the decimal fraction of a second of the given {@link Date}.
	 *
	 * @param dt the {@link Date} from with to extract the fraction
	 * @return a double containing the decimal fraction of a second
	 */
	private static double getSecondFraction(Date dt) {
		return dt.getTime() % 1000 / 1000.0;
	}

	public static Document createIpMac(String startTime, String endTime, String dhcpServer, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createIpMac(startTime, endTime, dhcpServer);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createIpMac(Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createIpMac();
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createArMac(Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createArMac();
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createArDev(Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createArDev();
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createArIp(Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createArIp();
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createAuthAs(Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createAuthAs();
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createAuthBy(Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createAuthBy();
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createDevIp(Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createDevIp();
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createDiscoveredBy(Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createDiscoveredBy();
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createRole(String name, String administrativeDomain, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createRole(name, administrativeDomain);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createRole(String name, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createRole(name);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createDevAttr(String name, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createDevAttr(name);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createCapability(String name, String administrativeDomain, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createCapability(name, administrativeDomain);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createCapability(String name, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createCapability(name);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createDevChar(String manufacturer, String model, String os, String osVersion,
			String deviceType, String discoveredTime, String discovererId, String discoveryMethod, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createDevChar(manufacturer, model, os, osVersion, deviceType, discoveredTime, discovererId, discoveryMethod);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createEnforcementReport(EnforcementAction enforcementAction, String otherTypeDefinition,
			String enforcementReason, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createEnforcementReport(enforcementAction, otherTypeDefinition, enforcementReason);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createEvent(String name, String discoveredTime, String discovererId, Integer magnitude,
			Integer confidence, Significance significance, EventType type, String otherTypeDefinition,
			String information, String vulnerabilityUri, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createEvent(name, discoveredTime, discovererId, magnitude, confidence,
				significance, type, otherTypeDefinition, information, vulnerabilityUri);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document create(String elementName, String qualifiedName, String uri, Cardinality cardinality,
			Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.create(elementName, qualifiedName, uri, cardinality);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document create(String elementName, String qualifiedName, String uri, Cardinality cardinality,
			String attrName, String attrValue, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.create(elementName, qualifiedName, uri, cardinality, attrName, attrValue);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document create(String elementName, String qualifiedName, String uri, Cardinality cardinality,
			HashMap<String, String> attributes, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.create(elementName, qualifiedName, uri, cardinality, attributes);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createLayer2Information(Integer vlan, String vlanName, Integer port,
			String administrativeDomain, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createLayer2Information(vlan, vlanName, port, administrativeDomain);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createLocation(List<LocationInformation> locationInformation, String discoveredTime,
			String discovererId, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createLocation(locationInformation, discoveredTime, discovererId);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createRequestForInvestigation(String qualifier, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createRequestForInvestigation(qualifier);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createWlanInformation(String ssid, List<WlanSecurityType> ssidUnicastSecurity,
			WlanSecurityType ssidGroupSecurity, List<WlanSecurityType> ssidManagementSecurity,
			Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createWlanInformation(ssid, ssidUnicastSecurity, ssidGroupSecurity, ssidManagementSecurity);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createUnexpectedBehavior(String discoveredTime, String discovererId, Integer magnitude,
			Integer confidence, Significance significance, String type, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createUnexpectedBehavior(discoveredTime, discovererId, magnitude, confidence, significance, type);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

	public static Document createClientTime(String time, Date timestamp) {
		Document doc = IFMAP_METADATA_FACTORY.createClientTime(time);
		setDocumentXmlAttributes(doc, timestamp);
		return doc;
	}

}


text:
Regression Test Suites scripts, and folders for: execution results for
significant releases, and
configuration scripts and supporting files in a variety of languages:

- [GO](https://github.com/hyperledger/fabric/bddtests/regression/go)
  language test scripts
- [NODE](https://github.com/hyperledger/fabric/bddtests/regression/node)
  language test scripts
  Note: a flexible-use performance engine, which can be configured and used
  for a variety of tests, is located in the
  [node/performance](https://github.com/hyperledger/fabric/bddtests/regression/node/performance)
  folder.  For examples how to use it, check there, or look for examples in the
  daily test suite and long-run test suite scripts.
- [results](https://github.com/hyperledger/fabric/bddtests/regression/results)
  folder containing logfiles and results of running the Test Suites on
  significant releases, for reference

### Continous Integration Setup
Continuous Integration team will execute the *daily test suite* each day when a
merge commit has been pushed to fabric repository.
We have configured Jenkins in vLaunch to execute the Daily Test Suite:
the jobs listed below are downstream jobs which are run after successfully
executing the upstream job.
After the build is successfully executed, Jenkins will post build results
back to **rel-criteria-build** slack channel,
and generate a test summary report, to be available for viewing for 30 days.
For significant releases, the results will be stored
in **bddtests/regression/results** folder.

### Daily Test Suite - daily_test_suite.sh
Expected total time duration is between 13 - 16 hours.

* Consensus Acceptance Tests (CAT) - using chaincode example02, GO, gRPC
  - Objective of CAT tests is to ensure the stability and resiliency of the
    BFT Batch design.
* Large Networks Basic API And Consensus Tests - using chaincode example02,
  GO, gRPC
  - Objective of Basic gRPC API test is to ensure basic gRPC API functions
    are working as expected
* Ledger Stress Tests (LST) for API and 20K runs with concurrency and
  1K payload - using chaincode addrecs, GO, gRPC
* Speed Tests for measuring turnaround performance of the communication path
  and blockchain network processing - using chaincode addrecs, GO, gRPC
* Concurrency Tests - using chaincode addrecs, GO, gRPC
  - Objective of Concurrency test is to ensure system is able to accept
    multiple threads concurrently for specified number of mins.
* Complex Transactions Tests - using chaincode auction, node, gRPC
  - Objective of this test is to send complex transactions using
    auction chaincode
* Performance Tests, random sized payloads - using chaincodes example02
  and auction, node, gRPC
  - CI performs below tests in Performance testing
     * Invoke on chaincode_example02 using 4 peers and
       4 Threads for 180 secs
     * Query on chaincode_example02 using 4 peers and
       4 Threads for 180 secs
     * Invoke on auction chaincode using 4 peers and
       1000 Tx for each of the 4 Threads
     * Query on auction chaincode using 4 peers and
       1000 Tx for each of the 4 Threads
     * Invoke on auction chaincode using 4 peers and 4 Threads.
       Each Invoke is followed by a Query on every Thread
     * Invoke on example02 chaincode using 4 peers and 4 Threads.
Each Invoke is followed by a Query on every Thread

### LongRun Test Suite - longrun_test_suite.sh
Expected total time duration is 72 hours when executed from
Jenkins automation scripts, which run several parallel jobs.

* Consensus peers restarts tests, 2 tests, each approximately 10 hours -
  using chaincode example02, GO, gRPC
* Ledger Stress Test 1 Million transactions, approximately 36 hours -
  using chaincode addrecs, GO, gRPC
* Ledger Stress Test, 72 hours - using chaincode addrecs, GO, gRPC
  - Send parallel Invoke requests on all 4 peers
* Performance Tests, 72 hours, random sized payloads - using chaincode auction,
  node, gRPC (includes variable traffic, concurrency, complex transactions)
  - Invoke 1 Tx per sec on 1 peer for 72 hrs (1 Thread)

### Full Regression Test Suite
Execute both the Daily Test Suite AND the Long Run Test Suite.

This work is licensed under a Creative Commons Attribution 4.0 International License.
s


text:
using namespace System;
using namespace System::Runtime::InteropServices;

namespace DeviceDriver {

    public interface class IDeviceDriver {
        int UsbRelayInit();
        int UsbRelayExit();
        usb_relay_device_info * UsbRelayDeviceEnumerate();
        void UsbRelayDeviceFreeEnumerate(usb_relay_device_info * info);
        void UsbRelayDeviceClose(int hHandle);
        int UsbRelayDeviceOpen(struct usb_relay_device_info* device_info);
        int UsbRelayDeviceOpenWithSerialNumber(const char *serial_number, unsigned len);
        int UsbRelayDeviceOpenOneRelayChannel(int hHandle, int index);
        int UsbRelayDeviceOpenAllRelayChannel(int hHandle);
        int UsbRelayDeviceCloseOneRelayChannel(int hHandle, int index);
        int UsbRelayDeviceCloseAllRelayChannel(int hHandle);
        int UsbRelayDeviceGetStatus(int hHandle, unsigned int *status);
    };

    private ref class DriverWrapper : public IDeviceDriver {
    public:
        virtual int UsbRelayInit();
        virtual int UsbRelayExit();
        virtual usb_relay_device_info * UsbRelayDeviceEnumerate();
        virtual void UsbRelayDeviceFreeEnumerate(usb_relay_device_info * info);
        virtual void UsbRelayDeviceClose(int hHandle);
        virtual int UsbRelayDeviceOpen(struct usb_relay_device_info* device_info);
        virtual int UsbRelayDeviceOpenWithSerialNumber(const char *serial_number, unsigned len);
        virtual int UsbRelayDeviceOpenOneRelayChannel(int hHandle, int index);
        virtual int UsbRelayDeviceOpenAllRelayChannel(int hHandle);
        virtual int UsbRelayDeviceCloseOneRelayChannel(int hHandle, int index);
        virtual int UsbRelayDeviceCloseAllRelayChannel(int hHandle);
        virtual int UsbRelayDeviceGetStatus(int hHandle, unsigned int *status);
	};
}


text:
"use babel";

const handlers = {
    setState(state, action) {
        return Object.assign({}, state, action.state);
    },
    indexed(state, action) {
        return Object.assign({}, state, {indexed: action.result});
    },
    setActiveFile(state, action) {
        return Object.assign({}, state, {activeFile: action.file})
    },
    setActivePosition(state, action) {
        return Object.assign({}, state, {activePosition: action.pos})
    },
    setActiveEntity(state, action) {
        return Object.assign({}, state, {
            metadata: state.metadata.map(ent => {
                return Object.assign({}, ent, {ui_active: ent == action.entity});
            })
        })
    },
    setMetadata(state, action) {
        const allMetadata = state.allMetadata || [];
        const path = action.file.path;
        const files = state.files || {};
        const key = '$' + path;
        let fixture = {};
        fixture[key] = action.file;

        const finalFiles = Object.assign({}, files, fixture);
        return Object.assign({}, state, {
            metadata: action.metadata || state.metadata,
            files: finalFiles,
            allMetadata: Object.keys(finalFiles).reduce((acc, k) => acc.concat(finalFiles[k].metadata || [] ), [])
        })
    },
    rememberPosition(state, action) {
        console.log("GO < TO", action);
        // TODO refactor
        const pos = {
            path,
            pos,
            selections: action.selections
        }
        const positions = (state.positions || []).concat(pos);
        return Object.assign({}, state, {positions})
    }
}

export default function reducer(state, action) {
    if (handlers.hasOwnProperty(action.type)) {
        return handlers[action.type](state, action);
    }
    return state;
}


text:
    Low variance

Features with low variance are less likely to contain useful information. Consider removing them, especially if they have zero variance. This is less likely to be true if your features are on different scales; for example, if one features is in years, and another feature is in millimeters.

    Covariance

Two features with covariance far from zero are likely to contain redundant information.


text:
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tada.settings")
    sys.path.append(os.path.join(os.getcwd(), 'apps'))

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)


text:
<!DOCTYPE html>

  <title>Editing: designMode attribute test</title>
  <link rel="author" title="Baidu" href="mailto: guopengcheng@baidu.com"/>
  <link rel="help" href="http://www.w3.org/TR/html5/editing.html#making-entire-documents-editable:-the-designmode-idl-attribute"/>


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Use udica to build SELinux policy for containers)
[#]: via: (https://fedoramagazine.org/use-udica-to-build-selinux-policy-for-containers/)
[#]: author: (Lukas Vrabec https://fedoramagazine.org/author/lvrabec/)

Use udica to build SELinux policy for containers
======

![][1]

While modern IT environments move towards Linux containers, the need to secure these environments is as relevant as ever. Containers are a process isolation technology. While containers can be a defense mechanism, they only excel when combined with SELinux.

Fedora SELinux engineering built a new standalone tool, **udica** , to generate SELinux policy profiles for containers by automatically inspecting them. This article focuses on why _udica_ is needed in the container world, and how it makes SELinux and containers work better together. You'll find examples of SELinux separation for containers that let you avoid turning protection off because the generic SELinux type _container_t_ is too tight. With _udica_ you can easily customize the policy with limited SELinux policy writing skills.

### SELinux technology

SELinux is a security technology that brings proactive security to Linux systems. It's a labeling system that assigns a label to all _subjects_ (processes and users) and _objects_ (files, directories, sockets, etc.). These labels are then used in a security policy that controls access throughout the system. It's important to mention that what's not allowed in an SELinux security policy is denied by default. The policy rules are enforced by the kernel. This security technology has been in use on Fedora for several years. A real example of such a rule is:

```
allow httpd_t httpd_log_t: file { append create getattr ioctl lock open read setattr };
```

The rule allows any process labeled as _httpd_t_ ****to create, append, read and lock files labeled as _httpd_log_t_. Using the _ps_ command, you can list all processes with their labels:

```
$ ps -efZ | grep httpd
system_u:system_r:httpd_t:s0    root     13911     1  0 Apr14 ?       00:05:14 /usr/sbin/httpd -DFOREGROUND
...
```

To see which objects are labeled as httpd_log_t, use _semanage_ :

```
# semanage fcontext -l | grep httpd_log_t
/var/log/httpd(/.)?                               all files          system_u:object_r:httpd_log_t:s0
/var/log/nginx(/.)?                               all files          system_u:object_r:httpd_log_t:s0
...
```

The SELinux security policy for Fedora is shipped in the _selinux-policy_ RPM package.

### SELinux vs. containers

In Fedora, the _container-selinux_ RPM package provides a generic SELinux policy for all containers started by engines like _podman_ or _docker_. Its main purposes are to protect the host system against a container process, and to separate containers from each other. For instance, containers confined by SELinux with the process type _container_t_ can only read/execute files in _/usr_ and write to _container_file_t_ ****files type on host file system. To prevent attacks by containers on each other, Multi-Category Security (MCS) is used.

Using only one generic policy for containers is problematic, because of the huge variety of container usage. On one hand, the default container type ( _container_t_ ) is often too strict. For example:

  * [Fedora SilverBlue][2] needs containers to read/write a user's home directory
  * [Fluentd][3] project needs containers to be able to read logs in the _/var/log_ directory

On the other hand, the default container type could be too loose for certain use cases:

  * It has no SELinux network controls — all container processes can bind to any network port
  * It has no SELinux control on [Linux capabilities][4] — all container processes can use all capabilities

There is one solution to handle both use cases: write a custom SELinux security policy for the container. This can be tricky, because SELinux expertise is required. For this purpose, the _udica_ tool was created.

### Introducing udica

Udica generates SELinux security profiles for containers. Its concept is based on the "block inheritance" feature inside the [common intermediate language][5] (CIL) supported by SELinux userspace. The tool creates a policy that combines:

  * Rules inherited from specified CIL blocks (templates), and
  * Rules discovered by inspection of container JSON file, which contains mountpoints and ports definitions

You can load the final policy immediately, or move it to another system to load into the kernel. Here's an example, using a container that:

  * Mounts _/home_ as read only
  * Mounts _/var/spool_ as read/write
  * Exposes port _tcp/21_

The container starts with this command:

```
# podman run -v /home:/home:ro -v /var/spool:/var/spool:rw -p 21:21 -it fedora bash
```

The default container type ( _container_t_ ) doesn't allow any of these three actions. To prove it, you could use the _sesearch_ tool to query that the _allow_ rules are present on system:

```
# sesearch -A -s container_t -t home_root_t -c dir -p read
```

There's no _allow_ rule present that lets a process labeled as _container_t_ access a directory labeled _home_root_t_ (like the _/home_ directory). The same situation occurs with _/var/spool_ , which is labeled _var_spool_t:_

```
# sesearch -A -s container_t -t var_spool_t -c dir -p read
```

On the other hand, the default policy completely allows network access.

```
# sesearch -A -s container_t -t port_type -c tcp_socket
allow container_net_domain port_type:tcp_socket { name_bind name_connect recv_msg send_msg };
allow sandbox_net_domain port_type:tcp_socket { name_bind name_connect recv_msg send_msg };
```

### Securing the container

It would be great to restrict this access and allow the container to bind just on TCP port _21_ or with the same label. Imagine you find an example container using _podman ps_ whose ID is _37a3635afb8f_ :

```
# podman ps -q
37a3635afb8f
```

You can now inspect the container and pass the inspection file to the _udica_ tool. The name for the new policy is _my_container_.

```
# podman inspect 37a3635afb8f > container.json
# udica -j container.json my_container
Policy my_container with container id 37a3635afb8f created!

Please load these modules using:
 # semodule -i my_container.cil /usr/share/udica/templates/{base_container.cil,net_container.cil,home_container.cil}

Restart the container with: "--security-opt label=type:my_container.process" parameter
```

That's it! You just created a custom SELinux security policy for the example container. Now you can load this policy into the kernel and make it active. The _udica_ output above even tells you the command to use:

```
# semodule -i my_container.cil /usr/share/udica/templates/{base_container.cil,net_container.cil,home_container.cil}
```

Now you must restart the container to allow the container engine to use the new custom policy:

```
# podman run --security-opt label=type:my_container.process -v /home:/home:ro -v /var/spool:/var/spool:rw -p 21:21 -it fedora bash
```

The example container is now running in the newly created _my_container.process_ SELinux process type:

```
# ps -efZ | grep my_container.process
unconfined_u:system_r:container_runtime_t:s0-s0:c0.c1023 root 2275 434  1 13:49 pts/1 00:00:00 podman run --security-opt label=type:my_container.process -v /home:/home:ro -v /var/spool:/var/spool:rw -p 21:21 -it fedora bash
system_u:system_r:my_container.process:s0:c270,c963 root 2317 2305  0 13:49 pts/0 00:00:00 bash
```

### Seeing the results

The command _sesearch_ now shows _allow_ rules for accessing _/home_ and _/var/spool:_

```
# sesearch -A -s my_container.process -t home_root_t -c dir -p read
allow my_container.process home_root_t:dir { getattr ioctl lock open read search };
# sesearch -A -s my_container.process -t var_spool_t -c dir -p read
allow my_container.process var_spool_t:dir { add_name getattr ioctl lock open read remove_name search write }
```

The new custom SELinux policy also allows _my_container.process_ to bind only to TCP/UDP ports labeled the same as TCP port 21:

```
# semanage port -l | grep 21 | grep ftp
 ftp_port_t                     tcp      21, 989, 990
# sesearch -A -s my_container.process -c tcp_socket -p name_bind
 allow my_container.process ftp_port_t:tcp_socket name_bind;
```

### Conclusion

The _udica_ tool helps you create SELinux policies for containers based on an inspection file without any SELinux expertise required. Now you can increase the security of containerized environments. Sources are available on [GitHub][6], and an RPM package is available in Fedora repositories for Fedora 28 and later.

* * *

*Photo by _[_Samuel Zeller_][7]_ on *[ _Unsplash_.][8]

--------------------------------------------------------------------------------

via: https://fedoramagazine.org/use-udica-to-build-selinux-policy-for-containers/

作者:[Lukas Vrabec][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://fedoramagazine.org/author/lvrabec/
[b]: https://github.com/lujun9972
[1]: https://fedoramagazine.org/wp-content/uploads/2019/05/udica-816x345.jpg
[2]: https://silverblue.fedoraproject.org
[3]: https://www.fluentd.org
[4]: http://man7.org/linux/man-pages/man7/capabilities.7.html
[5]: https://en.wikipedia.org/wiki/Common_Intermediate_Language
[6]: https://github.com/containers/udica
[7]: https://unsplash.com/photos/KVG-XMOs6tw?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText
[8]: https://unsplash.com/search/photos/lockers?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText


text:
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="2dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"/>

        <com.android.volley.toolbox.NetworkImageView
            android:id="@+id/poster"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="fitXY"
            android:layout_centerInParent="true">

        </com.android.volley.toolbox.NetworkImageView>

    </RelativeLayout>

</android.support.v7.widget.CardView>


text:
# frozen_string_literal: true

require "rails/generators/app_base"

module Rails
  module ActionMethods # :nodoc:
    attr_reader :options

    def initialize(generator)
      @generator = generator
      @options   = generator.options
    end

    private
      %w(template copy_file directory empty_directory inside
         empty_directory_with_keep_file create_file chmod shebang).each do |method|
        class_eval <<-RUBY, __FILE__, __LINE__ + 1
          def #{method}(*args, &block)
            @generator.send(:#{method}, *args, &block)
          end
        RUBY
      end

      def method_missing(meth, *args, &block)
        @generator.send(meth, *args, &block)
      end
  end

  # The application builder allows you to override elements of the application
  # generator without being forced to reverse the operations of the default
  # generator.
  #
  # This allows you to override entire operations, like the creation of the
  # Gemfile, README, or JavaScript files, without needing to know exactly
  # what those operations do so you can create another template action.
  #
  #  class CustomAppBuilder < Rails::AppBuilder
  #    def test
  #      @generator.gem "rspec-rails", group: [:development, :test]
  #      run "bundle install"
  #      generate "rspec:install"
  #    end
  #  end
  class AppBuilder
    def rakefile
      template "Rakefile"
    end

    def readme
      copy_file "README.md", "README.md"
    end

    def ruby_version
      template "ruby-version", ".ruby-version"
    end

    def gemfile
      template "Gemfile"
    end

    def configru
      template "config.ru"
    end

    def gitignore
      template "gitignore", ".gitignore"
    end

    def gitattributes
      template "gitattributes", ".gitattributes"
    end

    def version_control
      if !options[:skip_git] && !options[:pretend]
        run git_init_command, capture: options[:quiet], abort_on_failure: false
      end
    end

    def app
      directory "app"

      empty_directory_with_keep_file "app/assets/images"

      keep_file  "app/controllers/concerns"
      keep_file  "app/models/concerns"
    end

    def bin
      directory "bin" do |content|
        "#{shebang}\n" + content
      end
      chmod "bin", 0755 & ~File.umask, verbose: false
    end

    def bin_when_updating
      bin
    end

    def config
      empty_directory "config"

      inside "config" do
        template "routes.rb" unless options[:update]
        template "application.rb"
        template "environment.rb"
        template "cable.yml" unless options[:update] || options[:skip_action_cable]
        template "puma.rb"   unless options[:update]
        template "storage.yml" unless options[:update] || skip_active_storage?

        directory "environments"
        directory "initializers"
        directory "locales" unless options[:update]
      end
    end

    def config_when_updating
      action_cable_config_exist       = File.exist?("config/cable.yml")
      active_storage_config_exist     = File.exist?("config/storage.yml")
      rack_cors_config_exist          = File.exist?("config/initializers/cors.rb")
      assets_config_exist             = File.exist?("config/initializers/assets.rb")
      asset_manifest_exist            = File.exist?("app/assets/config/manifest.js")
      asset_app_stylesheet_exist      = File.exist?("app/assets/stylesheets/application.css")
      csp_config_exist                = File.exist?("config/initializers/content_security_policy.rb")
      permissions_policy_config_exist = File.exist?("config/initializers/permissions_policy.rb")

      @config_target_version = Rails.application.config.loaded_config_version || "5.0"

      config

      if !options[:skip_action_cable] && !action_cable_config_exist
        template "config/cable.yml"
      end

      if !skip_active_storage? && !active_storage_config_exist
        template "config/storage.yml"
      end

      if skip_sprockets? && skip_propshaft? && !assets_config_exist
        remove_file "config/initializers/assets.rb"
      end

      if skip_sprockets? && !asset_manifest_exist
        remove_file "app/assets/config/manifest.js"
      end

      if skip_sprockets? && !asset_app_stylesheet_exist
        remove_file "app/assets/stylesheets/application.css"
      end

      unless rack_cors_config_exist
        remove_file "config/initializers/cors.rb"
      end

      if options[:api]
        unless csp_config_exist
          remove_file "config/initializers/content_security_policy.rb"
        end

        unless permissions_policy_config_exist
          remove_file "config/initializers/permissions_policy.rb"
        end
      end

      if !skip_sprockets?
        insert_into_file "config/application.rb", %(require "sprockets/railtie"), after: /require\(["']rails\/all["']\)\n/
      end
    end

    def master_key
      return if options[:pretend] || options[:dummy_app]

      require "rails/generators/rails/master_key/master_key_generator"
      master_key_generator = Rails::Generators::MasterKeyGenerator.new([], quiet: options[:quiet], force: options[:force])
      master_key_generator.add_master_key_file_silently
      master_key_generator.ignore_master_key_file_silently
    end

    def credentials
      return if options[:pretend] || options[:dummy_app]

      require "rails/generators/rails/credentials/credentials_generator"
      Rails::Generators::CredentialsGenerator.new([], quiet: options[:quiet]).add_credentials_file
    end

    def credentials_diff_enroll
      return if options[:skip_decrypted_diffs] || options[:skip_git] || options[:dummy_app] || options[:pretend]

      rails_command "credentials:diff --enroll", inline: true, shell: @generator.shell
    end

    def database_yml
      template "config/databases/#{options[:database]}.yml", "config/database.yml"
    end

    def db
      directory "db"
    end

    def lib
      empty_directory "lib"
      empty_directory_with_keep_file "lib/tasks"
      empty_directory_with_keep_file "lib/assets"
    end

    def log
      empty_directory_with_keep_file "log"
    end

    def public_directory
      directory "public", "public", recursive: false
    end

    def storage
      empty_directory_with_keep_file "storage"
      empty_directory_with_keep_file "tmp/storage"
    end

    def test
      empty_directory_with_keep_file "test/fixtures/files"
      empty_directory_with_keep_file "test/controllers"
      empty_directory_with_keep_file "test/mailers"
      empty_directory_with_keep_file "test/models"
      empty_directory_with_keep_file "test/helpers"
      empty_directory_with_keep_file "test/integration"

      template "test/channels/application_cable/connection_test.rb"
      template "test/test_helper.rb"
    end

    def system_test
      empty_directory_with_keep_file "test/system"

      template "test/application_system_test_case.rb"
    end

    def tmp
      empty_directory_with_keep_file "tmp"
      empty_directory_with_keep_file "tmp/pids"
      empty_directory "tmp/cache"
      empty_directory "tmp/cache/assets"
    end

    def vendor
      empty_directory_with_keep_file "vendor"
    end

    def config_target_version
      defined?(@config_target_version) ? @config_target_version : Rails::VERSION::STRING.to_f
    end
  end

  module Generators
    # We need to store the RAILS_DEV_PATH in a constant, otherwise the path
    # can change in Ruby 1.8.7 when we FileUtils.cd.
    RAILS_DEV_PATH = File.expand_path("../../../../../..", __dir__)

    class AppGenerator < AppBase
      # :stopdoc:

      add_shared_options_for "application"

      # Add rails command options
      class_option :version, type: :boolean, aliases: "-v", group: :rails, desc: "Show Rails version number and quit"
      class_option :api, type: :boolean, desc: "Preconfigure smaller stack for API only apps"
      class_option :minimal, type: :boolean, desc: "Preconfigure a minimal rails app"
      class_option :javascript, type: :string, aliases: ["-j", "--js"], default: "importmap", desc: "Choose JavaScript approach [options: importmap (default), webpack, esbuild, rollup]"
      class_option :css, type: :string, aliases: "-c", desc: "Choose CSS processor [options: tailwind, bootstrap, bulma, postcss, sass... check https://github.com/rails/cssbundling-rails]"
      class_option :skip_bundle, type: :boolean, aliases: "-B", default: nil, desc: "Don't run bundle install"
      class_option :skip_decrypted_diffs, type: :boolean, default: nil, desc: "Don't configure git to show decrypted diffs of encrypted credentials"

      def initialize(*args)
        super

        imply_options({
          **OPTION_IMPLICATIONS,
          minimal: [
            :skip_action_cable,
            :skip_action_mailbox,
            :skip_action_mailer,
            :skip_action_text,
            :skip_active_job,
            :skip_active_storage,
            :skip_bootsnap,
            :skip_dev_gems,
            :skip_hotwire,
            :skip_javascript,
            :skip_jbuilder,
            :skip_system_test,
          ],
          api: [
            :skip_asset_pipeline,
            :skip_javascript,
          ],
        }, meta_options: [:minimal])

        if !options[:skip_active_record] && !DATABASES.include?(options[:database])
          raise Error, "Invalid value for --database option. Supported preconfigurations are: #{DATABASES.join(", ")}."
        end

        @after_bundle_callbacks = []
      end

      public_task :report_implied_options
      public_task :set_default_accessors!
      public_task :create_root
      public_task :target_rails_prerelease

      def create_root_files
        build(:readme)
        build(:rakefile)
        build(:ruby_version)
        build(:configru)

        unless options[:skip_git]
          build(:gitignore)
          build(:gitattributes)
        end

        build(:gemfile)
        build(:version_control)
      end

      def create_app_files
        build(:app)
      end

      def create_bin_files
        build(:bin)
      end

      def update_bin_files
        build(:bin_when_updating)
      end
      remove_task :update_bin_files

      def update_active_storage
        unless skip_active_storage?
          rails_command "active_storage:update", inline: true
        end
      end
      remove_task :update_active_storage

      def create_config_files
        build(:config)
      end

      def update_config_files
        build(:config_when_updating)
      end
      remove_task :update_config_files

      def create_master_key
        build(:master_key)
      end

      def create_credentials
        build(:credentials)
        build(:credentials_diff_enroll)
      end

      def display_upgrade_guide_info
        say "\nAfter this, check Rails upgrade guide at https://guides.rubyonrails.org/upgrading_ruby_on_rails.html for more details about upgrading your app."
      end
      remove_task :display_upgrade_guide_info

      def create_boot_file
        template "config/boot.rb"
      end

      def create_active_record_files
        return if options[:skip_active_record]
        build(:database_yml)
      end

      def create_db_files
        return if options[:skip_active_record]
        build(:db)
      end

      def create_lib_files
        build(:lib)
      end

      def create_log_files
        build(:log)
      end

      def create_public_files
        build(:public_directory)
      end

      def create_tmp_files
        build(:tmp)
      end

      def create_vendor_files
        build(:vendor)
      end

      def create_test_files
        build(:test) unless options[:skip_test]
      end

      def create_system_test_files
        build(:system_test) if depends_on_system_test?
      end

      def create_storage_files
        build(:storage) unless skip_active_storage?
      end

      def delete_app_assets_if_api_option
        if options[:api]
          remove_dir "app/assets"
          remove_dir "lib/assets"
          remove_dir "tmp/cache/assets"
        end
      end

      def delete_app_helpers_if_api_option
        if options[:api]
          remove_dir "app/helpers"
          remove_dir "test/helpers"
        end
      end

      def delete_app_views_if_api_option
        if options[:api]
          if options[:skip_action_mailer]
            remove_dir "app/views"
          else
            remove_file "app/views/layouts/application.html.erb"
          end
        end
      end

      def delete_public_files_if_api_option
        if options[:api]
          remove_file "public/404.html"
          remove_file "public/422.html"
          remove_file "public/500.html"
          remove_file "public/apple-touch-icon-precomposed.png"
          remove_file "public/apple-touch-icon.png"
          remove_file "public/favicon.ico"
        end
      end

      def delete_assets_initializer_skipping_sprockets_and_propshaft
        if skip_sprockets? && skip_propshaft?
          remove_file "config/initializers/assets.rb"
        end

        if skip_sprockets?
          remove_file "app/assets/config/manifest.js"
          remove_dir  "app/assets/config"
          remove_file "app/assets/stylesheets/application.css"
          create_file "app/assets/stylesheets/application.css", "/* Application styles */\n" unless options[:api]
        end
      end

      def delete_application_record_skipping_active_record
        if options[:skip_active_record]
          remove_file "app/models/application_record.rb"
        end
      end

      def delete_active_job_folder_if_skipping_active_job
        if options[:skip_active_job]
          remove_dir "app/jobs"
        end
      end

      def delete_action_mailer_files_skipping_action_mailer
        if options[:skip_action_mailer]
          remove_file "app/views/layouts/mailer.html.erb"
          remove_file "app/views/layouts/mailer.text.erb"
          remove_dir "app/mailers"
          remove_dir "test/mailers"
        end
      end

      def delete_action_cable_files_skipping_action_cable
        if options[:skip_action_cable]
          remove_dir "app/javascript/channels"
          remove_dir "app/channels"
          remove_dir "test/channels"
        end
      end

      def delete_non_api_initializers_if_api_option
        if options[:api]
          remove_file "config/initializers/content_security_policy.rb"
          remove_file "config/initializers/permissions_policy.rb"
        end
      end

      def delete_api_initializers
        unless options[:api]
          remove_file "config/initializers/cors.rb"
        end
      end

      def delete_new_framework_defaults
        unless options[:update]
          remove_file "config/initializers/new_framework_defaults_#{Rails::VERSION::MAJOR}_#{Rails::VERSION::MINOR}.rb"
        end
      end

      def finish_template
        build(:leftovers)
      end

      public_task :apply_rails_template, :run_bundle
      public_task :generate_bundler_binstub
      public_task :run_javascript
      public_task :run_hotwire
      public_task :run_css

      def run_after_bundle_callbacks
        @after_bundle_callbacks.each(&:call)
      end

      def self.banner
        "rails new #{arguments.map(&:usage).join(' ')} [options]"
      end

    # :startdoc:

    private
      # Define file as an alias to create_file for backwards compatibility.
      def file(*args, &block)
        create_file(*args, &block)
      end

      # Registers a callback to be executed after bundle binstubs
      # have run.
      #
      #   after_bundle do
      #     git add: '.'
      #   end
      def after_bundle(&block) # :doc:
        @after_bundle_callbacks << block
      end

      def get_builder_class
        defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder
      end
    end

    # This class handles preparation of the arguments before the AppGenerator is
    # called. The class provides version or help information if they were
    # requested, and also constructs the railsrc file (used for extra configuration
    # options).
    #
    # This class should be called before the AppGenerator is required and started
    # since it configures and mutates ARGV correctly.
    class ARGVScrubber # :nodoc:
      def initialize(argv = ARGV)
        @argv = argv
      end

      def prepare!
        handle_version_request!(@argv.first)
        handle_invalid_command!(@argv.first, @argv) do
          handle_rails_rc!(@argv.drop(1))
        end
      end

      def self.default_rc_file
        xdg_config_home = ENV["XDG_CONFIG_HOME"].presence || "~/.config"
        xdg_railsrc = File.expand_path("rails/railsrc", xdg_config_home)
        if File.exist?(xdg_railsrc)
          xdg_railsrc
        else
          File.expand_path("~/.railsrc")
        end
      end

      private
        def handle_version_request!(argument)
          if ["--version", "-v"].include?(argument)
            require "rails/version"
            puts "Rails #{Rails::VERSION::STRING}"
            exit(0)
          end
        end

        def handle_invalid_command!(argument, argv)
          if argument == "new"
            yield
          else
            ["--help"] + argv.drop(1)
          end
        end

        def handle_rails_rc!(argv)
          if argv.find { |arg| arg == "--no-rc" }
            argv.reject { |arg| arg == "--no-rc" }
          else
            railsrc(argv) { |rc_argv, rc| insert_railsrc_into_argv!(rc_argv, rc) }
          end
        end

        def railsrc(argv)
          if (customrc = argv.index { |x| x.include?("--rc=") })
            fname = File.expand_path(argv[customrc].gsub(/--rc=/, ""))
            yield(argv.take(customrc) + argv.drop(customrc + 1), fname)
          else
            yield argv, self.class.default_rc_file
          end
        end

        def read_rc_file(railsrc)
          extra_args = File.readlines(railsrc).flat_map(&:split)
          puts "Using #{extra_args.join(" ")} from #{railsrc}"
          extra_args
        end

        def insert_railsrc_into_argv!(argv, railsrc)
          return argv unless File.exist?(railsrc)
          extra_args = read_rc_file railsrc
          argv.take(1) + extra_args + argv.drop(1)
        end
    end
  end
end


text:
Bing
====

The Bing™ Maps REST Services Application Programming Interface (API)
provides a Representational State Transfer (REST) interface to
perform tasks such as creating a static map with pushpins, geocoding
an address, retrieving imagery metadata, or creating a route.
Using Geocoder you can retrieve Bing's geocoded data from Bing Maps REST Services.

Examples
~~~~~~~~

Basic Geocoding
---------------

.. code-block:: python

    >>> import geocoder # pip install geocoder
    >>> g = geocoder.bing('Mountain View, CA')
    >>> g.json
    ...

Reverse Geocoding
-----------------

.. code-block:: python

    >>> import geocoder
    >>> g = geocoder.bing([45.15, -75.14], method='reverse')
    >>> g.json
    ...

Command Line Interface
----------------------

.. code-block:: bash

    $ geocode 'Mountain View, CA' --provider bing
    $ geocode '45.15, -75.14' --provider bing --method reverse

Parameters
~~~~~~~~~~

- `location`: Your search location you want geocoded.
- `key`: use your own API Key from Bing.
- `method`: (default=geocode) Use the following:

  - geocode
  - reverse

References
~~~~~~~~~~

- `Bing Maps REST Services <http://msdn.microsoft.com/en-us/library/ff701714.aspx>`_


text:
require 'chefspec'

describe 'rpm_package::install' do
  let(:chef_run) do
    ChefSpec::ServerRunner.new(platform: 'centos', version: '7.3.1611')
                          .converge(described_recipe)
  end

  it 'installs a rpm_package with the default action' do
    expect(chef_run).to install_rpm_package('default_action')
    expect(chef_run).to_not install_rpm_package('not_default_action')
  end

  it 'installs a rpm_package with an explicit action' do
    expect(chef_run).to install_rpm_package('explicit_action')
  end

  it 'installs a rpm_package with attributes' do
    expect(chef_run).to install_rpm_package('with_attributes').with(version: '1.0.0')
    expect(chef_run).to_not install_rpm_package('with_attributes').with(version: '1.2.3')
  end

  it 'installs a rpm_package when specifying the identity attribute' do
    expect(chef_run).to install_rpm_package('identity_attribute')
  end
end


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jasperlu.filltoggle">
</manifest>


text:
"""
Tables for the account app
"""
from django.contrib.auth import get_user_model

import django_tables2 as tables

from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable, BooleanColumn

class UserListTable(PaginateTable):
    """
    Table for displaying users.
    """

    actions = ActionsColumn(
        [
            {
                'title': '',
                'url': 'accounts_user_change',
                'args': [tables.A('pk')],
                'attrs': {'data-toggle': 'tooltip', 'title': 'Edit User', 'data-delay': '{ "show": 300, "hide": 0 }'}
            },
            {
                'title': '',
                'url': 'accounts_user_delete',
                'args': [tables.A('pk')],
                'attrs': {'data-toggle': 'tooltip', 'title': 'Delete User', 'data-delay': '{ "show": 300, "hide": 0 }', 'class': 'js-delete'}
            },
        ],
        delimiter='   '
    )

    email = tables.LinkColumn('accounts_user_view', args=[tables.A('pk')], verbose_name='Email')
    first_name = tables.Column(verbose_name='First Name')
    last_name = tables.Column(verbose_name='Last Name')
    is_active = BooleanColumn(verbose_name='Active')
    user_level = tables.Column(verbose_name='User Level', accessor='group_strigify', order_by='groups')

    class Meta:
        model = get_user_model()
        sequence = fields = ('email', 'first_name', 'last_name', 'is_active', 'user_level', )
        attrs = {'class': 'table table-striped table-hover'}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Microsoft.Common.Core.Diagnostics;
using Microsoft.R.Components.InteractiveWorkflow;

namespace Microsoft.R.Components.Plots.Implementation.Commands {
    internal abstract class InteractiveWorkflowAsyncCommand {
        protected IRInteractiveWorkflow InteractiveWorkflow { get; }

        protected InteractiveWorkflowAsyncCommand(IRInteractiveWorkflow interactiveWorkflow) {
            Check.ArgumentNull(nameof(interactiveWorkflow), interactiveWorkflow);
            InteractiveWorkflow = interactiveWorkflow;
        }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHaveAYear.cs" company="OBeautifulCode">
//   Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace OBeautifulCode.AccountingTime
{
    /// <summary>
    /// Exposes a year.
    /// </summary>
    public interface IHaveAYear
    {
        /// <summary>
        /// Gets the year.
        /// </summary>
        int Year { get; }
    }
}


text:
{% load twitter_tags i18n %}

{% tweets_default as tweets %}

{% if tweets %}

    {% for tweet in tweets %}

{{ tweet.full_name }} @{{ tweet.user_name }}

            {% if tweet.is_retweet %}

            {{ tweet.retweeter_full_name }}

            {% endif %}

{{ tweet.text|safe }}

            {% blocktrans with sometime=tweet.created_at|timesince %}{{ sometime }} ago{% endblocktrans %}

    {% endfor %}

{% endif %}


text:
package openblocks.common.item;

import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import openblocks.Config;
import openmods.infobook.BookDocumentation;
import openmods.utils.EnchantmentUtils;
import openmods.utils.ItemUtils;
import openmods.utils.NbtUtils;

@BookDocumentation(hasVideo = true)
public class ItemCursor extends Item {

	// TODO maybe allow off-hand item use?
	public ItemCursor() {
		setMaxStackSize(1);
	}

	@Override
	public int getMaxItemUseDuration(ItemStack par1ItemStack) {
		return 50;
	}

	@Override
	public EnumActionResult onItemUse(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
		NBTTagCompound tag = ItemUtils.getItemTag(stack);
		tag.setInteger("dimension", world.provider.getDimension());
		NbtUtils.store(tag, pos);
		tag.setInteger("side", facing.ordinal());
		return EnumActionResult.SUCCESS;
	}

	@Override
	public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player, EnumHand hand) {
		if (!world.isRemote) {
			NBTTagCompound tag = stack.getTagCompound();
			if (tag != null && NbtUtils.hasCoordinates(tag) && tag.hasKey("dimension")) {
				final int dimension = tag.getInteger("dimension");

				final BlockPos pos = NbtUtils.readBlockPos(tag);
				if (world.provider.getDimension() == dimension && world.isBlockLoaded(pos)) {
					final EnumFacing side = NbtUtils.readEnum(tag, "side", EnumFacing.UP);
					clickBlock(world, player, hand, stack, pos, side);
				}
			}
		}
		return ActionResult.newResult(EnumActionResult.SUCCESS, stack);
	}

	private static void clickBlock(World world, EntityPlayer player, EnumHand hand, @Nullable ItemStack heldItem, BlockPos pos, EnumFacing side) {
		if (!world.isAirBlock(pos)) {
			final IBlockState state = world.getBlockState(pos);
			final double distanceToLinkedBlock = player.getDistanceSq(pos);
			if (distanceToLinkedBlock < Config.cursorDistanceLimit) {
				final Block block = state.getBlock();
				if (player.capabilities.isCreativeMode) {
					block.onBlockActivated(world, pos, state, player, hand, heldItem, side, 0, 0, 0);
				} else {
					final int cost = (int)Math.max(0, distanceToLinkedBlock - 10);
					final int playerExperience = EnchantmentUtils.getPlayerXP(player);
					if (cost <= playerExperience) {
						block.onBlockActivated(world, pos, state, player, hand, heldItem, side, 0, 0, 0);
						EnchantmentUtils.addPlayerXP(player, -cost);
					}
				}
			}
		}
	}

}


text:
/* jshint node: true */
'use strict';

require(__dirname + '/../setup');

var mongoose = require('mongoose');
var mongoConnection = require(__dirname + '/../config/mongoConnection');

mongoose.connect(mongoConnection.getConnectionString());
mongoose.connection.on('error', function (err) {
	if (err) {
		console.log(err);
	}
});

var buildUserBase = require(__dirname + '/buildUserBase.js');
var buildRequestBase = require(__dirname + '/buildRequestBase.js');
var clearDatabase = require(__dirname + '/clearDatabase.js');

clearDatabase(function (err) {
	if (err) {
		console.error(err);
	} else {
		buildUserBase(function (err) {
			if (err) {
				console.error(err);
			} else {
				buildRequestBase({ random: false }, function (err) {
					if (err) {
						console.error(err);
					} else {
						mongoose.connection.close();
					}
				});
			}
		});
	}
});


text:
package com.lmax.disruptor;

import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public final class SingleProducerSequencerTest
{
    private final SingleProducerSequencer sequencer = new SingleProducerSequencer(16, new BlockingWaitStrategy());
    private final Sequence initialGatingSequence = new Sequence();
    private final Sequence dynamicallyAddedGatingSequence = new Sequence();

    @Before
    public void setUp()
    {
        sequencer.addGatingSequences(initialGatingSequence);
    }

    @Test
    public void shouldApplyGatingSequence() throws Exception
    {
        sequencer.publish(sequencer.next());
        sequencer.publish(sequencer.next());
        sequencer.publish(sequencer.next());
        sequencer.publish(sequencer.next());
        sequencer.publish(sequencer.next());

        initialGatingSequence.set(1L);

        assertThat(sequencer.getCursor(), is(4L));
        assertTrue(sequencer.hasAvailableCapacity(13));
        assertFalse(sequencer.hasAvailableCapacity(14));
    }

    @Test
    public void shouldRespectDynamicallyAddedGatingSequence() throws Exception
    {
        sequencer.publish(sequencer.next());
        sequencer.publish(sequencer.next());
        sequencer.publish(sequencer.next());
        sequencer.publish(sequencer.next());
        sequencer.publish(sequencer.next());

        initialGatingSequence.set(1L);

        assertThat(sequencer.getCursor(), is(4L));
        assertTrue(sequencer.hasAvailableCapacity(13));
        assertFalse(sequencer.hasAvailableCapacity(14));

        sequencer.addGatingSequences(dynamicallyAddedGatingSequence);

        dynamicallyAddedGatingSequence.set(0L);

        assertTrue(sequencer.hasAvailableCapacity(12));
        assertFalse(sequencer.hasAvailableCapacity(13));
    }

}


text:
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Emgu.CV.Structure;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Size = System.Drawing.Size;

namespace Pentacorn.Vision
{
    static class Extensions
    {
        public static Rectangle Abs(this Rectangle that)
        {
            if (that.Width < 0)
                that = new Rectangle(that.X - that.Width, -that.Width, that.Y, that.Height);
            if (that.Height < 0)
                that = new Rectangle(that.X, that.Width, that.Y - that.Height, -that.Height);

            return that; // Todo, this function is stupid according to Jaap who wrote it.
        }

        public static void Invoke(this Control control, Action action)
        {
            control.Invoke((Delegate)action);
        }

        public static T Invoke<T>(this Control control, Func<T> func)
        {
            return (T)control.Invoke((Delegate)func);
        }

        public static Matrix WorldViewProjectionForPixels2d(this Viewport vp)
        {
            var projection = Matrix.CreateOrthographicOffCenter(0, vp.Width, vp.Height, 0, 0, 1);
            var halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
            return halfPixelOffset * projection;
        }

        public static Ray ThroughPixel(this BoundingFrustum bf, Vector3 orig, float x, float y, float imw, float imh)
        {
            var fx = x / imw;
            var fy = y / imh;

            var corners = bf.GetCorners();

            var left = Vector3.Lerp(corners[4], corners[7], fy);
            var right = Vector3.Lerp(corners[5], corners[6], fy);

            var pixel = Vector3.Lerp(left, right, fx);

            var dir = Vector3.Normalize((pixel - orig));
            return new Ray(orig, dir);
        }

        public static int Area(this Size s)
        {
            return s.Width * s.Height;
        }

        public static Bgra ToBgra(this Color color)
        {
            return new Bgra(color.B, color.G, color.R, color.A);
        }

        public static string ToSanitizedFileName(this string s)
        {
            string invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
            string invalidReStr = string.Format(@"[{0}]+", invalidChars);
            return Regex.Replace(s, invalidReStr, "_");
        }

        public static string Truncate(this string s, int maxLength)
        {
            if (string.IsNullOrEmpty(s) || maxLength <= 0)
                return string.Empty;
            else if (s.Length > (maxLength - 3))
                return s.Substring(0, maxLength - 3) + "...";
            else
                return s;
        }
    }
}


text:
const EventStream = require('event-stream')

function encapsulateStringArray (listOfVals) {
  return `"${listOfVals.map((val) => (val && typeof val === 'string') ? val.replace(/"/g, "'") : val).join(';')}"`
}

module.exports = {
  contentType: 'text/csv',
  serialize: function (req, res, next) {
    let fields = req.fieldSelection
    const header = req.fieldHeader

    if (req.isDownload) {
      res.attachment('BVBRC_' + req.call_collection + '.csv')
    }
    // console.log(`media type csv, call_method: ${req.call_method}`)

    if (req.call_method === 'stream') {
      Promise.all([res.results]).then((vals) => {
        const results = vals[0]
        let docCount = 0
        let head
        results.stream.pipe(EventStream.mapSync((data) => {
          if (!head) {
            head = data
          } else {
            if (!fields && docCount < 1) {
              fields = Object.keys(data)
            }
            if (docCount < 1) {
              if (header) {
                res.write(header.join(',') + '\n')
              } else {
                res.write(fields.join(',') + '\n')
              }
            }

            const row = fields.map((field) => {
              if (data[field] instanceof Array) {
                return encapsulateStringArray(data[field])
              } else if (data[field]) {
                if (typeof data[field] === 'string') {
                  return `"${data[field].replace(/"/g, "'")}"`
                } else {
                  return data[field]
                }
              } else {
                return ''
              }
            })
            res.write(row.join(',') + '\n')
            docCount++
          }
        })).on('end', () => {
          res.end()
        })
      }, (error) => {
        next(new Error(`Unable to receive stream: ${error}`))
      })
    } else if (req.call_method === 'query') {
      if (res.results && res.results.response && res.results.response.docs) {
        if (!fields) {
          fields = Object.keys(res.results.response.docs[0])
        }
        res.write(fields.join(',') + '\n')
        res.results.response.docs.forEach((data) => {
          const row = fields.map((field) => {
            if (data[field] instanceof Array) {
              return encapsulateStringArray(data[field])
            } else if (data[field]) {
              if (typeof data[field] === 'string') {
                return `"${data[field].replace(/"/g, "'")}"`
              } else {
                return data[field]
              }
            } else {
              return ''
            }
          })

          res.write(row.join(',') + '\n')
        })
        res.end()
      }
    } else {
      next(new Error('Unable to serialize request to csv'))
    }
  }
}


text:
import MySQLdb
import credentials
import json

class Restaurant(object):
    def __init__(self, rid, name, address, city, state, zip_code, phone, website, twitter, lat, lng):
        self.rid = rid
        self.name = name
        self.address = address
        self.city = city
        self.state = state
        self.zip_code = zip_code
        self.phone = phone
        self.website = website
        self.twitter = twitter
        self.lat = lat
        self.lng = lng

    def __str__(self):
        return "rid: " + str(self.rid) + "name: " + str(self.name) + "address: " + str(self.address) + "city: " + str(self.city) + "state: " + str(self.state) + "zip_code: " + str(self.zip_code) + "phone: " + str(self.phone) + "website: " + str(self.website) + "twitter: " + str(self.twitter) + "lat: " + str(self.lat) + "lng: " + str(self.lng)

    def __json__(self):
        json_object = {}
        json_object["rid"] = str(self.rid)
        json_object["name"] = str(self.name)
        json_object["address"] = str(self.address)
        json_object["city"] = str(self.city)
        json_object["state"] = str(self.state)
        json_object["zip"] = str(self.zip_code)
        json_object["phone"] = str(self.phone)
        json_object["website"] = str(self.website)
        json_object["twitter"] = str(self.twitter)
        json_object["lat"] = str(self.lat)
        json_object["lng"] = str(self.lng)
        return json_object

    def save(self):
        """
        Saves this Restaurant to the database.
        """

        # Get new database instance
        db = credentials.getDatabase()

        cur = db.cursor()
        query = '''INSERT IGNORE INTO restaurants
                VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);'''

        data = (self.rid, self.name, self.address, self.city, self.state, self.zip_code, self.phone, self.website, self.twitter, self.lat, self.lng)
        cur.execute(query, data)

        # commit query
        db.commit()
        db.close()

def load(rid):
    """
    Args:
        rid: restaurant id

    Returns:
        The restaurant object with this id.
    """
    # Get new database instance
    db = credentials.getDatabase()

    cur = db.cursor()
    query = '''SELECT * FROM restaurants WHERE rid = %s;'''
    cur.execute(query, rid)

    rest = ""
    for tup in cur:
        rest = Restaurant(tup[0], tup[1], tup[2], tup[3], tup[4], tup[5], tup[6], tup[7], tup[8], tup[9], tup[10])

    # commit query
    db.commit()
    db.close()

    return rest

def loadAll():
    """
    Returns:
        A list of all restaurants.
    """
    # Get new database instance
    db = credentials.getDatabase()

    cur = db.cursor()
    query = '''SELECT * FROM restaurants;'''
    cur.execute(query)

    result = []
    for tup in cur:
        result.append(Restaurant(tup[0], tup[1], tup[2], tup[3], tup[4], tup[5], tup[6], tup[7], tup[8], tup[9], tup[10]))

    # commit query
    db.commit()
    db.close()

    return result

def isUnique(rid):
    """
    Args:
        rid: restaurant id

    Returns:
        True if the restaurant id does not exist in the database.
    """
    # Get new database instance
    db = credentials.getDatabase()

    cur = db.cursor()
    query = '''SELECT COUNT(*) FROM restaurants WHERE rid=%s;'''
    cur.execute(query, [rid])

    result = 0
    for tup in cur:
        result = tup[0]

    # commit query
    db.commit()
    db.close()

    return result == 0

# test = load('4c6c32b0e13db60c0265d5b1').__json__()
# print(test)


text:
export emrbootstrap="s3://elasticmapreduce/bootstrap-actions/configure-daemons"
export hadoopbootstrap="s3://elasticmapreduce/bootstrap-actions/configure-hadoop"
export appbootstrap="s3://ori-emrscript/bin2seq-emr-bootstrap.sh"
export emrlog="s3://ori-tmp/emr-log/"
export keypair="gsg-keypair"
#export args="--replace --namenode-heap-size=10240,--datanode-heap-size=10240,--client-heap-size=10240,--namenode-opts=-XX:+UseCompressedOops,--jobtracker-opts=-XX:+UseCompressedOops,--tasktracker-opts=-XX:+UseCompressedOops, -m,mapred.child.java.opts=-Xmx10240"
export args="--namenode-heap-size=4096,--datanode-heap-size=4096,--client-heap-size=4096,--namenode-opts=-XX:+UseCompressedOops,--client-opts=mapred.map.child.java.opts=-Xmx4G"
export clustername="bin2seq"
export amiversion="3.3.1"
export instance="r3.xlarge" #"m3.xlarge"
export cores="1"
export tasks="1"

#clean up log from previous runs
aws s3 rm --recursive $emrlog

#Query the cheapest price for EMR instance
export bidprice=`aws ec2 describe-spot-price-history --instance-types $instance --product-descriptions Linux/UNIX |grep SpotPrice |sort |head -n 1 |cut -d':' -f2 | sed -e 's/"//g' -e 's/,//g' |awk '{print $1 + 0.01}'  |cut -c1-4` #lowest bid + $0.01
echo "biding price="$bidprice
#create EMR cluster
aws emr create-cluster --name $clustername --enable-debugging --log-uri $emrlog  --ec2-attributes KeyName=$keypair --ami-version $amiversion \
--bootstrap-actions Path=$emrbootstrap,Name="Set VM parameters",Args=[$args] \
--bootstrap-actions Path=$hadoopbootstrap,Name="Set Hadoop paramters",Args=["-m,mapreduce.map.java.opts=-Xmx4G"] \
Path=$appbootstrap,Name="Install dependencies" \
--instance-groups \
Name=Master,InstanceGroupType=MASTER,InstanceCount=1,BidPrice=$bidprice,Name=Master,InstanceType=$instance \
Name=Core,InstanceGroupType=CORE,BidPrice=$bidprice,InstanceCount=$cores,InstanceType=$instance \
Name=Task,InstanceGroupType=TASK,BidPrice=$bidprice,InstanceCount=$tasks,InstanceType=$instance

#Path=$emrbootstrap,Name="Set Client Opts",Args=[$opts] \
#elastic-mapreduce --jobflow $jobid --jar /home/hadoop/lib/emr-s3distcp-1.0.jar --args '--src,s3://ori-msd10k-seq/,--dest,hdfs:///msd10k'
#elastic-mapreduce --jobflow $jobid --jar /home/hadoop/lib/emr-s3distcp-1.0.jar --args '--src,s3://ori-colorferet-seq/,--dest,hdfs:///colorferet'


text:
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Designcoil_GroupedTierPrices>
            <active>true</active>
            <codePool>community</codePool>
        </Designcoil_GroupedTierPrices>
    </modules>
</config>


text:
class Survey < ActiveRecord::Base
  belongs_to :creator, class_name: "User"
  has_many :completed_surveys, class_name: "Completion"
  has_many :survey_takers, class_name: "User", through: :completions
  has_many :questions
end


text:
<?php

namespace Doctrine\DBAL\Exception;

/**
 * Exception for a write operation attempt on a read-only database element detected in the driver.
 *
 * @psalm-immutable
 */
class ReadOnlyException extends ServerException
{
}


text:
describe("Base Node", function () {
    var apiNode;
    var NodeType = ozpIwc.api.base.Node;
    beforeEach(function () {
        apiNode = new NodeType({
            resource: "/foo",
            version: 50,
            self: {href: "https://example.com/iwc/foo"},
            contentType: "text/plain",
            entity: {
                msg: "hello world",
                _links: {
                    self: {href: "https://example.com/iwc/foo"},
                    "ozp:iwcSelf": {href: "web+ozp://test.api/foo"}
                }
            }
        });
    });

    it("fails if constructed without a resource", function () {
        expect(function () {
            new NodeType();
        }).toThrow();
    });
    it("deserializes and serializes live data with the same outcome", function () {
        var serialized = apiNode.serializeLive();
        var node2 = new NodeType({resource: "/foo"});
        node2.deserializeLive(serialized);
        expect(node2).toEqual(apiNode);
    });

    it("a set with etag properly updates the version", function () {
        apiNode.set({
            entity: "goodbye world",
            eTag: 100
        });
        expect(apiNode.entity).toEqual("goodbye world");
        expect(apiNode.version).toEqual(100);
    });
    var serializedFields = ["entity", "resource", "self"];
    it("deserializes and serializes persisted data with the same outcome", function () {
        var node2 = new NodeType({resource: "/foo"});
        node2.deserialize(apiNode.serialize(), NodeType.serializedContentType);
        serializedFields.forEach(function (k) {
            expect(node2[k]).toEqual(apiNode[k]);
        });

    });

    it("deserializes and serializes persisted data with the same outcome using the constructor", function () {
        var node2 = new NodeType({
            serializedEntity: apiNode.serialize(),
            serializedContentType: NodeType.serializedContentType
        });
        serializedFields.forEach(function (k) {
            expect(node2[k]).toEqual(apiNode[k]);
        });
    });

    it("deserializes and serializes persisted data with the same outcome using the constructor without content type", function () {
        var node2 = new NodeType({
            serializedEntity: apiNode.serialize()
        });
        serializedFields.forEach(function (k) {
            expect(node2[k]).toEqual(apiNode[k]);
        });
    });
    it("sets up it's uri from a template", function () {
        // only defined if initEndpoints is called, so we define it here
        // rather than spyOn()
        ozpIwc.api.uriTemplate = function () {
            return {
                name: "ozp:data-item",
                href: "http://example.com/{+resource}",
                type: NodeType.serializedContentType

            };
        };
        var node = new NodeType({
            resource: "/foo",
            version: 50,
            uriTemplate: "doesn't matter since it's mocked",
            contentType: "text/plain",
            entity: "hello world"
        });

        expect(node.self).toEqual({type: node.contentType});
        node.self = node.getSelfUri();
        expect(node.self.href).toEqual("http://example.com/foo");
        expect(node.self.type).toEqual(NodeType.serializedContentType);
    });
});