text:
namespace Google.Cloud.Recommender.V1.Snippets
{
    // [START recommender_v1_generated_Recommender_MarkRecommendationFailed_sync_flattened]
    using Google.Cloud.Recommender.V1;
    using System.Collections.Generic;

    public sealed partial class GeneratedRecommenderClientSnippets
    {
        /// <summary>Snippet for MarkRecommendationFailed</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void MarkRecommendationFailed()
        {
            // Create client
            RecommenderClient recommenderClient = RecommenderClient.Create();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/locations/[LOCATION]/recommenders/[RECOMMENDER]/recommendations/[RECOMMENDATION]";
            IDictionary<string, string> stateMetadata = new Dictionary<string, string> { { "", "" }, };
            string etag = "";
            // Make the request
            Recommendation response = recommenderClient.MarkRecommendationFailed(name, stateMetadata, etag);
        }
    }
    // [END recommender_v1_generated_Recommender_MarkRecommendationFailed_sync_flattened]
}

redpajama_set_name: RedPajamaGithub


text:
CKEDITOR.plugins.setLang("a11yhelp", "oc", {
    title: "Instruccions d'accessibilitat",
    contents: "Contengut de l'ajuda. Per tampar aquesta fenèstra, quichatz sus la tòca Escap.",
    legend: [{
        name: "General",
        items: [{
            name: "Barra d'aisinas de l'editor",
            legend: "Quichar sus ${toolbarFocus} per accedir a la barra d'aisinas. Se desplaçar cap al groupe seguent o precedent de la barra d'aisinas amb las tòcas Tab e Maj+Tab. Se desplaçar cap al boton seguent o precedent de la barra d'aisinas amb las tòcas Sageta dreita e Sageta esquèrra. Quichar sus la barra d'espaci o la tòca Entrada per activer lo boton de barra d'aisinas."
        },
            {
                name: "Fenèstra de l'editor",
                legend: "Dins una bóstia de dialòg, quichar sus Tab per passar a l'element seguent, quichar sus Maj+Tab per passar a l'element precedent, quichar sus Entrada per validar, quichar sus Escap per anullar. Quand una bóstia de dialòg possedís des onglets, la lista pòt èsser atenta amb Alt+F10 o amb Tab. Dins la lista dels onglets, se desplaçar cap al seguent e lo precedent amb las tòcas Sageta dreita e Sageta esquèrra respectivament."
            }, {
                name: "Menú contextual de l'editor",
                legend: "Quichar sus ${contextMenu} o sus la tòca Menú per dobrir lo menú contextual. Se desplaçar ensuite cap a l'opcion seguenta del menú amb las tòcas Tab o Sageta bas. Se desplaçar cap a l'opcion precedenta amb las tòcas Maj+Tab o Sageta naut. Quichar sus la barra d'espaci o la tòca Entrada per seleccionar l'opcion del menu. Quichar sus la barra d'espaci, la tòca Entrada o Sageta dreita per dobrir lo sosmenú de l'opcion seleccionada. Tornar a l'element de menú parent amb la tòca Escap o Sageta esquèrra. Tampar lo menú contextual amb Escap."
            },
            {
                name: "Zòna de lista de l'editor",
                legend: "Dins una lista en menú desenrotlant, se desplaçar cap a l'element seguent de la lista amb las tòcas Tab o Sageta bas. Se desplaçar cap a l'element precedent de la lista amb las tòcas Maj+Tab o Sageta naut. Quichar sus la barra d'espaci o sus Entrada per seleccionar l'opcion dins la lista. Quichar sus Escap per tampar lo menú desenrotlant."
            }, {
                name: "Barra del camin d'elements de l'editor",
                legend: "Quichar sus ${elementsPathFocus} per naviguer cap a la barra del fial d'Ariana dels elements. Se desplaçar cap al boton de l'element seguent amb las tòcas Tab o Sageta dreita. Se desplaçar cap al boton precedent amb las tòcas Maj+Tab o Sageta esquèrra. Quichar sus la barra d'espaci o sus Entrada per seleccionar l'element dins l'editor."
            }]
    },
        {
            name: "Comandas",
            items: [{name: "Anullar la comanda", legend: "Quichar sus ${undo}"}, {
                name: "Comanda restablir",
                legend: "Quichar sus ${redo}"
            }, {name: " Comanda gras", legend: "Quichar sus ${bold}"}, {
                name: " Comanda italica",
                legend: "Quichar sus ${italic}"
            }, {name: " Comanda solinhat", legend: "Quichar sus ${underline}"}, {
                name: " Comanda ligam",
                legend: "Quichar sus ${link}"
            }, {name: "Comanda enrotlar la barra d'aisinas", legend: "Quichar sus ${toolbarCollapse}"}, {
                name: "Comanda d'accès a l'element seleccionable precedent",
                legend: "Quichar sus ${accessNextSpace} per accedir a l'element seleccionable inategnible lo mai pròche abans lo cursor, per exemple : doas linhas orizontalas adjacentas. Repetir la combinason de tòcas per aténher los elements seleccionables precedents."
            }, {
                name: "Comanda d'accès a l'element seleccionable seguent",
                legend: "Quichar sus ${accessNextSpace} per accedir a l'element seleccionable inatenhible lo mai pròche aprèp lo cursor, per exemple : doas linhas orizontalas adjacentas. Repetir la combinason de tòcas per aténher los elements seleccionables seguents."
            },
                {name: " Ajuda sus l'accessibilitat", legend: "Quichar sus ${a11yHelp}"}]
        }],
    tab: "Tabulacion",
    pause: "Pausa",
    capslock: "Verr. Maj.",
    escape: "Escap",
    pageUp: "Pagina superiora",
    pageDown: "Pagina seguenta",
    leftArrow: "Sageta esquèrra",
    upArrow: "Sageta naut",
    rightArrow: "Sageta dreita",
    downArrow: "Sageta bassa",
    insert: "Inser",
    leftWindowKey: "Tòca Windows esquèrra",
    rightWindowKey: "Tòca Windows dreita",
    selectKey: "Tòca Seleccionar",
    numpad0: "0 del pavat numeric",
    numpad1: "1 del pavat numeric",
    numpad2: "2 del pavat numeric",
    numpad3: "3 del pavat numeric",
    numpad4: "4 del pavat numeric",
    numpad5: "5 del pavat numeric",
    numpad6: "6 del pavat numeric",
    numpad7: "7 del pavat numeric",
    numpad8: "Pavat numeric 8",
    numpad9: "9 del pavat numeric",
    multiply: "Multiplicar",
    add: "Plus",
    subtract: "Mens",
    decimalPoint: "Punt decimal",
    divide: "Devesir",
    f1: "F1",
    f2: "F2",
    f3: "F3",
    f4: "F4",
    f5: "F5",
    f6: "F6",
    f7: "F7",
    f8: "F8",
    f9: "F9",
    f10: "F10",
    f11: "F11",
    f12: "F12",
    numLock: "Verr. Num.",
    scrollLock: "Arrèst desfil.",
    semiColon: "Punt-virgula",
    equalSign: "Signe egal",
    comma: "Virgula",
    dash: "Jonhent",
    period: "Punt",
    forwardSlash: "Barra oblica",
    graveAccent: "Accent grèu",
    openBracket: "Parentèsi dobèrta",
    backSlash: "Barra oblica invèrsa",
    closeBracket: "Parentèsi tampanta",
    singleQuote: "Apostròfa"
});


text:
/**
 * @author shirishgoyal
 * created on 16.12.2015
 */
(function () {
    'use strict';

    angular.module('BlurAdmin.pages.page', [])
        .config(routeConfig);

    /** @ngInject */
    function routeConfig($stateProvider) {
        $stateProvider
            .state('page', {
                url: '/page',
                abstract: true,
                views: {
                    'full_screen': {
                        templateUrl: 'app/pages/page/index.html'
                    }
                },
                authenticate: false
            })
            .state('page.home', {
                url: '/home',
                templateUrl: 'app/pages/page/home.html',
                controller: 'PageCtrl',
                controllerAs: 'vm',
                authenticate: false
            })
            .state('page.rules', {
                url: '/rules',
                templateUrl: 'app/pages/page/rules.html',
                controller: 'PageCtrl',
                controllerAs: 'vm',
                authenticate: false
            })
            .state('page.faq', {
                url: '/faq',
                templateUrl: 'app/pages/page/faq.html',
                controller: 'PageCtrl',
                controllerAs: 'vm',
                authenticate: false
            })
            .state('page.technical', {
                url: '/technical',
                templateUrl: 'app/pages/page/technical.html',
                controller: 'PageCtrl',
                controllerAs: 'vm',
                authenticate: false
            })
            .state('page.contact', {
                url: '/contact',
                templateUrl: 'app/pages/page/contact.html',
                controller: 'PageCtrl',
                controllerAs: 'vm',
                authenticate: false
            })
        ;
    }

})();


text:
package com.google.vrtoolkit.cardboard.samples.treasurehunt;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;

/**
 * Created by Mayank on 11/15/2015.
 */
public class CameraPreviewDeuteranopia extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback{
    private int test = 0;
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private ImageView mFilteredImageView;
    private ImageView mFilteredImageViewRight;
    private static String TAG = CameraPreview.class.getName();
    public CameraPreviewDeuteranopia(Context context, Camera camera, ImageView filteredImageView, ImageView filteredImageViewRight) {
        super(context);
        mCamera = camera;
        mFilteredImageView = filteredImageView;
        mFilteredImageViewRight = filteredImageViewRight;
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.

        try {
            //  holder.setFormat(PixelFormat.TRANSPARENT);
            mCamera.setPreviewDisplay(holder);
            //TODO @see associated with previewCallback
            mCamera.setPreviewCallback(this);
            mCamera.startPreview();
        } catch (Exception e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the com.google.vrtoolkit.cardboard.samples.treasurehunt.CameraActivity preview in your activity.
        try {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
            e.printStackTrace();
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here
        // start preview with new settings

        try {
            mCamera.setPreviewDisplay(mHolder);
            //TODO if view is not fixed @see https://stackoverflow.com/questions/14412618/android-onpreviewframe-is-not-called
            mCamera.setPreviewCallback(this);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        // System.arraycopy(data, 0, mData, 0, data.length);

        int size = data.length;
        Camera.Size previewSize = camera.getParameters().getPreviewSize();
        ColorblindnessDeuteranopiaFilter colorblindnessTestFilter = new ColorblindnessDeuteranopiaFilter(getContext(),mFilteredImageView,mFilteredImageViewRight, camera);
        colorblindnessTestFilter.execute(data);

    }
}


text:
'use strict';

var React = require('react');
var mui = require('material-ui');
var SvgIcon = mui.SvgIcon;

var ImageFlashOn = React.createClass({
  displayName: 'ImageFlashOn',

  render: function render() {
    return React.createElement(
      SvgIcon,
      this.props,
      React.createElement('path', { d: 'M7 2v11h3v9l7-12h-4l4-8z' })
    );
  }

});

module.exports = ImageFlashOn;


text:
<?php
// Quick and dirty navigation.
$menu_item_default = 'index';
$menu_items = array(
    'index' => array(
        'label' => 'Home',
        'desc' => 'A list of all my magazines',
    ),
    'add' => array(
        'label' => 'Add',
        'desc' => 'Add a magazine to my collection',
    ),
);

// Determine the current menu item.
$menu_current = $menu_item_default;
// If there is a query for a specific menu item and that menu item exists...
if (@array_key_exists($this->uri->segment(2), $menu_items)) {
    $menu_current = $this->uri->segment(2);
}
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Launch My Empire</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

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

    <link href="<?php echo base_url(); ?>css/font-awesome.min.css" rel="stylesheet">

    <link href="<?php echo base_url(); ?>css/pace.css" rel="stylesheet">

    <link href="<?php echo base_url(); ?>css/colorbox/colorbox.css" rel="stylesheet">

    <link href="<?php echo base_url(); ?>css/morris.css" rel="stylesheet"/>

    <link href='<?php echo base_url(); ?>css/fullcalendar.css' rel='stylesheet' />

    <link href="<?php echo base_url(); ?>css/jquery.dataTables_themeroller.css" rel="stylesheet">

    <link href="<?php echo base_url(); ?>css/endless.css" rel="stylesheet">
    <link href="<?php echo base_url(); ?>css/endless-skin.css" rel="stylesheet">

    <link href="<?php echo base_url(); ?>css/custom.css" rel="stylesheet">

        Skin Color

        Sidebar Menu

            <input type="checkbox" checked id="fixedSidebar">

            Fixed Sidebar

    <?php /*?>

            <img src="<?php echo base_url()."img/mylogo.png"; ?>" style=" margin-top: -6px;" />

        <button type="button" class="navbar-toggle pull-left" id="sidebarToggle">

        </button>

                    <?php echo "Settings";  ?>

                            <img src="<?php echo base_url(); ?>img/profile/<?php echo $userdata['image']; ?>" alt="User Avatar">

                                <?php echo $userdata['full_name']; ?>

<?php echo $userdata['email']; ?>

<a tabindex="-1" href="<?php echo base_url(); ?>home/profile" class="main-link"> Edit profile

 Log out

<?php */?>


text:
namespace LiveCharts
{
    /// <summary>
    /// Separator current state
    /// </summary>
    public enum SeparationState
    {
        /// <summary>
        /// Remove the separator from the chart
        /// </summary>
        Remove,
        /// <summary>
        /// Kepp the separator in the chart
        /// </summary>
        Keep,
        /// <summary>
        /// no animated add
        /// </summary>
        InitialAdd
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('debate', '0015_auto_20170821_1636'),
    ]

    operations = [
        migrations.AddField(
            model_name='debatetopic',
            name='article_URL',
            field=models.URLField(blank=True),
        ),
        migrations.AddField(
            model_name='debatetopic',
            name='cover_photo',
            field=models.ImageField(blank=True, upload_to=b''),
        ),
    ]


text:
{% extends "base/backend_master.html" %}

{% block title %} Income Statement - {{ month_year | date:"F,Y" }} {% endblock %}

{% block childPage %}

Income Statement For {{ month_year | date:"F,Y" }}

                            <button type="button" class="btn btn-default btn-circle-lg waves-effect waves-circle waves-float btnPrint pull-right no-print" style="top:-10px;">
                                print
                            </button>

                                <form method="GET" action="{% url 'report.incomes' %}" enctype="multipart/form-data">

                                                <input type="text" value="{{ month_year | date:"Y-m"}}" class="datepicker3 form-control" placeholder="Please choose a month..." name="monthYear" required>

Month

                                        <button class="btn btn-circle-lg btn-primary waves-effect" type="submit">GET</button>

                                </form>

                                        Amount (tk)
                                        Amount (tk)

                                        {% for transaction in income_statements %}

                                                    {{ transaction.title | safe }}

                                                    {{ transaction.amount_column_1|floatformat:2 }}

                                                    {{ transaction.amount_column_2 | safe }}

                                        {% endfor %}

{% endblock %}

{% block child_page_js %}

{% endblock %}


text:
import { getCwdPath } from '../../testHelpers/cwd';
import { createCosmosConfig } from '..';

it('returns resolved default getUserDepsFilePath', () => {
  const cosmosConfig = createCosmosConfig(process.cwd());
  expect(cosmosConfig.userDepsFilePath).toBe(getCwdPath('cosmos.userdeps.js'));
});

it('returns resolved custom getUserDepsFilePath', () => {
  const cosmosConfig = createCosmosConfig(process.cwd(), {
    userDepsFilePath: 'heremydeps.js',
  });
  expect(cosmosConfig.userDepsFilePath).toBe(getCwdPath('heremydeps.js'));
});


text:
<?php
namespace OpenSearchServer\Search\Field;

use OpenSearchServer\Search\Search as Search;

abstract class SearchField extends Search
{
	const SEARCH_MODE_PATTERN = 'PATTERN';
	const SEARCH_MODE_TERM = 'TERM';
	const SEARCH_MODE_PHRASE = 'PHRASE';
	const SEARCH_MODE_TERM_AND_PHRASE = 'TERM_AND_PHRASE';

	/**
	 * Add a field to search into
	 * @return OpenSearchServer\Search\Search
	 */
	public function searchField($field, $mode = self::SEARCH_MODE_PATTERN, $boost = 1, $phraseBoost = 1) {
		if(empty($this->data['searchFields'])) {
			$this->data['searchFields'] = array();
		}
		$this->data['searchFields'][] = array(
			'field' => $field,
			'mode' => $mode,
			'boost' => $boost,
			'phraseBoost' => $phraseBoost
		);
		return $this;
	}

	/******************************
	 *     HELPER AND ALIASES
	 ******************************/
	/**
	 * Helper method: add several searchFields with same parameters
	 */
	public function searchFields(array $fields, $mode = self::SEARCH_MODE_PATTERN, $boost = 1, $phraseBoost = 2) {
		foreach($fields as $field) {
			$this->searchField($field, $mode, $boost, $phraseBoost);
		}
		return $this;
	}
}


text:
<?php

namespace Functional\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 */
class DomainContractMutation extends ContractMutation
{
    /**
     * @ORM\Column(type="string")
     */
    private $domain;

    /**
     * @return string
     */
    public function getDomain()
    {
        return $this->domain;
    }

    /**
     * @param Contract $original
     */
    protected function absorb(Contract $original)
    {
        if (!($original instanceof DomainContract)) {
            throw new \InvalidArgumentException(sprintf(
                'DomainContractMutation can only be created from DomainContract entities, "%s" given',
                get_class($original)
            ));
        }

        parent::absorb($original);

        $this->domain = $original->getDomain();
    }
}


text:
'use strict';

const Support   = require('../support'),
  expectsql = Support.expectsql,
  current   = Support.sequelize,
  sql       = current.dialect.queryGenerator;

// Notice: [] will be replaced by dialect specific tick/quote character when there is not dialect specific expectation but only a default expectation

if (current.dialect.name !== 'sqlite') {
  describe(Support.getTestDialectTeaser('SQL'), () => {
    describe('removeColumn', () => {
      it('schema', () => {
        expectsql(sql.removeColumnQuery({
          schema: 'archive',
          tableName: 'user'
        }, 'email'), {
          mssql: 'ALTER TABLE [archive].[user] DROP COLUMN [email];',
          mariadb: 'ALTER TABLE `archive`.`user` DROP `email`;',
          mysql: 'ALTER TABLE `archive.user` DROP `email`;',
          postgres: 'ALTER TABLE "archive"."user" DROP COLUMN "email";'
        });
      });
    });
  });
}


text:
package org.apache.activemq.artemis.protocol.amqp.broker;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;

import io.netty.channel.ChannelPipeline;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.BaseInterceptor;
import org.apache.activemq.artemis.api.core.Interceptor;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.protocol.amqp.proton.AMQPConstants;
import org.apache.activemq.artemis.protocol.amqp.converter.ProtonMessageConverter;
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyServerConnection;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.management.Notification;
import org.apache.activemq.artemis.core.server.management.NotificationListener;
import org.apache.activemq.artemis.jms.client.ActiveMQDestination;
import org.apache.activemq.artemis.spi.core.protocol.ConnectionEntry;
import org.apache.activemq.artemis.spi.core.protocol.MessageConverter;
import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager;
import org.apache.activemq.artemis.spi.core.protocol.ProtocolManagerFactory;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.activemq.artemis.spi.core.remoting.Acceptor;
import org.apache.activemq.artemis.spi.core.remoting.Connection;
import org.apache.activemq.artemis.protocol.amqp.proton.AMQPConnectionContext;

/**
 * A proton protocol manager, basically reads the Proton Input and maps proton resources to ActiveMQ Artemis resources
 */
public class ProtonProtocolManager implements ProtocolManager<Interceptor>, NotificationListener {

   private static final List<String> websocketRegistryNames = Arrays.asList("amqp");

   private final ActiveMQServer server;

   private MessageConverter protonConverter;

   private final ProtonProtocolManagerFactory factory;

   /*
   * used when you want to treat senders as a subscription on an address rather than consuming from the actual queue for
   * the address. This can be changed on the acceptor.
   * */
   private String pubSubPrefix = ActiveMQDestination.JMS_TOPIC_ADDRESS_PREFIX;

   private int maxFrameSize = AMQPConstants.Connection.DEFAULT_MAX_FRAME_SIZE;

   public ProtonProtocolManager(ProtonProtocolManagerFactory factory, ActiveMQServer server) {
      this.factory = factory;
      this.server = server;
      this.protonConverter = new ProtonMessageConverter(server.getStorageManager());
   }

   public ActiveMQServer getServer() {
      return server;
   }

   @Override
   public MessageConverter getConverter() {
      return protonConverter;
   }

   @Override
   public void onNotification(Notification notification) {

   }

   @Override
   public ProtocolManagerFactory<Interceptor> getFactory() {
      return factory;
   }

   @Override
   public void updateInterceptors(List<BaseInterceptor> incomingInterceptors,
                                  List<BaseInterceptor> outgoingInterceptors) {
      // no op
   }

   @Override
   public boolean acceptsNoHandshake() {
      return false;
   }

   @Override
   public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed, Connection remotingConnection) {
      AMQPConnectionCallback connectionCallback = new AMQPConnectionCallback(this, remotingConnection, server.getExecutorFactory().getExecutor(), server);
      long ttl = ActiveMQClient.DEFAULT_CONNECTION_TTL;

      if (server.getConfiguration().getConnectionTTLOverride() != -1) {
         ttl = server.getConfiguration().getConnectionTTLOverride();
      }

      String id = server.getConfiguration().getName();
      AMQPConnectionContext amqpConnection =
         new AMQPConnectionContext(connectionCallback, id, (int) ttl, getMaxFrameSize(), AMQPConstants.Connection.DEFAULT_CHANNEL_MAX, server.getExecutorFactory().getExecutor(), server.getScheduledPool());

      Executor executor = server.getExecutorFactory().getExecutor();

      ActiveMQProtonRemotingConnection delegate = new ActiveMQProtonRemotingConnection(this, amqpConnection, remotingConnection, executor);

      connectionCallback.setProtonConnectionDelegate(delegate);

      ConnectionEntry entry = new ConnectionEntry(delegate, executor, System.currentTimeMillis(), ttl);

      return entry;
   }

   @Override
   public void removeHandler(String name) {

   }

   @Override
   public void handleBuffer(RemotingConnection connection, ActiveMQBuffer buffer) {
      ActiveMQProtonRemotingConnection protonConnection = (ActiveMQProtonRemotingConnection) connection;

      protonConnection.bufferReceived(protonConnection.getID(), buffer);
   }

   @Override
   public void addChannelHandlers(ChannelPipeline pipeline) {

   }

   @Override
   public boolean isProtocol(byte[] array) {
      return array.length >= 4 && array[0] == (byte) 'A' && array[1] == (byte) 'M' && array[2] == (byte) 'Q' && array[3] == (byte) 'P';
   }

   @Override
   public void handshake(NettyServerConnection connection, ActiveMQBuffer buffer) {
   }

   @Override
   public List<String> websocketSubprotocolIdentifiers() {
      return websocketRegistryNames;
   }

   public String getPubSubPrefix() {
      return pubSubPrefix;
   }

   public void setPubSubPrefix(String pubSubPrefix) {
      this.pubSubPrefix = pubSubPrefix;
   }

   public int getMaxFrameSize() {
      return maxFrameSize;
   }

   public void setMaxFrameSize(int maxFrameSize) {
      this.maxFrameSize = maxFrameSize;
   }
}


text:
\chapter{CONCLUSÕES E SUGESTÕES PARA FUTUROS TRABALHOS}\label{ch:conclusao}
\section{CONCLUSÕES}
O uso das bibliotecas que Python oferece para a mineração de dados permite que o desenvolvimento das soluções se tornem mais rápidos e efetivos. Assim como a utilização da API do \textit{Twitter} para a obtenção dos dados e as etapas do processo de \textit{data mining}.

\section{SUGESTÕES PARA FUTUROS TRABALHOS}

%
%- Resgatar o objetivo
%- Comentar as ferramentas estudadas
%- Comentar as ferramentas utilizadas
%- Breve resumo dos resultados
%- Pontos positivos e negativos (O fato de não ter o perfil real)
%
%7.2
%Pensar em outra API (Aplicação para previsão de resultados) ou rede social, baseando-se numa pergunta específica


text:
"""
PyExifTool is a Python library to communicate with an instance of Phil
Harvey's excellent ExifTool_ command-line application.  The library
provides the class :py:class:`ExifTool` that runs the command-line
tool in batch mode and features methods to send commands to that
program, including methods to extract meta-information from one or
more image files.  Since ``exiftool`` is run in batch mode, only a
single instance needs to be launched and can be reused for many
queries.  This is much more efficient than launching a separate
process for every single query.

.. _ExifTool: http://www.sno.phy.queensu.ca/~phil/exiftool/

The source code can be checked out from the github repository with

::

    git clone git://github.com/smarnach/pyexiftool.git

Alternatively, you can download a tarball_.  There haven't been any
releases yet.

.. _tarball: https://github.com/smarnach/pyexiftool/tarball/master

PyExifTool is licenced under GNU GPL version 3 or later.

Example usage::

    import exiftool

    files = ["a.jpg", "b.png", "c.tif"]
    with exiftool.ExifTool() as et:
        metadata = et.get_metadata_batch(files)
    for d in metadata:
        print("{:20.20} {:20.20}".format(d["SourceFile"],
                                         d["EXIF:DateTimeOriginal"]))
"""

from __future__ import unicode_literals

import sys
import subprocess
import os
import json
import warnings
import codecs

try:        # Py3k compatibility
    basestring
except NameError:
    basestring = (bytes, str)

executable = "exiftool"
"""The name of the executable to run.

If the executable is not located in one of the paths listed in the
``PATH`` environment variable, the full path should be given here.
"""

# Sentinel indicating the end of the output of a sequence of commands.
# The standard value should be fine.
sentinel = b"{ready}"

# The block size when reading from exiftool.  The standard value
# should be fine, though other values might give better performance in
# some cases.
block_size = 4096

# This code has been adapted from Lib/os.py in the Python source tree
# (sha1 265e36e277f3)
def _fscodec():
    encoding = sys.getfilesystemencoding()
    errors = "strict"
    if encoding != "mbcs":
        try:
            codecs.lookup_error("surrogateescape")
        except LookupError:
            pass
        else:
            errors = "surrogateescape"

    def fsencode(filename):
        """
        Encode filename to the filesystem encoding with 'surrogateescape' error
        handler, return bytes unchanged. On Windows, use 'strict' error handler if
        the file system encoding is 'mbcs' (which is the default encoding).
        """
        if isinstance(filename, bytes):
            return filename
        else:
            return filename.encode(encoding, errors)

    return fsencode

fsencode = _fscodec()
del _fscodec

class ExifTool(object):
    """Run the `exiftool` command-line tool and communicate to it.

    You can pass the file name of the ``exiftool`` executable as an
    argument to the constructor.  The default value ``exiftool`` will
    only work if the executable is in your ``PATH``.

    Most methods of this class are only available after calling
    :py:meth:`start()`, which will actually launch the subprocess.  To
    avoid leaving the subprocess running, make sure to call
    :py:meth:`terminate()` method when finished using the instance.
    This method will also be implicitly called when the instance is
    garbage collected, but there are circumstance when this won't ever
    happen, so you should not rely on the implicit process
    termination.  Subprocesses won't be automatically terminated if
    the parent process exits, so a leaked subprocess will stay around
    until manually killed.

    A convenient way to make sure that the subprocess is terminated is
    to use the :py:class:`ExifTool` instance as a context manager::

        with ExifTool() as et:
            ...

    .. warning:: Note that there is no error handling.  Nonsensical
       options will be silently ignored by exiftool, so there's not
       much that can be done in that regard.  You should avoid passing
       non-existent files to any of the methods, since this will lead
       to undefied behaviour.

    .. py:attribute:: running

       A Boolean value indicating whether this instance is currently
       associated with a running subprocess.
    """

    def __init__(self, executable_=None):
        if executable_ is None:
            self.executable = executable
        else:
            self.executable = executable_
        self.running = False

    def start(self):
        """Start an ``exiftool`` process in batch mode for this instance.

        This method will issue a ``UserWarning`` if the subprocess is
        already running.  The process is started with the ``-G`` and
        ``-n`` as common arguments, which are automatically included
        in every command you run with :py:meth:`execute()`.
        """
        if self.running:
            warnings.warn("ExifTool already running; doing nothing.")
            return
        with open(os.devnull, "w") as devnull:
            self._process = subprocess.Popen(
                [self.executable, "-stay_open", "True",  "-@", "-",
                 "-common_args", "-G", "-n"],
                stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                stderr=devnull)
        self.running = True

    def terminate(self):
        """Terminate the ``exiftool`` process of this instance.

        If the subprocess isn't running, this method will do nothing.
        """
        if not self.running:
            return
        self._process.stdin.write(b"-stay_open\nFalse\n")
        self._process.stdin.flush()
        self._process.communicate()
        del self._process
        self.running = False

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.terminate()

    def __del__(self):
        self.terminate()

    def execute(self, *params):
        """Execute the given batch of parameters with ``exiftool``.

        This method accepts any number of parameters and sends them to
        the attached ``exiftool`` process.  The process must be
        running, otherwise ``ValueError`` is raised.  The final
        ``-execute`` necessary to actually run the batch is appended
        automatically; see the documentation of :py:meth:`start()` for
        the common options.  The ``exiftool`` output is read up to the
        end-of-output sentinel and returned as a raw ``bytes`` object,
        excluding the sentinel.

        The parameters must also be raw ``bytes``, in whatever
        encoding exiftool accepts.  For filenames, this should be the
        system's filesystem encoding.

        .. note:: This is considered a low-level method, and should
           rarely be needed by application developers.
        """
        if not self.running:
            raise ValueError("ExifTool instance not running.")
        self._process.stdin.write(b"\n".join(params + (b"-execute\n",)))
        self._process.stdin.flush()
        output = b""
        fd = self._process.stdout.fileno()
        while not output[-32:].strip().endswith(sentinel):
            output += os.read(fd, block_size)
        return output.strip()[:-len(sentinel)]

    def execute_json(self, *params):
        """Execute the given batch of parameters and parse the JSON output.

        This method is similar to :py:meth:`execute()`.  It
        automatically adds the parameter ``-j`` to request JSON output
        from ``exiftool`` and parses the output.  The return value is
        a list of dictionaries, mapping tag names to the corresponding
        values.  All keys are Unicode strings with the tag names
        including the ExifTool group name in the format <group>:<tag>.
        The values can have multiple types.  All strings occurring as
        values will be Unicode strings.  Each dictionary contains the
        name of the file it corresponds to in the key ``"SourceFile"``.

        The parameters to this function must be either raw strings
        (type ``str`` in Python 2.x, type ``bytes`` in Python 3.x) or
        Unicode strings (type ``unicode`` in Python 2.x, type ``str``
        in Python 3.x).  Unicode strings will be encoded using
        system's filesystem encoding.  This behaviour means you can
        pass in filenames according to the convention of the
        respective Python version – as raw strings in Python 2.x and
        as Unicode strings in Python 3.x.
        """
        params = map(fsencode, params)
        return json.loads(self.execute(b"-j", *params).decode("utf-8"))

    def get_metadata_batch(self, filenames):
        """Return all meta-data for the given files.

        The return value will have the format described in the
        documentation of :py:meth:`execute_json()`.
        """
        return self.execute_json(*filenames)

    def get_metadata(self, filename):
        """Return meta-data for a single file.

        The returned dictionary has the format described in the
        documentation of :py:meth:`execute_json()`.
        """
        return self.execute_json(filename)[0]

    def get_tags_batch(self, tags, filenames):
        """Return only specified tags for the given files.

        The first argument is an iterable of tags.  The tag names may
        include group names, as usual in the format <group>:<tag>.

        The second argument is an iterable of file names.

        The format of the return value is the same as for
        :py:meth:`execute_json()`.
        """
        # Explicitly ruling out strings here because passing in a
        # string would lead to strange and hard-to-find errors
        if isinstance(tags, basestring):
            raise TypeError("The argument 'tags' must be "
                            "an iterable of strings")
        if isinstance(filenames, basestring):
            raise TypeError("The argument 'filenames' must be "
                            "an iterable of strings")
        params = ["-" + t for t in tags]
        params.extend(filenames)
        return self.execute_json(*params)

    def get_tags(self, tags, filename):
        """Return only specified tags for a single file.

        The returned dictionary has the format described in the
        documentation of :py:meth:`execute_json()`.
        """
        return self.get_tags_batch(tags, [filename])[0]

    def get_tag_batch(self, tag, filenames):
        """Extract a single tag from the given files.

        The first argument is a single tag name, as usual in the
        format <group>:<tag>.

        The second argument is an iterable of file names.

        The return value is a list of tag values or ``None`` for
        non-existent tags, in the same order as ``filenames``.
        """
        data = self.get_tags_batch([tag], filenames)
        result = []
        for d in data:
            d.pop("SourceFile")
            result.append(next(iter(d.values()), None))
        return result

    def get_tag(self, tag, filename):
        """Extract a single tag from a single file.

        The return value is the value of the specified tag, or
        ``None`` if this tag was not found in the file.
        """
        return self.get_tag_batch(tag, [filename])[0]


text:
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

public class JsonServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public JsonServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out= response.getWriter();
        JSONObject json = new JSONObject();
        json.put("name", "Sameera Jayasekara");
        json.put("email", "codesstore@blogspot.com");
        out.print(json);

    }

}


text:
define(['require', 'lodash', 'log', 'event_channel', './abstract-statement-source-gen-visitor'], function (require, _, log, EventChannel, AbstractStatementSourceGenVisitor) {

    var TryStatementVisitor = function (parent) {
        AbstractStatementSourceGenVisitor.call(this, parent);
    };

    TryStatementVisitor.prototype = Object.create(AbstractStatementSourceGenVisitor.prototype);
    TryStatementVisitor.prototype.constructor = TryStatementVisitor;

    TryStatementVisitor.prototype.canVisitTryStatement = function (tryStatement) {
        return true;
    };

    TryStatementVisitor.prototype.beginVisitTryStatement = function (tryStatement) {
        /**
         * set the configuration start for the try statement
         * If we need to add additional parameters which are dynamically added to the configuration start
         * that particular source generation has to be constructed here
         */
        this.appendSource('try {');
        log.debug('Begin Visit Try Statement');
    };

    TryStatementVisitor.prototype.visitTryStatement = function (tryStatement) {
        log.debug('Visit Try Statement');
    };

    TryStatementVisitor.prototype.endVisitTryStatement = function (tryStatement) {
        this.appendSource("}\n");
        this.getParent().appendSource(this.getGeneratedSource());
        log.debug('End Visit Try Statement');
    };

    TryStatementVisitor.prototype.visitStatement = function(statement){
        var StatementVisitorFactory = require('./statement-visitor-factory');
        var statementVisitorFactory = new StatementVisitorFactory();
        var statementVisitor = statementVisitorFactory.getStatementVisitor(statement, this);
        statement.accept(statementVisitor);
    };

    return TryStatementVisitor;
});


text:
id: 587d8249367417b2b2512c3f
title: Set a Content Security Policy with helmet.contentSecurityPolicy()
challengeType: 2
---

## Description

As a reminder, this project is being built upon the following starter project on Glitch, or cloned from GitHub.
This challenge highlights one promising new defense that can significantly reduce the risk and impact of many type of attacks in modern browsers. By setting and configuring a Content Security Policy you can prevent the injection of anything unintended into your page. This will protect your app from XSS vulnerabilities, undesired tracking, malicious frames, and much more. CSP works by defining a whitelist of content sources which are trusted. You can configure them for each kind of resource a web page may need (scripts, stylesheets, fonts, frames, media, and so on…). There are multiple directives available, so a website owner can have a granular control. See HTML 5 Rocks, KeyCDN for more details. Unfortunately CSP is unsupported by older browser.
By default, directives are wide open, so it's important to set the defaultSrc directive as a fallback. Helmet supports both defaultSrc and default-src naming styles. The fallback applies for most of the unspecified directives. In this exercise, use helmet.contentSecurityPolicy(), and configure it setting the defaultSrc directive to ["self"] (the list of allowed sources must be in an array), in order to trust only your website address by default. Set also the scriptSrc directive so that you will allow scripts to be downloaded from your website, and from the domain 'trusted-cdn.com'.
Hint: in the "'self'" keyword, the single quotes are part of the keyword itself, so it needs to be enclosed in double quotes to be working.

## Instructions

## Tests

```yml
tests:
  - text: helmet.csp() middleware should be mounted correctly
    testString: getUserInput => $.get(getUserInput('url') + '/_api/app-info').then(data => { assert.include(data.appStack, 'csp'); }, xhr => { throw new Error(xhr.responseText); })
  - text: Your csp config is not correct. defaultSrc should be ["'self'"] and scriptSrc should be ["'self'", 'trusted-cdn.com']
    testString: getUserInput => $.get(getUserInput('url') + '/_api/app-info').then(data => { var cspHeader = Object.keys(data.headers).filter(function(k){ return k === 'content-security-policy' || k === 'x-webkit-csp' || k === 'x-content-security-policy' })[0]; assert.equal(data.headers[cspHeader], "default-src 'self'; script-src 'self' trusted-cdn.com"); }, xhr => { throw new Error(xhr.responseText); })

```

## Challenge Seed

## Solution

```js
// solution required
```


text:
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
  <DefaultLanguage xmlns="" code="en-US" />
  <App xmlns="" ProductID="{314fac6d-bf26-4108-b573-059f22c9b32f}" Title="GoMusic" RuntimeType="Silverlight" Version="2.0.1.0" Genre="apps.normal" Author="GoMusic author" Description="
" Publisher="GoMusic" PublisherID="{a7498231-1f4f-4211-873f-f201f1d1a66a}">
    <IconPath IsRelative="true" IsResource="false">appicon5_300.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_MEDIALIB_AUDIO" />
      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_MEDIALIB_PHOTO" />
      <Capability Name="ID_CAP_REMOVABLE_STORAGE" />
    </Capabilities>
    <Tasks>
      <DefaultTask Name="_default" />
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="GoMusicToken" TaskName="_default">
        <TemplateFlip>
          <SmallImageURI IsRelative="true" IsResource="false">Assets\appicon5_300.png</SmallImageURI>
          <Count>0</Count>
          <BackgroundImageURI IsRelative="true" IsResource="false">Assets\appicon5_300.png</BackgroundImageURI>
          <Title>
          </Title>
          <BackContent>
          </BackContent>
          <BackBackgroundImageURI IsRelative="true" IsResource="false">
          </BackBackgroundImageURI>
          <BackTitle>
          </BackTitle>
          <LargeBackgroundImageURI IsRelative="true" IsResource="false">Assets\wideTile2.png</LargeBackgroundImageURI>
          <LargeBackContent />
          <LargeBackBackgroundImageURI IsRelative="true" IsResource="false">
          </LargeBackBackgroundImageURI>
          <DeviceLockImageURI IsRelative="true" IsResource="false">
          </DeviceLockImageURI>
          <HasLarge>True</HasLarge>
        </TemplateFlip>
      </PrimaryToken>
    </Tokens>
    <ScreenResolutions>
      <ScreenResolution Name="ID_RESOLUTION_WVGA" />
      <ScreenResolution Name="ID_RESOLUTION_WXGA" />
      <ScreenResolution Name="ID_RESOLUTION_HD720P" />
    </ScreenResolutions>
  </App>
</Deployment>


text:
using namespace std;
#define TREE_DATA_TYPE show

class tree
{
private:
	typedef struct TreeEntry{

		TreeEntry *left;
		TREE_DATA_TYPE *data;
		TreeEntry *right;

	} TreeEntry;

	TreeEntry *root;
	void displayInOrder(TreeEntry *entry);
	void displayAllTitles(TreeEntry *entry);
	void displayActorsByShowName(TreeEntry * entry, string showName);
	void displayShowsByActorName(TreeEntry * entry, string showName);
	void displayShowsByDateRange(TreeEntry * entry, int yearRangeStart, int yearRangeEnd);

public:

	tree();
	void displayAll();
	void displayAllTitles();
	void tree::addToTree(TREE_DATA_TYPE *newData);

	void displayActorsByShowName(string showName);
	void displayShowsByActorName(string actorName);

	void displayShowsByDateRange(int yearRangeStart, int yearRangeEnd);

	//ADD OTHER FUNCTIONS HERE;
};


text:
#ifndef __DRIVER_VALUE_INT_HPP__
#define __DRIVER_VALUE_INT_HPP__
#include "value_interface.hpp"

#include <sstream>

namespace driver {
  namespace value {

    /**
     * Integer wrapped value
     */
    class Integer : public COMPARABLE_VALUE_INTERFACE_OBJECT_ONLY(cass_int32_t, Integer) {
    public:
      Integer(cass_int32_t integer)
        : integer_(integer) {
        set_integer_string();
      }

      Integer(const CassValue* value) {
        initialize(value);
        set_integer_string();
      }

      Integer(const std::string& value) {
        //Convert the value
        if (!value.empty()) {
          std::stringstream valueStream(value);
          if ((valueStream >> integer_).fail()) {
            integer_ = 0;
            std::cerr << "Invalid Integer: Using default [" << integer_ << "]";
          }
        }
        set_integer_string();
      }

      Integer(const CassRow* row, size_t column_index) {
        initialize(row, column_index);
        set_integer_string();
      }

      const char* c_str() const {
        return integer_string_.c_str();
      }

      std::string cql_type() const {
        return std::string("int");
      }

      std::string cql_value() const {
        return integer_string_;
      }

      /**
       * Comparison operation for driver integers
       *
       * @param rhs Right hand side to compare
       * @return -1 if LHS < RHS, 1 if LHS > RHS, and 0 if equal
       */
      int compare(const cass_int32_t& rhs) const {
        if (integer_ < rhs) return -1;
        if (integer_ > rhs) return 1;

        return 0;
      }

      /**
       * Comparison operation for driver integers
       *
       * @param rhs Right hand side to compare
       * @return -1 if LHS < RHS, 1 if LHS > RHS, and 0 if equal
       */
      int compare(const Integer& rhs) const {
        return compare(rhs.integer_);
      }

      void statement_bind(shared::native::StatementPtr statement, size_t index) {
        ASSERT_EQ(CASS_OK, cass_statement_bind_int32(statement.get(), index, integer_));
      }

      std::string str() const {
        return integer_string_;
      }

      cass_int32_t value() const {
        return integer_;
      }

      CassValueType value_type() const {
        return CASS_VALUE_TYPE_INT;
      }

    protected:
      /**
       * Native driver value
       */
      cass_int32_t integer_;
      /**
       * Native driver value as string
       */
      std::string integer_string_;

      void initialize(const CassValue* value) {
        // Ensure the value types
        ASSERT_TRUE(value != NULL) << "Invalid CassValue: Value should not be null";
        CassValueType value_type = cass_value_type(value);
        ASSERT_EQ(CASS_VALUE_TYPE_INT, value_type)
          << "Invalid Value Type: Value is not a integer [" << value_type << "]";
        const CassDataType* data_type = cass_value_data_type(value);
        value_type = cass_data_type_type(data_type);
        ASSERT_EQ(CASS_VALUE_TYPE_INT, value_type)
          << "Invalid Data Type: Value->DataType is not a integer";

        // Get the 32-bit integer
        ASSERT_EQ(CASS_OK, cass_value_get_int32(value, &integer_))
          << "Unable to Get 32-bit Integer: Invalid error code returned";
      }

      void initialize(const CassRow* row, size_t column_index) {
        ASSERT_TRUE(row != NULL) << "Invalid Row: Row should not be null";
        initialize(cass_row_get_column(row, column_index));
      }

      /**
       * Set the string value of the integer
       */
      void set_integer_string() {
        std::stringstream integer_string;
        integer_string << integer_;
        integer_string_ = integer_string.str();
      }
    };
  }
}

#endif // __DRIVER_VALUE_INT_HPP__


text:
#ifndef OPENCAD_H
#define OPENCAD_H

#define OCAD_VERSION    "0.3.4"
#define OCAD_VERSION_MAJOR 0
#define OCAD_VERSION_MINOR 3
#define OCAD_VERSION_REV   4

#ifndef OCAD_COMPUTE_VERSION
#define OCAD_COMPUTE_VERSION(maj,min,rev) ((maj)*10000+(min)*100+rev) // maj - any, min < 99, rev < 99
#endif

#define OCAD_VERSION_NUM OCAD_COMPUTE_VERSION(OCAD_VERSION_MAJOR,OCAD_VERSION_MINOR,OCAD_VERSION_REV)

/*  check if the current version is at least major.minor.revision */
#define CHECK_VERSION(major,minor,rev) \
    (OCAD_VERSION_MAJOR > (major) || \
    (OCAD_VERSION_MAJOR == (major) && OCAD_VERSION_MINOR > (minor)) || \
    (OCAD_VERSION_MAJOR == (major) && OCAD_VERSION_MINOR == (minor) && OCAD_VERSION_REV >= (release)))

#define DWG_VERSION_STR_SIZE  6

#ifndef OCAD_EXTERN
#ifdef OCAD_STATIC
  #define OCAD_EXTERN extern
#else
#   if defined (_MSC_VER)
#    ifdef OCAD_EXPORTS
#      define OCAD_EXTERN __declspec(dllexport) // extern
#      else
#      define OCAD_EXTERN __declspec(dllimport) // extern
#      endif
#    else
#     if defined(__GNUC__) && __GNUC__ >= 4
#       define OCAD_EXTERN __attribute__((visibility("default")))
#     else
#       define OCAD_EXTERN                extern
#     endif
#   endif
#endif
#endif

#if defined(__GNUC__) && __GNUC__ >= 4
# define OCAD_PRINT_FUNC_FORMAT( format_idx, arg_idx ) __attribute__((__format__ (__printf__, format_idx, arg_idx)))
#else
#  define OCAD_PRINT_FUNC_FORMAT( format_idx, arg_idx )
#endif

void DebugMsg(const char *, ...) OCAD_PRINT_FUNC_FORMAT (1,2);

#endif // OPENCAD_H


text:
package org.openxava.test.model;

import java.math.*;
import java.util.*;

import javax.persistence.*;

import org.openxava.annotations.*;
import org.openxava.jpa.*;

/**
 * Example of reference used as key that
 * as well have a reference used as key. <p>
 *
 * @author Javier Paniza
 */

@Entity
@IdClass(TransportChargeKey.class)
@View(name="WithDescriptionsList", members="delivery; amount")
@Tabs({
	@Tab(properties="delivery.invoice.year, delivery.invoice.number, delivery.number, amount"),
	@Tab(name="WithDistance", properties="delivery.invoice.year, delivery.invoice.number, delivery.number, delivery.distance, amount")
})
public class TransportCharge {

	@Id @ManyToOne(fetch=FetchType.LAZY)
	/* This the default mapping (at least with Hibernate)
	@JoinColumns({
		@JoinColumn(name="DELIVERY_INVOICE_YEAR", referencedColumnName="INVOICE_YEAR"),
		@JoinColumn(name="DELIVERY_INVOICE_NUMBER", referencedColumnName="INVOICE_NUMBER"),
		@JoinColumn(name="DELIVERY_TYPE", referencedColumnName="TYPE"),
		@JoinColumn(name="DELIVERY_NUMBER", referencedColumnName="NUMBER")
	})
	*/
	@ReferenceView("MoreSections")
	@DescriptionsList(forViews="WithDescriptionsList")
	private Delivery delivery;

	@Stereotype("MONEY") @Required
	private BigDecimal amount;

	public static Collection<TransportCharge> findAll() {
		Query query = XPersistence.getManager().createQuery("from TransportCharge as o");
 		return query.getResultList();
	}

	public Delivery getDelivery() {
		return delivery;
	}

	public void setDelivery(Delivery delivery) {
		this.delivery = delivery;
	}

	public BigDecimal getAmount() {
		return amount;
	}

	public void setAmount(BigDecimal amount) {
		this.amount = amount;
	}

}


text:
import path from 'path';
import chalk from 'chalk';
import fs from 'fs';

function CheckBuildsExist() {
  const mainPath = path.join(__dirname, '..', '..', 'app', 'main.prod.js');
  const rendererPath = path.join(__dirname, '..', '..', 'app', 'dist', 'renderer.prod.js');

  if (!fs.existsSync(mainPath)) {
    throw new Error(chalk.whiteBright.bgRed.bold('The main process is not built yet. Build it by running "npm run build-main"'));
  }

  if (!fs.existsSync(rendererPath)) {
    throw new Error(chalk.whiteBright.bgRed.bold('The renderer process is not built yet. Build it by running "npm run build-renderer"'));
  }
}

CheckBuildsExist();


text:
A single command to build your site into a `dist` folder

```console
npm run build
```

⚠ **Note that this folder need to be served from a real web server.** You
cannot just open an `index.html` and expect the client code to work correctly.
If you want to run the built project locally, you can run it with these commands

```console
npm install -g serve
serve dist
```

This will install a small web server and launch your project from `dist`.

## Debugging static build

During the static build, you might get some different kinds of errors

### `Invariant Violation`

```
Invariant Violation: Minified React error #61; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=61 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
```

By default, the static build has `process.env.NODE_ENV` set to `production`. You
can start the static build like this

```console
NODE_ENV=development npm run build
```

Then you can return to the console and you should have a more explicit error.

### Debugging Phenomic core

Phenomic uses [debug](https://github.com/visionmedia/debug) under the hood, so
it's pretty easy to get a very verbose output in your terminal. You can start or
build your project by prefixing your command with the `DEBUG` environment
variable set to `phenomic:*`

```console
NODE_ENV=development DEBUG=phenomic:* npm run build
```

Depending on what you want to view/filter, you can use a more spefic value for
`DEBUG` (eg: `DEBUG=phenomic:core:*`).

## Deploying static build

You can deploy the `dist` folder to any kind of static hosting. Nothing special
is supposed to be done!

---

Congratulations! You successfully followed our tutorial. You can find the source
in
[phenomic/examples/react-app-getting-started](https://github.com/phenomic/phenomic/tree/master/examples/react-app-getting-started)


text:
package org.apache.camel.component.servlet.rest;

import java.io.ByteArrayInputStream;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.component.servlet.ServletCamelRouterTestSupport;
import org.apache.camel.model.rest.RestBindingMode;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class RestServletPostXmlJaxbPojoTest extends ServletCamelRouterTestSupport {

    @Test
    public void testPostJaxbPojo() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:input");
        mock.expectedMessageCount(1);
        mock.message(0).body().isInstanceOf(UserJaxbPojo.class);

        String body = "{\"id\": 123, \"name\": \"Donald Duck\"}";
        WebRequest req = new PostMethodWebRequest(
                contextUrl + "/services/users/new",
                new ByteArrayInputStream(body.getBytes()), "application/json");
        WebResponse response = query(req, false);

        assertEquals(200, response.getResponseCode());

        assertMockEndpointsSatisfied();

        UserJaxbPojo user = mock.getReceivedExchanges().get(0).getIn().getBody(UserJaxbPojo.class);
        assertNotNull(user);
        assertEquals(123, user.getId());
        assertEquals("Donald Duck", user.getName());
    }

    @Test
    public void testPostJaxbPojoNoContentType() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:input");
        mock.expectedMessageCount(1);
        mock.message(0).body().isInstanceOf(UserJaxbPojo.class);

        String body = "<user name=\"Donald Duck\" id=\"456\"></user>";
        WebRequest req = new PostMethodWebRequest(
                contextUrl + "/services/users/new",
                new ByteArrayInputStream(body.getBytes()), "foo");
        WebResponse response = query(req, false);

        assertEquals(200, response.getResponseCode());

        assertMockEndpointsSatisfied();

        UserJaxbPojo user = mock.getReceivedExchanges().get(0).getIn().getBody(UserJaxbPojo.class);
        assertNotNull(user);
        assertEquals(456, user.getId());
        assertEquals("Donald Duck", user.getName());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                restConfiguration().component("servlet").bindingMode(RestBindingMode.auto);

                // use the rest DSL to define the rest services
                rest("/users/")
                        .post("new").type(UserJaxbPojo.class)
                        .to("mock:input");
            }
        };
    }

}


text:
package org.gradle.api.artifacts.dsl;

import org.gradle.api.Incubating;
import org.gradle.api.NonExtensible;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.ExternalModuleDependency;
import org.gradle.api.artifacts.FileCollectionDependency;
import org.gradle.api.artifacts.ProjectDependency;
import org.gradle.api.file.FileCollection;
import org.gradle.internal.HasInternalProtocol;

import javax.annotation.Nullable;

/**
 * Factory class for creating {@link Dependency} instances, with strong typing.
 *
 *

 * An instance of the factory can be injected into a task, plugin or other object by annotating a public constructor or property getter method with {@code javax.inject.Inject}.
 * It is also available via {@link Project#getDependencyFactory()}.
 *

 *
 *

 * Note: This interface is not intended for implementation by build script or plugin authors.
 *

 *
 * @since 7.6
 */
@HasInternalProtocol
@NonExtensible
@Incubating
public interface DependencyFactory {
    /**
     * Create an {@link ExternalModuleDependency} from the "group:name:version:classifier@extension" notation.
     *
     *

     * Classifier and extension may each separately be omitted. Version may be omitted if there is no classifier.
     *

     *
     * @param dependencyNotation the dependency notation
     * @return the new dependency
     */
    ExternalModuleDependency create(CharSequence dependencyNotation);

    /**
     * Create an {@link ExternalModuleDependency} from a series of strings.
     *
     * @param group the group (optional)
     * @param name the name
     * @param version the version (optional)
     * @return the new dependency
     */
    ExternalModuleDependency create(@Nullable String group, String name, @Nullable String version);

    /**
     * Create an {@link ExternalModuleDependency} from a series of strings.
     *
     * @param group the group (optional)
     * @param name the name
     * @param version the version (optional)
     * @param classifier the classifier (optional)
     * @param extension the extension (optional)
     * @return the new dependency
     */
    ExternalModuleDependency create(@Nullable String group, String name, @Nullable String version, @Nullable String classifier, @Nullable String extension);

    /**
     * Create a {@link FileCollectionDependency} from a {@link FileCollection}.
     *
     * @param fileCollection the file collection
     * @return the new dependency
     */
    FileCollectionDependency create(FileCollection fileCollection);

    /**
     * Create a {@link ProjectDependency} from a {@link Project}.
     *
     * @param project the project
     * @return the new dependency
     */
    ProjectDependency create(Project project);

    /**
     * Creates a dependency on the API of the current version of Gradle.
     *
     * @return The dependency.
     * @since 7.6
     */
    Dependency gradleApi();

    /**
     * Creates a dependency on the Gradle test-kit API.
     *
     * @return The dependency.
     * @since 7.6
     */
    Dependency gradleTestKit();

    /**
     * Creates a dependency on the version of Groovy that is distributed with the current version of Gradle.
     *
     * @return The dependency.
     * @since 7.6
     */
    Dependency localGroovy();
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>01_HolaMundo</groupId>
  <artifactId>01_HolaMundo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <warSourceDirectory>target</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>

   	<properties>
		<spring.version>4.0.1.RELEASE</spring.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

	</dependencies>
</project>


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

namespace Scour.Code {
    class Admin {
    }
}


text:
'use strict';

var reporters = require('./jasmine-reporters');

module.exports = function(gulp, plugins, options) {
  // Convert the text to an actual reporter
  var reporter = options.jasmine.reporter;

  switch (reporter) {
    case 'terminal':
      options.jasmine.reporter = reporters[reporter];
      break;
    // Add other reporters as necessary, pass in reporter options from
    // options.jasmine.reporterOptions
    default:
      options.jasmine.reporter = null;
  }
  return function () {
    return gulp.src(options.src)
      .pipe(plugins.jasmine(options.jasmine));
      //.pipe(plugins.istanbul.writeReports())
      //.pipe(plugins.istanbul.enforceThresholds(options.coverage.enforce));
  };
};


text:
class AddDeletedAtToUser < ActiveRecord::Migration
  def change
    add_column :users, :deleted_at, :timestamp
  end
end


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import six
from .legend import get_labels

# Matplolib is not consistent. Sometimes it does not
# accept abbreviations
# LINETYPES = [
#     '-',  #solid
#     '--', #dashed
#     '-.', #dash-dot
#     ':',  #dotted
#     '.',  #point
#     '|',  #vline
#     '_',  #hline
# ]

LINETYPES = [
    'solid',
    'dashed',
    'dashdot',
    'dotted'
]

def line_gen():
    while True:
        for line in LINETYPES:
            yield line

def assign_linetypes(data, aes):
    """
    Assigns line types to the given data based on the aes and adds the right
    legend.

    Parameters
    ----------
    data : DataFrame
        dataframe which should have shapes assigned to
    aes : aesthetic
        mapping, including a mapping from line type to variable

    Returns
    -------
    data : DataFrame
        the changed dataframe
    legend_entry : dict
        An entry into the legend dictionary.
        Documented in `components.legend`
    """

    legend_entry = dict()
    if 'linetype' in aes:
        linetype_col = aes['linetype']
        linetype = line_gen()
        labels, scale_type, indices = get_labels(data, linetype_col, "discrete")
        linetype_mapping = dict((value, six.next(linetype)) for value in labels)
        data[':::linetype_mapping:::'] = data[linetype_col].apply(
            lambda x: linetype_mapping[x])

        legend_entry = {
            'column_name': linetype_col,
            'dict': dict((v, k) for k, v in linetype_mapping.items()),
            'scale_type': "discrete"}
    return data, legend_entry


text:
PipelineService
---------------------------------

.. automodule:: google.cloud.aiplatform_v1beta1.services.pipeline_service
    :members:
    :inherited-members:

.. automodule:: google.cloud.aiplatform_v1beta1.services.pipeline_service.pagers
    :members:
    :inherited-members:


text:
Encodes GIF using custom palette generated for a whole video stream

### Usage
```
turbo run turbo/hqgif <frame rate> <input file pattern> <output file> [<scale>]
turbo run turbo/hqgif 2.5 screenshot_%d.bmp c:\output\screencast.gif
turbo run turbo/hqgif 1.0 screenshot_%d.bmp c:\output\screencast.gif 340x256
```

### Build
```
turbo build turbo.me --mount="%~dp0=c:\temp" --no-base --overwrite
```


text:
[![MIT License][license-img]][license-url]

> Provides an easy and quick way to describe your stories with an YAML file
> Can generate [Mocha](https://mochajs.org) files from stories.yml

## Install

```bash
npm install -g tell-cli
```

> **must be installed globally**

## Usages

> An yaml file named **stories.yml** as describe [below](#stories.yml) must be placed in your *spec | tests |...* folder

```bash
# output stories in console, doesn't generate spec files
tell spec
# prompts for overwite specs files - default to false
tell spec --generate
tell spec -g
# doesn't prompts
tell spec --generate --yes
tell spec -g -Y
```

### spec/stories.yml

```yml
src/filename.js:
  render:
    - throw if no argument
    - should return a string
    - should return helloworld
  a_function_name:
    other_cases
      - returns false if no arguments
      - returns arguments is empty
      - returns false is not a plainobject
      - returns options property 'name' is not defined
      - expect to returns array of arguments
    other_other_cases:
      - returns false if no arguments
      - returns arguments is empty
      - returns false is not a plainobject
      - returns options property <name> is not defined
      - expect to returns array of arguments
src/an_other_filename.js:
  - throw if no argument
  - should return a string
  - should return helloworld
```

## History

- v0.1.4 Fix multiple files

## Issues

- Not tested under UNIX
- No unit tests...

## Dependencies

- [**chalk** ^1.1.0](https://www.npmjs.com/package/chalk)
- [**commander** ^2.8.1](https://www.npmjs.com/package/commander)
- [**esformatter** ^0.7.3](https://www.npmjs.com/package/esformatter)
- [**fs-extra** ^0.23.1](https://www.npmjs.com/package/fs-extra)
- [**inquirer** ^0.9.0](https://www.npmjs.com/package/inquirer)
- [**is-valid-path** ^0.1.1](https://www.npmjs.com/package/is-valid-path)
- [**js-yaml** ^3.3.1](https://www.npmjs.com/package/js-yaml)
- [**lodash.isarray** ^3.0.4](https://www.npmjs.com/package/lodash.isarray)
- [**lodash.template** ^3.6.2](https://www.npmjs.com/package/lodash.template)

[license-img]: http://img.shields.io/badge/license-MIT-blue.svg?style=flat-square
[license-url]: LICENSE-MIT

[coverall-url]: https://coveralls.io/r/sixertoy/tell-cli
[coverall-img]: https://img.shields.io/coveralls/sixertoy/tell-cli.svg?style=flat-square

[travis-url]: https://travis-ci.org/sixertoy/tell-cli
[travis-img]: http://img.shields.io/travis/sixertoy/tell-cli.svg?style=flat-square


text:
namespace my_namespace {

class SomeClass;

struct MyStruct {
  SomeClass* ptr_field;
};

class MyClass {
  SomeClass* ptr_field;
};

union MyUnion1 {
  SomeClass* some_class_ptr;
  const char* char_ptr;
};

union MyUnion2 {
  SomeClass* some_class_ptr;
  uintptr_t uintptr;
};

union MyUnion3 {
  SomeClass* some_class_ptr;
  SomeClass* some_class_ptr2;
};

struct MyNestedStruct {
  SomeClass* ptr_field;
};

union MyUnion4 {
  MyNestedStruct nested_struct;
  uintptr_t uintptr;
};

}  // namespace my_namespace


text:
<?php if (mb_strlen($this->parentPath)): ?>

		<a href="<?php echo build_url('file', 'index', array('folder' => base64_encode($this->parentPath)))?>">Parent Directory

<?php endif; ?>
<?php foreach ($this->files as $file):?>

	<?php if (is_string($file)): ?>
		<a href="<?php echo build_url('file', 'index', array('folder' => base64_encode($this->base.$file)))?>"><?php $this->o($file)?>

	<?php else: ?>
		<a class="action-icon" title="Edit file" href="<?php echo build_url('file', 'edit', array('id'=>$file->id, 'returnurl'=>base64_encode('file/index/folder/'.base64_encode($file->path)), 'parent'=>base64_encode($file->path)))?>">
			<img src="<?php echo resource('images/pencil.png')?>" />

		<?php if ($this->u()->hasRole(User::ROLE_USER)): ?>
		<a class="action-icon" title="Delete file" href="<?php echo build_url('file', 'delete', array('id'=>$file->id, 'returnurl'=>base64_encode('file/index/folder/'.base64_encode($file->path))))?>">
			<img src="<?php echo resource('images/delete.png')?>" />

		<?php endif; ?>

		<a href="<?php echo build_url('file', 'view', array('id' => $file->id)).htmlentities($file->filename)?>"><?php $this->o($file->getTitle())?>

		<?php if (!empty($file->description)): ?>

<?php $this->o($file->description) ?>

		<?php endif; ?>
	<?php endif; ?>

<?php endforeach; ?>

<form method="post" action="<?php echo build_url('file', 'createfolder')?>">

	<input type="hidden" value="<?php echo base64_encode($this->base)?>" name="parent" />
	<input type="text" value="" name="child" />
	<input type="submit" value="Create Folder" class="abutton" />

</form>

<form method="post" action="<?php echo build_url('file', 'upload');?>" enctype="multipart/form-data">
	<input type="hidden" name="returnurl"
	value="<?php echo base64_encode('file/index/folder/'.base64_encode($this->base))?>" />
	<input type="hidden" value="<?php echo base64_encode($this->base)?>" name="parent" />

File
	<input class="input" type="file" name="file" id="file" />

Filename:
	<input class="input" type="text" name="filename" id="filename" />

Title:
	<input class="input" type="text" name="title" id="title" />

Description:
	<textarea class="input" name="description" id="description"></textarea>

<input type="submit" class="abutton" value="Upload"
		accesskey="a" />

</form>


text:
#include <assert.h>
#include <QChar>
#include <QFont>
#include <QFontMetrics>
#include <QString>
#include <QPainter>
#include <QStringList>
#include <QFontDatabase>
#include <gnu_java_awt_peer_qt_QtFontMetrics.h>
#include "qtfont.h"
#include "qtstrings.h"
#include "qtgraphics.h"

QFontMetrics *getFontMetrics( JNIEnv *env, jobject obj )
{
  jclass cls = env->GetObjectClass( obj );
  jfieldID field = env->GetFieldID( cls, "nativeObject", "J" );
  return (QFontMetrics *)env->GetLongField( obj, field );
}

static void setNativePtr( JNIEnv *env, jobject obj, void *value )
{
  jlong longValue = (jlong) value;
  jclass cls = env->GetObjectClass( obj );
  jfieldID field = env->GetFieldID( cls, "nativeObject", "J" );
  env->SetLongField( obj, field, longValue );
}

static jobject makeRectangle(JNIEnv *env, QRect *rect)
{
  if( rect == NULL )
    return NULL;
  if( rect->isNull() || !rect->isValid() )
    return NULL;
  jclass cls = env->FindClass("java/awt/Rectangle");
  jmethodID mid = env->GetMethodID(cls, "<init>", "(IIII)V");
  jvalue values[4];

  int x,y,w,h;
  rect->getRect(&x, &y, &w, &h);
  values[0].i = (jint) x;
  values[1].i = (jint) y;
  values[2].i = (jint) w;
  values[3].i = (jint) h;

  return env->NewObjectA(cls, mid, values);
}

/*
 * Create font metrics from a font.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_init
(JNIEnv *env, jobject obj, jobject fontPeer)
{
  QFont *f = getFont(env, fontPeer);
  assert( f );
  QFontMetrics *fm = new QFontMetrics( *f );
  assert( fm );
  setNativePtr( env, obj, fm );
}

/*
 * Create font metrics from a font.
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_initGraphics
(JNIEnv *env, jobject obj, jobject fontPeer, jobject graphics)
{
  QFont *f = getFont(env, fontPeer);
  assert( f );
  QPainter *painter = getPainter( env, graphics );
  assert( painter );
  QFontMetrics *fm = new QFontMetrics( *f , painter->device());
  assert( fm );
  setNativePtr( env, obj, fm );
}

/*
 * Dispose
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_dispose
(JNIEnv *env, jobject obj)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  if ( fm )
    delete fm;
  setNativePtr( env, obj, NULL );
}

/*
 * Returns JNI_TRUE if a character is displayable.
 */
JNIEXPORT jboolean JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_canDisplay
(JNIEnv *env, jobject obj, jint c)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  assert( fm );
  bool result = fm->inFont( QChar( (unsigned int) c ) );
  return (result ? JNI_TRUE : JNI_FALSE);
}

/*
 * Returns the ascent.
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_getAscent
(JNIEnv *env, jobject obj)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  assert( fm );
  return fm->ascent();
}

/*
 * Returns the descent
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_getDescent
(JNIEnv *env, jobject obj)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  assert( fm );
  return fm->descent();
}

/*
 * Returns the height.
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_getHeight
(JNIEnv *env, jobject obj)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  assert( fm );
  return fm->height();
}

/*
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_getLeading
(JNIEnv *env, jobject obj)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  assert( fm );
  return fm->leading();
}

/*
 * getStringBounds
 */
JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_getStringBounds
(JNIEnv *env, jobject obj, jstring str)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  assert( fm );
  QString *qStr = getQString(env, str);
  QRect r = fm->boundingRect( *qStr );
  delete qStr;

  return makeRectangle( env, &r );
}

/*
 * Returns the width of the widest character.
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_getMaxAdvance
(JNIEnv *env, jobject obj)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  assert( fm );
  return fm->maxWidth();
}

/*
 * Returns the width of a given character.
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_charWidth
(JNIEnv *env, jobject obj, jchar c)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  assert( fm );
  return fm->width( QChar( (unsigned short)c ) );
}

/*
 * Returns the width of a string.
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_qt_QtFontMetrics_stringWidth
(JNIEnv *env, jobject obj, jstring str)
{
  QFontMetrics *fm = getFontMetrics( env, obj );
  assert( fm );
  QString *qStr = getQString(env, str);
  int width = fm->width( *qStr );
  delete qStr;
  return width;
}


text:
namespace java {
  namespace lang {
    class Class;
  }
}
template<class T> class JArray;

namespace java {
  namespace lang {

    class Readable : public ::java::lang::Object {
    public:

      static ::java::lang::Class *class$;
      static jmethodID *mids$;
      static bool live$;
      static jclass initializeClass(bool);

      explicit Readable(jobject obj) : ::java::lang::Object(obj) {
        if (obj != NULL)
          env->getClass(initializeClass);
      }
      Readable(const Readable& obj) : ::java::lang::Object(obj) {}
    };
  }
}

#include <Python.h>

namespace java {
  namespace lang {
    extern PyTypeObject PY_TYPE(Readable);

    class t_Readable {
    public:
      PyObject_HEAD
      Readable object;
      static PyObject *wrap_Object(const Readable&);
      static PyObject *wrap_jobject(const jobject&);
      static void install(PyObject *module);
      static void initialize(PyObject *module);
    };
  }
}

#endif


text:
[![Pod Version](http://img.shields.io/cocoapods/v/VMViewControllerDataSource.svg?style=flat)]()
[![Pod Platform](http://img.shields.io/cocoapods/p/VMViewControllerDataSource.svg?style=flat)]()
[![Pod License](http://img.shields.io/cocoapods/l/VMViewControllerDataSource.svg?style=flat)](http://opensource.org/licenses/MIT)

## OVERVIEW

The VMViewControllerDataSource class implements a specialized datasource object that renders reusable UIViewController objects instead of cells objects.

In order to achieve that, the view controller data source implements either `tableView:cellForRowAtIndexPath:` or `collectionView:cellForItemAtIndexPath:`.

Every row or item created with a view controller data source is either a `VMViewControllerTableViewDataSourceCell` or a `VMViewControllerCollectionViewDataSourceCell` which has the view controller's view attached to its subviews hierarchy.

The view controller data source acts as datasource for your `UITableView` or `UICollectionView`.

Through message forwarding, your view controller can implement the `VMViewControllerTableViewDataSource` protocol and can respond to all the methods that are needed to build the table or the collection views, that can be then further customized with their standard delegate methods.

## Installation

VMViewControllerDataSource is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

    pod "VMViewControllerDataSource"

## USAGE

Just import the main header whenever you need on your project source files.

```
#import <VMViewControllerDataSource/VMViewControllerDataSource.h>
```

To run the example project; clone the repo, and run `pod install` from the Example directory first.

## LICENSE

VMViewControllerDataSource is available under the MIT License (MIT).

Copyright (c) 2015 Valerio Mazzeo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## AUTHOR

[Valerio Mazzeo](https://twitter.com/valeriomazzeo)


text:
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>{% if page.title %}{{ page.title | escape }}{% else %}{{ site.title | escape }}{% endif %}</title>
  <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.description }}{% endif %}">

  <link rel="stylesheet" href="{{ "/css/gridism.css" | prepend: site.baseurl }}">
  <link rel="stylesheet" href="{{ "/css/solace-common.css" | prepend: site.baseurl }}">
  <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
</head>


text:
module FormHelper
  def form_errors(errors, field_name)
    tag.div(id: "error-#{field_name.to_s.dasherize}") do
      tag.ul(class: %w[help-block error-block]) do
        safe_join(errors.map { |e| tag.li(e) })
      end
    end
  end

  def form_group(form, field_name, label: nil, help: nil, attributes: {}, &block)
    raise "No input field given" unless block_given?

    errors = form.object.errors[field_name]
    attributes[:class] = Array(attributes[:class]) << "form-group"
    attributes[:class] << "has-error" if errors.any?

    tag.div(**attributes) do
      wrapped_label = tag.div(class: "form-label") { form_label_element(form, field_name, label) }
      wrapped_field = tag.div(class: "form-wrapper", &block)
      errors = form_errors(errors, field_name)
      help = tag.div(class: "help-block") { help } if help

      safe_join([wrapped_label, help, errors, wrapped_field])
    end
  end

private

  def form_label_element(form, field_name, label)
    return label if label&.match?(/\A<label/) # already a label element

    form.label(field_name, label)
  end
end


text:
Gunter
======

A simple and clean theme for [Ghost](https://github.com/tryghost/ghost/) by [Germán Encinas](http://germanencinas.com/).

View Gunter in action [here](http://germanencinas.com/).

## Features

* Responsive design
* Sass powered
* Icons provided by [Font-Awesome](https://github.com/FortAwesome/Font-Awesome).
* Syntax highlighting using [Highlight.js](https://github.com/isagalaev/highlight.js)

## License

Copyright (c) 2015 Germán Encinas - Released under The MIT License.


text:
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <meta charset="utf-8">
  <meta name="theme-color" content="#FF5252">
  <link rel="icon" type="image/png" href="/images/logo_transparent.png" sizes="256x256">

  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="https://code.getmdl.io/1.2.1/material.teal-red.min.css">

  <link rel="stylesheet" href="/style.css?s=28092016" type="text/css" media="screen">

  <link rel="import" href="/third_party/bower_components/polymer/polymer.html">
  <link rel="import" href="/third_party/bower_components/paper-audio-player/paper-audio-player.html?s=28092016">
  <link rel="import" href="/third_party/bower_components/paper-fab-transitions/paper-fab-speed-dial.html">
  <link rel="import" href="/third_party/bower_components/paper-fab/paper-fab.html">
  <link rel="import" href="/third_party/bower_components/paper-fab-transitions/paper-fab-transitions.html">
  <link rel="import" href="/third_party/bower_components/iron-icons/social-icons.html">

  {{ partial "meta.html" . }}

  {{ partial "adwords-conversion.html" . }}

        About

        <button id="subscribe-menu"
                class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored">
          Subscribe
        </button>

RSS Feed

iTunes

Google Play Music

Stitcher Radio

YouTube


text:
{
  createRuntime(__filename).then(runtime => {
    const root = runtime.requireModule(runtime.__mockRootPath);
    const mock1 = root.jest.fn();
    mock1();
    const mock2 = root.jest.fn();
    mock2();
    expect(mock1).toBeCalled();
    expect(mock2).toBeCalled();
    jest.clearAllMocks();
    expect(mock1).not.toBeCalled();
    expect(mock2).not.toBeCalled();
  });
}


text:
set -e

# Verify that the libraries are error and warning-free.
echo "Running dartanalyzer..."
dartanalyzer $DARTANALYZER_FLAGS \
  lib/sdk_builds.dart

# Run the tests.
echo "Running tests..."
pub run test

# Install dart_coveralls; gather and send coverage data.
if [ "$COVERALLS_TOKEN" ] && [ "$TRAVIS_DART_VERSION" = "stable" ]; then
  echo "Running coverage..."
  pub global activate dart_coveralls
  pub global run dart_coveralls report \
    --exclude-test-files \
    --debug \
    test/sdk_builds_test.dart
fi


text:
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

from enum import Enum
from datetime import datetime
import json

SCORE_TO_REPUTATION_TEXT = {
    Common.DBotScore.NONE: f"None ({Common.DBotScore.NONE})",
    Common.DBotScore.GOOD: f"Good ({Common.DBotScore.GOOD})",
    Common.DBotScore.SUSPICIOUS: f"Suspicious ({Common.DBotScore.SUSPICIOUS})",
    Common.DBotScore.BAD: f"Bad ({Common.DBotScore.BAD})",
}

class AcceptedHeader(str, Enum):
    INDICATOR_TYPE = "Indicator Type"
    VALUE = "Value"
    REPUTATION = "Reputation"
    RELATIONSHIP_TYPE = "Relationship Type"
    ENTITY_CATEGORY = "Entity Category"
    TIMESTAMP = "Timestamp UTC"

ACCEPTED_HEADERS = [
    AcceptedHeader.INDICATOR_TYPE, AcceptedHeader.VALUE,
    AcceptedHeader.REPUTATION, AcceptedHeader.RELATIONSHIP_TYPE,
    AcceptedHeader.ENTITY_CATEGORY, AcceptedHeader.TIMESTAMP
]

def check_acceptable_headers(headers):
    for header in headers:
        if header not in ACCEPTED_HEADERS:
            raise ValueError(f"Please provide columns from {ACCEPTED_HEADERS}!")

def create_relationship_object(value: str, relationship_type: str, indicator_type: str,
                               timestamp: str, entity_category: str, reputation: int = Common.DBotScore.NONE):
    try:
        timestamp_parsed = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
        timestamp_human_readable = timestamp_parsed.strftime("%Y-%m-%d, %H:%M:%S")
    except ValueError:
        demisto.info("could not parse timestamp %s, keeping original string", timestamp)
        timestamp_human_readable = timestamp

    indicator_object = {
        "Value": f"{value}\n",
        "Reputation": SCORE_TO_REPUTATION_TEXT[reputation],
        "Relationship Type": relationship_type,
        "Indicator Type": indicator_type,
        "Timestamp UTC": timestamp_human_readable,
        "Entity Category": entity_category,
    }

    return indicator_object

def cyren_feed_relationship(args) -> CommandResults:
    if "indicator" not in args:
        raise ValueError("Please provide 'indicator' argument!")

    indicator = args["indicator"]
    if isinstance(indicator, str):
        try:
            indicator = json.loads(indicator)
        except json.JSONDecodeError:
            raise ValueError("Please provide JSON-encoded 'indicator' param!")
    elif not isinstance(indicator, dict):
        raise ValueError("Please provide JSON-encoded 'indicator' param!")

    headers = args.get("columns", ACCEPTED_HEADERS)
    if isinstance(headers, str):
        headers = [s.strip() for s in headers.split(",")]

    check_acceptable_headers(headers)

    relationships = indicator.get("CustomFields", {}).get("cyrenfeedrelationships", []) or []

    content = []

    for item in relationships:
        ioc_value = item.get("value", "")
        search_indicators = IndicatorsSearcher()

        results = search_indicators.search_indicators_by_version(value=ioc_value).get("iocs", [])

        if results:
            result = results[0]
            ioc_score = result.get("score")
            ioc_id = result.get("id")

            content.append(create_relationship_object(
                value=f"[{ioc_value}](#/indicator/{ioc_id})" if ioc_value else "",
                relationship_type=item.get("relationshiptype"),
                indicator_type=item.get("indicatortype"),
                timestamp=item.get("timestamp"),
                entity_category=item.get("entitycategory"),
                reputation=ioc_score,
            ))

        else:
            # In case that no related indicators were found, return the table without the link.
            content.append(create_relationship_object(
                value=ioc_value,
                relationship_type=item.get("relationshiptype"),
                indicator_type=item.get("indicatortype"),
                timestamp=item.get("timestamp"),
                entity_category=item.get("entitycategory"),
            ))

    output = tableToMarkdown("", content, headers, removeNull=True)
    return CommandResults(readable_output=output)

def main(args):
    try:
        return_results(cyren_feed_relationship(args))
    except Exception as e:
        return_error(f"Failed to execute CyrenThreatInDepthRenderRelated. Error: {str(e)}")

if __name__ in ("__main__", "__builtin__", "builtins"):
    main(demisto.args())