text:
namespace MDL {
namespace Paillier {
struct Encryption {};
//forward declaration
class Ctxt;
typedef std::vector<NTL::ZZ> PrimeSet;

class PubKey {
public:
    explicit PubKey(const NTL::ZZ &n);
    PubKey(const PubKey &oth);
    PubKey& operator=(const PubKey &oth) = delete;
    bool operator==(const PubKey &oth) const;
    ~PubKey() {}
    void Encrypt(Ctxt &ctxt, const NTL::ZZ &plain) const;
    void Encrypt(Ctxt &ctxt, const long plain) const;
    void Pack(Ctxt &ctxt, const std::vector<long> &slots, int bits) const;
    void Pack(Ctxt &ctxt, long m, int bits) const;
    const NTL::ZZ& GetN() const;
    const NTL::ZZ& GetG() const;
    const NTL::ZZ& GetN2() const;
    const PrimeSet& GetPrimes() const;
    PrimeSet GetPrimes(long bits) const;
    long bits_per_prime() const;
    long bits_all_prime() const;
private:
    class PubKeyImp;
    std::shared_ptr<PubKeyImp> imp = nullptr;
};

class SecKey {
public:
    explicit SecKey(const NTL::ZZ &p, const NTL::ZZ &q, const PubKey &pk);
    SecKey(const SecKey &oth);
    SecKey& operator=(const SecKey &oth) = delete;
    bool operator==(const SecKey &oth) const;
    ~SecKey() {}
    void Encrypt(Ctxt &ctxt, const NTL::ZZ &plain) const;
    void Encrypt(Ctxt &ctxt, const long plain) const;
    void Decrypt(NTL::ZZ &plain, const Ctxt &ctxt) const;
    void Decrypt(long &plain, const Ctxt &ctxt) const;
    void Unpack(std::vector<NTL::ZZ> &slots, const Ctxt &ctxt, int bits) const;
    const PubKey &GetPk() const;
private:
    class SecKeyImp; // implementation
    std::shared_ptr<SecKeyImp> imp = nullptr;
};

class Ctxt {
public:
    explicit Ctxt(const PubKey &pk);
    Ctxt(const Ctxt &oth);
    Ctxt& operator=(const Ctxt &oth) = delete;
    Ctxt& operator+=(const Ctxt &oth);
    Ctxt& operator+=(long v);
    Ctxt& operator+=(const NTL::ZZ &v);
    Ctxt& operator-=(const Ctxt &oth);
    Ctxt& operator-=(long v);
    Ctxt& operator-=(const NTL::ZZ &v);
    Ctxt& operator*=(long v);
    Ctxt& operator*=(const NTL::ZZ &v);
    Ctxt& negate();
    ~Ctxt() {}
    void SetCtxt(const NTL::ZZ &number);
    void SetCtxt(const long number);
    const PubKey& GetPk() const;
    const NTL::ZZ& GetValue() const;
private:
    class CtxtImp;
    std::shared_ptr<CtxtImp> imp = nullptr;
};

std::pair<SecKey, PubKey> GenKey(long bits);
}// namespace Paillier
}// namespace MDL
#endif // MDL_PAILLER_HPP


text:
package edu.jhu.pacaya.hypergraph.depparse;

import edu.jhu.pacaya.hypergraph.AbstractHypergraphTest;
import edu.jhu.pacaya.util.semiring.RealAlgebra;

public class O1DpHypergraphTest extends AbstractHypergraphTest {

    RealAlgebra s = RealAlgebra.getInstance();

    protected O1DpHypergraph getHypergraph() {
        double[] root = new double[] {1, 2, 3};
        double[][] child = new double[][]{ {0, 4, 5}, {6, 0, 7}, {8, 9, 0} };
        O1DpHypergraph graph = new O1DpHypergraph(root, child, s, true);
        return graph;
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace design_pattern
{
	interface ILifeViewer
	{
		void View( int maxLife, int currentLife );
	}
}


text:
jQuery.fn.centerFixed = function () {
    this.css("position","fixed");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
                                                $(window).scrollLeft()) + "px");
    return this;
}

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
                                                $(window).scrollLeft()) + "px");
    return this;
}

var closeWindow = function() {
    $('.mouth').addClass('closed');
    $('.window-left-toast').addClass('closed');
    $('.window-right-toast').addClass('closed');
    $('.window-center-col').addClass('closed');
    $('.window-container').hide();
};

var openWindow = function() {
    $('.mouth').removeClass('closed');
    $('.window-left-toast').removeClass('closed');
    $('.window-right-toast').removeClass('closed');
    $('.window-center-col').removeClass('closed');
    $('.window-container').show();
};

var toggleWindow = function() {
    $('.mouth').toggleClass('closed');
    $('.window-left-toast').toggleClass('closed');
    $('.window-right-toast').toggleClass('closed');
    $('.window-center-col').toggleClass('closed');
    $('.window-container').toggle();
};

var resetTools = function() {
    $('#pencil').removeClass('selected');
    $('#eraser').removeClass('selected');
    $('#pencil').removeClass('inactive');
    $('#eraser').removeClass('inactive');
};

var selectPencil = function() {
    isEraserSelected=false;
    resetTools();
    $('#pencil').addClass('selected');
    $('#eraser').addClass('inactive');
    openWindow();

    $("#eraser-selected-balloon").hide();
};

var selectEraser = function() {
    isEraserSelected=true;
    resetTools();
    $('#eraser').addClass('selected');
    $('#pencil').addClass('inactive');
    closeWindow();

    $("#eraser-selected-balloon").show();
    $("#eraser-selected-balloon").css("left", $('.window').width()/2 + 30);
};

//initialize selectbox
$('select').selectBox();
// init
$('#map-container').hide();
$('#tileset-widget').hide();
$('#export-widget').hide();
$('#tools-widget').hide();
$('#data-widget').center();
$('#export-widget').centerFixed();
$('#data-form').validate();
$('#new-button').addClass("disabled");
$('#export-button').addClass("disabled");

var initWidth = 229;
console.log("INIT WIDTH = "+initWidth);

// pencil is selected by default
selectPencil();

$('#pencil').click(function(){
    selectPencil();
});

$('#eraser').click(function(){
    selectEraser();
});

$('#tileset-widget-button').click(function(){
    if(isEraserSelected)
    {
        selectPencil();
        toggleWindow();
    }
});

window.onresize = function(event) {
    $('#map-container').center();
    $('#data-widget').center();
    $('#export-widget').centerFixed();

    if($('#map-container').offset().top < 52)
    {
        $('#map-container').css('top', '72px');
    }

    if($('#data-widget').offset().top < 52)
    {
        $('#data-widget').css('top', '72px');
    }

    if($('#export-widget').offset().top < 52)
    {
        $('#export-widget').css('top', '72px');
    }
};

var setupWindows = function() {
    // leave 30px for the scrollbar
    // and 20*2px for the toast background
    $('.window-container').width($('.window-container').width() + 30);
    $('.window-center-col').width($('.window-container').width());
    $('.window').width($('.window-container').width() + 20*2);

    $('.window-header-button').click(function(event) {

        if(!isEraserSelected)
        {
            toggleWindow();
        }
    });

    // jQuery UI for dragging
    $('.window').draggable();
};

$('#language-select').change(function() {
    console.log('select changed = '+$("#language-select").val());
    languageChanged($("#language-select").val());
});

var languageChanged = function(language) {

    if(language === "cpp")
    {
        $('#export-text-area').show();
        $('#ogmo-project-export').hide();
        $('#ogmo-level-export').hide();
        $('#export-text-area').val(printLevelCpp());
    }
    else if(language === "as3")
    {
        $('#export-text-area').show();
        $('#ogmo-project-export').hide();
        $('#ogmo-level-export').hide();
        $('#export-text-area').val(printLevelAS3());
    }
    else if(language === "flashpunk")
    {
        $('#export-text-area').show();
        $('#ogmo-project-export').hide();
        $('#ogmo-level-export').hide();
        $('#export-text-area').val(printLevelFlashPunk());
    }
    else if(language === "toast")
    {
        $('#export-text-area').show();
        $('#ogmo-project-export').hide();
        $('#ogmo-level-export').hide();
        $('#export-text-area').val(printLevelToast());
    }
    else if(language === "ogmo")
    {
        $('#export-text-area').hide();
        $('#ogmo-project-export').show();
        $('#ogmo-level-export').show();

        $('#ogmo-project-area').val(printOgmoProject());
        $('#ogmo-level-area').val(printOgmoLevel());
    }
    else if(language === "csv")
    {
        $('#export-text-area').show();
        $('#ogmo-project-export').hide();
        $('#ogmo-level-export').hide();

        $('#export-text-area').val(printLevelCSV());
    }
    else if(language === "phaser")
    {
        $('#export-text-area').show();
        $('#ogmo-project-export').hide();
        $('#ogmo-level-export').hide();

        $('#export-text-area').val(printLevelPhaser());
    }
};


text:
const Promise = require('promise')
const DisplayRpcClient = require('./display-rpc-client')

/**
 * I know how to display stuff. Updater tells me what's going on, and I make sure it is displayed correctly.
 *
 * If displayRpcPort is given, then I'll use RPC to talk to a separate service that handles display stuff,
 * using this protocol: https://github.com/sveasmart/display
 *
 * If displayRpcPort is not given (or falsy), then I'll just log to the local console.
 */
class Display {
  constructor(deviceId, displayRpcPort, mainDisplayTab, logCalls = true) {
    this.deviceId = deviceId
    console.assert(deviceId, "missing deviceId param")

    this.displayRpcPort = displayRpcPort
    if (this.displayRpcPort) {
      console.log("I will talk to a display via RPC on port " + this.displayRpcPort)

      this.mainDisplayTab = mainDisplayTab
      console.assert(mainDisplayTab, "missing mainDisplayTab param")

      this.logCalls = logCalls

      this.mainTabColumn = 0

      this.updaterStatus = "Starting up..."
      this.updaterError = null
      this.wasLastDisplayCallSuccessful = false

    } else {
      console.log("No displayRpcPort set, so I will use console.log")
    }

  }

  showNetworkConnecting() {
    this._setStatusAndSendToDisplay("Connecting...")
  }

  showNetworkOk() {
    this._setStatusAndSendToDisplay("Connected")
  }

  showNetworkError(err) {
    this._setStatusAndSendToDisplay("NETWORK ERROR", err)
  }

  showUpdateError(err) {
    this._setStatusAndSendToDisplay("UPDATE ERROR", err)
  }

  showUpdating() {
    this._setStatusAndSendToDisplay("Updating...")
  }

  showUpdateDone() {
    this._setStatusAndSendToDisplay("Update done!")
  }

  showDeviceId() {
    this._sendStatusToDisplay()
  }

  resendStatusToDisplayIfLastAttemptFailed() {
    if (!this.wasLastDisplayCallSuccessful) {
      console.log("Last RPC-call to display failed, so I'm trying again now.")
      this._sendStatusToDisplay()
    }
  }

  _setStatusAndSendToDisplay(status, error) {
    this.updaterStatus = status
    this.updaterError = error
    this._sendStatusToDisplay()
  }

  /*
    Sends the current status to the display.
    This is the ONLY public method that uses _call(...).
    The other methods above just update the status, and then call this method.
   */
  _sendStatusToDisplay() {
    if (!this.displayRpcPort) {
      if (this.updaterError) {
        console.log(this.updaterStatus, this.updaterError)
      } else {
        console.log(this.updaterStatus)
      }
      return
    }

    //Write the current status on row 7 of the main tab
    this._writeLineOnMainTab(7, this.updaterStatus)

    //We aways write deviceId as well.
    const deviceIdUpperCase = this.deviceId.toUpperCase()
    this._writeLineOnMainTab(6, 'ID: ' + deviceIdUpperCase)
  }

  _writeLineOnMainTab(row, text) {
    const col = this.mainTabColumn
    const rowLength = 16 - col
    //Add blank spaces to the rest of the row to override anything else there
    while (text.length < rowLength) {
      text = text + " "
    }
    this._call("writeText", [text, col, row, false, this.mainDisplayTab])
  }

  /*
    Triggers the RPC call to the display app.
    This is the ONLY method that talks to DisplayRpcClient and does that.
   */
  _call(method, args) {
    const displayRpcClient = new DisplayRpcClient(this.displayRpcPort, this.logCalls)
    displayRpcClient.call(method, args)
      .then(() => {
        this.wasLastDisplayCallSuccessful = true
      })
      .catch((err) => {
        this.wasLastDisplayCallSuccessful = false
      })
  }
}

module.exports = Display


text:
require 'rails_helper'

feature 'User views a unit of measure' do
  let(:unit_of_measure) { create(:unit_of_measure) }

  scenario 'the user sees the unit of measure' do
    visit unit_of_measure_path(unit_of_measure)

    expect(page).to have_content('Unit of Measure')
    expect(page).to have_content(unit_of_measure.name)
    expect(page).to have_content(unit_of_measure.symbol)
    expect(page).to have_content(unit_of_measure.unit_type)
    expect(page).to have_content(unit_of_measure.uuid)
  end
end


text:
require "spec_helper"

describe Chef::Resource::SelinuxPort do
  let(:node) { Chef::Node.new }
  let(:events) { Chef::EventDispatch::Dispatcher.new }
  let(:run_context) { Chef::RunContext.new(node, {}, events) }
  let(:resource) { Chef::Resource::SelinuxPort.new("5678", run_context) }
  let(:provider) { resource.provider_for_action(:manage) }

  it "sets port property as name_property" do
    expect(resource.port).to eql("5678")
  end

  it "sets the default action as :manage" do
    expect(resource.action).to eql([:manage])
  end

  it "supports :manage, :addormodify, :add, :modify, :delete actions" do
    expect { resource.action :manage }.not_to raise_error
    expect { resource.action :addormodify }.not_to raise_error
    expect { resource.action :add }.not_to raise_error
    expect { resource.action :modify }.not_to raise_error
    expect { resource.action :delete }.not_to raise_error
  end
end


text:
package org.apache.solr.handler.loader;

import java.io.IOException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.processor.UpdateRequestProcessor;

public class CSVLoader extends ContentStreamLoader {
  @Override
  public void load(
      SolrQueryRequest req,
      SolrQueryResponse rsp,
      ContentStream stream,
      UpdateRequestProcessor processor)
      throws Exception {
    new SingleThreadedCSVLoader(req, processor).load(req, rsp, stream, processor);
  }
}

class SingleThreadedCSVLoader extends CSVLoaderBase {
  SingleThreadedCSVLoader(SolrQueryRequest req, UpdateRequestProcessor processor) {
    super(req, processor);
  }

  @Override
  public void addDoc(int line, String[] vals) throws IOException {
    templateAdd.clear();
    SolrInputDocument doc = new SolrInputDocument();
    doAdd(line, vals, doc, templateAdd);
  }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template erase_head</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../string_algo/reference.html#header.boost.algorithm.string.erase_hpp" title="Header <boost/algorithm/string/erase.hpp>">
<link rel="prev" href="erase_head_copy.html" title="Function erase_head_copy">
<link rel="next" href="erase_tail_copy.html" title="Function erase_tail_copy">

Home
Libraries
People
FAQ
More

Function template erase_head

boost::algorithm::erase_head — Erase head algorithm.

Synopsis

// In header: <boost/algorithm/string/erase.hpp>

template<typename SequenceT> void erase_head(SequenceT & Input, int N);

Description

Remove the head from the input. The head is a prefix of a sequence of given size. If the sequence is shorter then required, the whole string is considered to be the head. The input sequence is modified in-place.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Parameters:

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Input

An input string

N

Length of the head For N>=0, at most N characters are extracted. For N<0, size(Input)-|N| characters are extracted.

Copyright © 2002-2004 Pavol Droba
Use, modification and distribution is subject to the Boost
                Software License, Version 1.0. (See accompanying file
                LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package com.elearning.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.elearning.dao.TeacherDao;
import com.elearning.entity.Teacher;
import com.elearning.service.TeacherService;
import com.elearning.tools.Md5Hash;

@Service(value="teacherServiceImpl")
@Transactional
public class TeacherServiceImpl implements TeacherService {

	@Autowired
	private TeacherDao teacherDao;

	public void insertBasicInformation(String ID, String name, String department, String phonenumber) {
		teacherDao.insertBasicInformation(ID, name, department, phonenumber);
	}

	public void register(Teacher teacher) {
		teacherDao.register(teacher);
	}

	public void modifyPassword(String ID, String password) {
		teacherDao.modifyPassword(ID, Md5Hash.toMD5(password));
	}

	public void editInfomation(String ID, String name, String image) {
		teacherDao.editInfomation(ID, name, image);
	}

	public String getPassword(String ID) {
		return teacherDao.getPassword(ID);
	}

	public void delete(String ID) {
		teacherDao.delete(ID);
	}

	public Teacher findByID(String ID) {
		return teacherDao.findByID(ID);
	}

	public List<Teacher> findByName(String name) {
		return teacherDao.findByName(name);
	}

	public List<Teacher> findAll() {
		return teacherDao.findAll();
	}

}


text:
'use strict';

var _ = require('./');

var _2 = _interopRequireDefault(_);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

(0, _2.default)().catch(function (err) {
  console.error(err.message + '\n' + err.stack);
});


text:
package org.knowm.xchange.bitfinex.v1.dto.trade;

import org.knowm.xchange.dto.Order.IOrderFlags;

public enum BitfinexOrderFlags implements IOrderFlags {

  /**
   * This type of order is a limit order that must be filled in its entirety or cancelled (killed).
   */
  FILL_OR_KILL,

  /**
   * This is an order which does not appear in the orderbook, and thus doesn't influence other
   * market participants. the taker fee will apply to any trades.
   */
  HIDDEN,

  /** These are orders that allow you to be sure to always pay the maker fee. */
  POST_ONLY,

  /**
   * For order amends indicates that the new order should use the remaining amount of the original
   * order.
   */
  USE_REMAINING,

  /**
   * This type of order a margin order that is leveraged in line with bitfinex current leverage
   * rates.
   */
  MARGIN,

  /** Trailing stop order */
  TRAILING_STOP,

  /** Stop order */
  STOP
}


text:
Getting Started
###############
It only takes a few minutes to get StreamAlert up and running! These instructions have been tested
on MacOS, but should also work on most linux systems.

********************
Install Dependencies
********************

1. Install Python 3.7 and `pip <https://pip.pypa.io/en/stable/installing/>`_
2. Install `Terraform <https://www.terraform.io/intro/getting-started/install.html>`_ >= v0.13.0:

.. code-block:: bash

  brew install terraform  # MacOS Homebrew
  terraform --version     # Must be >= v0.13.0

.. note::

  Terraform versions lower than 0.13 are not supported. We recommend installing Terraform
  version 0.13.0 or greater.

3. If you are using Linux, you may need to install the Python development libraries:

.. code-block:: bash

  sudo apt install python-dev    # Debian
  sudo yum install python-devel  # CentOS/RHEL

********************
Download StreamAlert
********************
1. Clone the latest stable release of StreamAlert:

.. code-block:: bash

  git clone --branch stable https://github.com/airbnb/streamalert.git

2. Create and activate a virtual environment:

.. code-block:: bash

  cd streamalert
  python3.7 -m venv venv
  source venv/bin/activate

3. Install the StreamAlert requirements:

.. code-block:: bash

  pip install -r requirements.txt

4. Run unit tests to make sure everything is installed correctly:

.. code-block:: bash

  tests/scripts/unit_tests.sh

*************************
Configure AWS Credentials
*************************
1. Create an AWS account and an `IAM user <https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html>`_
with permissions for at least the following services:

* Athena
* CloudTrail
* CloudWatch Events and Logs
* DynamoDB
* Glue
* IAM
* Kinesis Firehose and Streams
* KMS
* Lambda
* S3
* SNS
* SQS

2. Configure your AWS credentials

.. code-block:: bash

  pip install --user awscli
  aws configure

******
Deploy
******
.. note:: StreamAlert supports Terraform's native ability to lock the remote s3 state file whenever a user is planning and applying Terraform configuration.
    This is to prevent multiple users from deploying StreamAlert at the same time potentially resulting in a broken state.
    StreamAlert will automatically create and destroy this table via the command line interface.
    See `Terraform's documentation <https://www.terraform.io/docs/backends/types/s3.html>`_ for more information.

1. Set basic StreamAlert configuration options:

.. code-block:: bash

  python manage.py configure aws_account_id 111111111111  # Replace with your 12-digit AWS account ID
  python manage.py configure prefix <value>               # Choose a unique name prefix (alphanumeric characters only)

  .. code-block:: bash

    "athena_partitioner_config": {
      "concurrency_limit": 10,
      "file_format": "parquet",
      "log_level": "info"
    }

  * More information can be found on the `historical search <historical-search.html>`_ page.

2. Build the StreamAlert infrastructure for the first time:

.. code-block:: bash

  python manage.py init

There will be multiple Terraform prompts, type "yes" at each one to continue.

.. note:: You only need to ``python manage.py init`` once for any given StreamAlert deployment,
   although it is safe to run again if necessary.

3. At this point, StreamAlert is up and running! You can, for example, see the S3 buckets
that were automatically created:

.. code-block:: bash

  aws s3 ls | grep streamalert

You can also login to the AWS web console and see StreamAlert's CloudWatch logs, Lambda functions, etc.

*********
Live Test
*********
Now let's upload some data and trigger an alert to see StreamAlert in action! This example uses
SNS for both sending the log data and receiving the alert, but StreamAlert also supports many other
`data sources <datasources.html>`_ and `alert outputs <outputs.html>`_.

1. Create 2 SNS topics:

.. code-block:: bash

  aws sns create-topic --name streamalert-test-data
  aws sns create-topic --name streamalert-test-alerts

2. Export some environment variables for easy re-use later:

.. code-block:: bash

  export SA_REGION=us-east-1        # StreamAlert deployment region
  export SA_ACCOUNT=111111111111    # AWS account ID
  export SA_EMAIL=email@domain.com  # Email to receive an SNS notification

3. Subscribe your email to the alerts SNS topic:

.. code-block:: bash

  aws sns subscribe --topic-arn arn:aws:sns:$SA_REGION:$SA_ACCOUNT:streamalert-test-alerts \
      --protocol email --notification-endpoint $SA_EMAIL

.. note:: You will need to click the verification link in your email to activate the subscription.

4. Add the ``streamalert-test-data`` SNS topic as an input to the (default) ``prod`` `cluster <config-clusters.html>`_.
Open ``conf/clusters/prod.json`` and change the ``streamalert`` module to look like this:

.. code-block:: json

  {
    "classifier_config": {
      "enable_custom_metrics": true,
      "inputs": {
        "aws-sns": [
          "arn:aws:sns:REGION:ACCOUNTID:streamalert-test-data"
        ]
      },
      "log_level": "info",
      "log_retention_days": 14,
      "memory": 128,
      "timeout": 60
    }
  }

5. Tell StreamAlert which `log schemas <config-schemas.html>`_ will be sent to this input.
Open ``conf/clusters/prod.json`` and change the ``data_sources`` section to look like this:

.. code-block:: json

  {
    "data_sources": {
      "sns": {
        "streamalert-test-data": [
          "cloudwatch"
        ]
      }
    }
  }

6. Add the alert topic as a StreamAlert output:

.. code-block:: bash

  python manage.py output set aws-sns

  Please supply a short and unique descriptor for this SNS topic: test-email

  Please supply SNS topic name: streamalert-test-alerts

If you look at ``conf/outputs.json``, you'll notice that the SNS topic was automatically added.

7. Configure a rule to send to the alerts topic.
We will use ``rules/community/cloudwatch_events/cloudtrail_root_account_usage.py`` as an example, which
alerts on any usage of the root AWS account. Change the rule decorator to:

.. code-block:: python

  @rule(
      logs=['cloudwatch:events'],
      req_subkeys={'detail': ['userIdentity', 'eventType']},
      outputs=['aws-sns:test-email']  # Add this line
  )
  def cloudtrail_root_account_usage(rec):

8. Now we need to update StreamAlert with these changes:

.. code-block:: bash

  # Hook the streamalert-test-data SNS topic up to the StreamAlert Classifier function
  python manage.py build

  # Deploy a new version of all of the Lambda functions with the updated rule and config files
  python manage.py deploy

.. note:: Use ``build`` and ``deploy`` to apply any changes to StreamAlert's
   configuration or Lambda functions, respectively. Some changes (like this example) require both.

9. Time to test! Create a file named ``cloudtrail-root.json`` with the following contents:

.. code-block:: json

  {
    "account": "1234",
    "detail": {
      "eventType": "AwsConsoleSignIn",
      "userIdentity": {
        "type": "Root"
      }
    },
    "detail-type": "CloudTrail Test",
    "id": "1234",
    "region": "us-east-1",
    "resources": [],
    "source": "1.1.1.2",
    "time": "now",
    "version": "2018"
  }

This is only a rough approximation of what the real log might look like, but good enough for our purposes.
Then send it off to the data SNS topic:

.. code-block:: bash

  aws sns publish --topic-arn arn:aws:sns:$SA_REGION:$SA_ACCOUNT:streamalert-test-data \
      --message "$(cat cloudtrail-root.json)"

If all goes well, an alert should arrive in your inbox within a few minutes!
If not, look for any errors in the CloudWatch Logs for the StreamAlert Lambda functions.

10. After 10 minutes (the default refresh interval), the alert will also be searchable from
`Amazon Athena <https://console.aws.amazon.com/athena>`_. Select your StreamAlert database in the
dropdown on the left and preview the ``alerts`` table:

.. figure:: ../images/athena-alerts-search.png
  :alt: Query Alerts Table in Athena
  :align: center
  :target: _images/athena-alerts-search.png

(Here, my name prefix is ``testv2``.) If no records are returned, look for errors
in the Athena Partitioner function or try invoking it directly.

And there you have it! Ingested log data is parsed, classified, and scanned by the rules engine.
Any resulting alerts are delivered to your configured output(s) within a matter of minutes.


text:
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import datetime
import enum
import os
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from app.database import db

class Publisher(db.Model):
    """
    This class is DB model for storing publisher attributes
    """
    __tablename__ = 'publisher'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    name = db.Column(db.TEXT, unique=True, index=True, nullable=False)
    title = db.Column(db.Text)
    private = db.Column(db.BOOLEAN, default=False)
    description = db.Column(db.Text)
    country = db.Column(db.Text)
    email = db.Column(db.Text)
    phone = db.Column(db.Text)
    contact_public = db.Column(db.BOOLEAN)

    packages = relationship("Package", back_populates="publisher")

    users = relationship("PublisherUser", back_populates="publisher",
                         cascade='save-update, merge, delete, delete-orphan')

    @classmethod
    def get_by_name(cls, publisher):
        publisher = Publisher.query.filter_by(name=publisher).first()
        return publisher

class User(db.Model):
    """
    This class is DB model for storing user attributes
    """

    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    email = db.Column(db.TEXT, unique=True, index=True)
    secret = db.Column(db.TEXT, default=os.urandom(24).encode('hex'))
    name = db.Column(db.TEXT, unique=True, index=True, nullable=False)
    full_name = db.Column(db.TEXT)
    sysadmin = db.Column(db.BOOLEAN, default=False)
    oauth_source = db.Column(db.TEXT, default='github')

    publishers = relationship("PublisherUser", back_populates="user",
                              cascade='save-update, merge, delete, delete-orphan')

    @classmethod
    def get_by_name(cls, user):
        user = User.query.filter_by(name=user).first()
        return user

class UserRoleEnum(enum.Enum):
    owner = "OWNER"
    member = "MEMBER"

class PublisherUser(db.Model):
    """
    This class is association object between user and publisher
    as they have many to many relationship
    """
    __tablename__ = 'publisher_user'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    user_id = db.Column(db.Integer, ForeignKey('user.id'), primary_key=True)
    publisher_id = db.Column(db.Integer, ForeignKey('publisher.id'), primary_key=True)

    role = db.Column(db.Enum(UserRoleEnum, native_enum=False), nullable=False)
    """role can only OWNER or MEMBER"""

    publisher = relationship("Publisher", back_populates="users")
    user = relationship("User", back_populates="publishers")


text:
"""Advent of Code 2016 - Day 10: Elves Look, Elves Say"""

import pdb
import sys
import traceback
from typing import Tuple

def look_and_say(sequence: str) -> str:
    # create a run-length list of (char, count) from the input
    rle = []
    old_ch = sequence[0]
    counter = 1
    for ch in sequence[1:]:
        if old_ch != ch:
            rle.append((old_ch, counter))
            old_ch = ch
            counter = 1
        else:
            counter += 1
    rle.append((old_ch, counter))

    # build the new say sequence from the character counts
    result = []
    for ch, count in rle:
        result.append(str(count))
        result.append(ch)

    # reassemble into a string as required by the specification
    result = "".join(result)

    return result

def solve(number: str) -> Tuple[int, int]:
    part_1 = number
    for _ in range(40):
        part_1 = look_and_say(part_1)

    part_2 = part_1
    for _ in range(10):
        part_2 = look_and_say(part_2)

    return (len(part_1), len(part_2))

if __name__ == "__main__":
    try:
        print(solve(sys.argv[1]))
    except Exception:
        traceback.print_exc()
        pdb.post_mortem()


text:
import { Component, OnInit, HostListener, ViewChild } from '@angular/core';
import { Utils } from '../../shared/utils/utils';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
footerAtEndPlacement = false;
loading = true;

@HostListener('window:resize', ['$event'])
onResize() {
  if (window.innerWidth > 980) {
    this.footerAtEndPlacement = false;
  } else {
    this.footerAtEndPlacement = true;
  }
}

  constructor() {}

  ngOnInit() {
    if (window.innerWidth > 980) {
      this.footerAtEndPlacement = false;
    } else {
      this.footerAtEndPlacement = true;
    }
    this.loading = false;
  }

  goToUrl(url: string) {
    Utils.goToUrl(url);
  }

}


text:
bezier.hazmat.intersection\_helpers module
==========================================

.. automodule:: bezier.hazmat.intersection_helpers
   :members:
   :inherited-members:
   :undoc-members:
   :show-inheritance:


text:
module CloudTempfile
  class Storage

    attr_accessor :config

    def initialize(cfg)
      @config = cfg
    end

    # This "connection" is the fog connection responsible for persisting the file
    # @return [Fog::Storage]
    def connection
      @connection ||= ::Fog::Storage.new(self.config.fog_options)
    end

    # This "directory" action should only be used with the cloud provider and returns a <tt>Fog::Storage::Directory</tt> class
    # @return [Fog::Storage::Directory]
    def directory(options={})
      prefix = options.has_key?(:prefix)? options[:prefix] : self.config.prefix
      @directory ||= connection.directories.get(self.config.fog_directory, :prefix => prefix)
    end

    # This action will upload a Fog::Storage::File to the specified directory
    # @return [Fog::Storage::File]
    def upload_file(f, body, options={})
      file = init_fog_file(f, body, options)
      if self.config.enabled?
        return directory(options).files.create( file )
      else
        return local_file(f, body, options)
      end
    end

    # Used with the "Local" provider which will utilize the local file system with Fog.
    # This is handy for development and test environments.
    # @return [Fog::Storage::Local::File]
    def local_file(f, body, options={})
      #return !self.config.public?
      file = init_fog_file(f, body, options)
      # If the "file" is empty then return nil
      return nil if file.nil? || file.blank? || local_root.nil?
      file = local_root(options).files.create( file )
    end

    # This action will delete a AWS::File from the specified directory
    # @param [Fog::Storage::File]
    def delete_file(f)
      #return false if !f.kind_of?(Fog::Storage::AWS::File) || !storage_provider.eql?(:aws)
      log "Deleting: #{f.key}"
      return f.destroy
    end

    # Returns a list of remote files for the specified directory
    # @throws [BucketNotFound]
    # @return [Array]
    def get_remote_files
      raise BucketNotFound.new("#{self.config.fog_provider} Bucket: #{self.config.fog_directory} not found.") unless directory
      files = []
      directory.files.each { |f| files << f if File.extname(f.key).present? }
      return files
    end

    # Delete the expired file which are expired if the "config.clean_up" is true
    # and "config.clean_up_older_than" is the amount of seconds it is older than.
    #
    # Note: This action should be used with the "bundle exec rake cloud_temp_file:clear" rake command (cronjob)
    def delete_expired_tempfiles
      return if !self.config.clean_up? || !self.config.enabled?
      log "CloudTempfile.delete_expired_tempfiles is running..."
      # Delete expired temp files
      fog_files = (self.config.local?)? local_root.files : get_remote_files
      fog_files.each do |file|
        if file.last_modified <= Time.now.utc.ago(self.config.clean_up_older_than)
          delete_file(file)
        end
      end
      log "CloudTempfile.delete_expired_tempfiles is complete!"
    end

    # Custom Errors (Exceptions)
    class BucketNotFound < StandardError; end

    private

    # Initialize a Hash object to be use to by <tt>Fog::Storage</tt> to persist
    # @param [String] filename
    # @param [Object] body
    # @return [Hash]
    def init_fog_file(filename, body, options={})
      # If the "filename" or the "body" are empty then return nil
      return nil if filename.nil? || body.nil?
      # Set file's access control list (ACL).

      aws_acl = (self.config.aws_acl?)? self.config.aws_access_control_list.to_s : nil
      # expiry is the number of seconds the file will available publicly
      expiry = options.has_key?(:expiry)? options[:expiry] : ((self.config.expiry?)? self.config.expiry.to_i : nil)
      ext = File.extname(filename)[1..-1] # The file extension
      mime = MultiMime.lookup(ext) # Look up the content type based off the file extension
      prefix = options.has_key?(:prefix)? options[:prefix] : self.config.prefix
      full_filename = (self.config.local? || !self.config.enabled?)? filename : "#{prefix}#{filename}"
      disposition_attachment = options.has_key?(:attachment)? options[:attachment] : false

      # file Hash to be used to create a Fog for upload
      file = {
        :key => "#{full_filename}",
        :body => body,
        :content_type => mime
      }
      file.merge!({:content_disposition => "attachment"})  if disposition_attachment

      file.merge!({:public => true}) if self.config.public?

      if self.config.aws?
        if self.config.public? && self.config.expiry?
          file.merge!({:cache_control => "public, max-age=#{expiry}"})
        end
        # valid acls: private, public-read, public-read-write, authenticated-read, bucket-owner-read, bucket-owner-full-control
        file.merge!({:acl=>self.config.aws_access_control_list.to_s}) if self.config.aws_acl?
        file.merge!({:expires => Time.now.utc.to_i + expiry}) if !self.config.public? && self.config.expiry?
        file.merge!({:storage_class => 'REDUCED_REDUNDANCY'}) if self.config.aws_rrs?
      end

      return file
    end

    # This "local_root" action should only be used with the "Local" provider and returns a Fog::Storage::Local::Directory class
    # @return [Fog::Storage::Local::Directory]
    def local_root(options={})
      prefix = options.has_key?(:prefix)? options[:prefix] : self.config.prefix

      begin
        if !connection.directories.get(prefix).nil?
          @local_root ||= connection.directories.get(prefix)
        else
          @local_root ||= connection.directories.create(:key => prefix)
        end
      rescue
        @local_root ||= connection.directories.create(:key => prefix)
      end
    end

    def log(msg)
      CloudTempfile.log(msg)
    end

  end
end


text:
import React from 'react';

class TuftsStandardBanner extends React.Component {

  render(){
    return (

Tufts Web Standard

              From a university's main .edu website to its individual school, department and center sites, in higher ed, the digital footprint for a single institution can be vast. With limited resources and a continuously growing portfolio of Drupal sites, it was clear our existing development model was unsustainable for our small digital team. We needed a solution for scaling development, while simultaneously reducing our maintenance burden.

PROJECT ROLE

Front-end Web Developer,

Technical Strategist

    )
  }

}

export default TuftsStandardBanner;


text:
extern crate elastic_responses;
extern crate serde_json;

use elastic_responses::*;
use ::load_file;

#[test]
fn success_parse_ping_response() {
    let f = load_file("tests/samples/ping_success.json");
    let deserialized = parse::<PingResponse>().from_reader(200, f).unwrap();

    assert_eq!("Scorcher", &deserialized.name);
}