text:
#include <zephyr.h>
#include <drivers/pwm.h>
#include <logging/log.h>

LOG_MODULE_REGISTER(pwm_capture, CONFIG_PWM_LOG_LEVEL);

struct z_pwm_pin_capture_cb_data {
	uint32_t period;
	uint32_t pulse;
	struct k_sem sem;
	int status;
};

static void z_pwm_pin_capture_cycles_callback(const struct device *dev,
					      uint32_t pwm,
					      uint32_t period_cycles,
					      uint32_t pulse_cycles,
					      int status,
					      void *user_data)
{
	struct z_pwm_pin_capture_cb_data *data = user_data;

	data->period = period_cycles;
	data->pulse = pulse_cycles;
	data->status = status;

	k_sem_give(&data->sem);
}

int z_impl_pwm_pin_capture_cycles(const struct device *dev, uint32_t pwm,
				  pwm_flags_t flags, uint32_t *period,
				  uint32_t *pulse, k_timeout_t timeout)
{
	struct z_pwm_pin_capture_cb_data data;
	int err;

	if ((flags & PWM_CAPTURE_MODE_MASK) == PWM_CAPTURE_MODE_CONTINUOUS) {
		LOG_ERR("continuous capture mode only supported via callback");
		return -ENOTSUP;
	}

	flags |= PWM_CAPTURE_MODE_SINGLE;
	k_sem_init(&data.sem, 0, 1);

	err = pwm_pin_configure_capture(dev, pwm, flags,
					z_pwm_pin_capture_cycles_callback,
					&data);
	if (err) {
		LOG_ERR("failed to configure pwm capture");
		return err;
	}

	err = pwm_pin_enable_capture(dev, pwm);
	if (err) {
		LOG_ERR("failed to enable pwm capture");
		return err;
	}

	err = k_sem_take(&data.sem, timeout);
	if (err == -EAGAIN) {
		(void)pwm_pin_disable_capture(dev, pwm);
		(void)pwm_pin_configure_capture(dev, pwm, flags, NULL, NULL);
		LOG_WRN("pwm capture timed out");
		return err;
	}

	if (data.status == 0) {
		if (period != NULL) {
			*period = data.period;
		}

		if (pulse != NULL) {
			*pulse = data.pulse;
		}
	}

	return data.status;
}


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

import javax.annotation.Generated;

/**
 *

 * The NextToken string was altered unexpectedly, and the operation has stopped. Run the operation without
 * changing the NextToken string, and try again.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidNextTokenException extends com.amazonaws.services.snowball.model.AmazonSnowballException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InvalidNextTokenException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InvalidNextTokenException(String message) {
        super(message);
    }

}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'
require 'logging'

class Synapse::EC2Watcher
  attr_reader   :synapse
  attr_accessor :default_servers, :ec2
end

class FakeAWSInstance
  def ip_address
    @ip_address ||= fake_address
  end

  def private_ip_address
    @private_ip_address ||= fake_address
  end

  def dns_name
    @dns_name ||= "ec2-#{ip_address.gsub('.', '-')}.eu-test-1.compute.amazonaws.com"
  end

  def private_dns_name
    @private_dns_name ||= "ip-#{private_ip_address.gsub('.', '-')}.eu-test-1.compute.internal"
  end

  def fake_address
    4.times.map { (0...254).to_a.shuffle.pop.to_s }.join('.')
  end
end

describe Synapse::EC2Watcher do
  let(:mock_synapse) { double }
  subject { Synapse::EC2Watcher.new(basic_config, mock_synapse) }

  let(:basic_config) do
    { 'name' => 'ec2tagtest',
      'haproxy' => {
        'port' => '8080',
        'server_port_override' => '8081'
      },
      "discovery" => {
        "method" => "ec2tag",
        "tag_name"   => "fuNNy_tag_name",
        "tag_value"  => "funkyTagValue",
        "aws_region" => 'eu-test-1',
        "aws_access_key_id" => 'ABCDEFGHIJKLMNOPQRSTU',
        "aws_secret_access_key" => 'verylongfakekeythatireallyneedtogenerate'
      }
    }
  end

  before(:all) do
    # Clean up ENV so we don't inherit any actual AWS config.
    %w[AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_REGION].each { |k| ENV.delete(k) }
  end

  before(:each) do
    # https://ruby.awsblog.com/post/Tx2SU6TYJWQQLC3/Stubbing-AWS-Responses
    # always returns empty results, so data may have to be faked.
    AWS.stub!
  end

  def remove_discovery_arg(name)
    args = basic_config.clone
    args['discovery'].delete name
    args
  end

  def remove_haproxy_arg(name)
    args = basic_config.clone
    args['haproxy'].delete name
    args
  end

  def munge_haproxy_arg(name, new_value)
    args = basic_config.clone
    args['haproxy'][name] = new_value
    args
  end

  describe '#new' do
    let(:args) { basic_config }

    it 'instantiates cleanly with basic config' do
      expect { subject }.not_to raise_error
    end

    context 'when missing arguments' do
      it 'complains if aws_region is missing' do
        expect {
          Synapse::EC2Watcher.new(remove_discovery_arg('aws_region'), mock_synapse)
        }.to raise_error(ArgumentError, /Missing aws_region/)
      end
      it 'complains if aws_access_key_id is missing' do
        expect {
          Synapse::EC2Watcher.new(remove_discovery_arg('aws_access_key_id'), mock_synapse)
        }.to raise_error(ArgumentError, /Missing aws_access_key_id/)
      end
      it 'complains if aws_secret_access_key is missing' do
        expect {
          Synapse::EC2Watcher.new(remove_discovery_arg('aws_secret_access_key'), mock_synapse)
        }.to raise_error(ArgumentError, /Missing aws_secret_access_key/)
      end
      it 'complains if server_port_override is missing' do
        expect {
          Synapse::EC2Watcher.new(remove_haproxy_arg('server_port_override'), mock_synapse)
        }.to raise_error(ArgumentError, /Missing server_port_override/)
      end
    end

    context 'invalid data' do
      it 'complains if the haproxy server_port_override is not a number' do
          expect {
            Synapse::EC2Watcher.new(munge_haproxy_arg('server_port_override', '80deadbeef'), mock_synapse)
          }.to raise_error(ArgumentError, /Invalid server_port_override/)
      end
    end
  end

  context "instance discovery" do
    let(:instance1) { FakeAWSInstance.new }
    let(:instance2) { FakeAWSInstance.new }

    context 'using the AWS API' do
      let(:ec2_client) { double('AWS::EC2') }
      let(:instance_collection) { double('AWS::EC2::InstanceCollection') }

      before do
        subject.ec2 = ec2_client
      end

      it 'fetches instances and filter instances' do
        # Unfortunately there's quite a bit going on here, but this is
        # a chained call to get then filter EC2 instances, which is
        # done remotely; breaking into separate calls would result in
        # unnecessary data being retrieved.

        expect(subject.ec2).to receive(:instances).and_return(instance_collection)

        expect(instance_collection).to receive(:tagged).with('foo').and_return(instance_collection)
        expect(instance_collection).to receive(:tagged_values).with('bar').and_return(instance_collection)
        expect(instance_collection).to receive(:select).and_return(instance_collection)

        subject.send(:instances_with_tags, 'foo', 'bar')
      end
    end

    context 'returned backend data structure' do
      before do
        expect(subject).to receive(:instances_with_tags).and_return([instance1, instance2])
      end

      let(:backends) { subject.send(:discover_instances) }

      it 'returns an Array of backend name/host/port Hashes' do

        expect(backends.all? {|b| %w[name host port].each {|k| b.has_key?(k) }}).to eql(true)
      end

      it 'sets the backend port to server_port_override for all backends' do
        backends = subject.send(:discover_instances)
        expect(backends.all? { |b| b['port'] == basic_config['haproxy']['server_port_override'] }).to eql(true)
      end
    end

    context 'returned instance fields' do
      before do
        expect(subject).to receive(:instances_with_tags).and_return([instance1])
      end

      let(:backend) { subject.send(:discover_instances).pop }

      it "returns an instance's private IP as the hostname" do
        expect( backend['host'] ).to eq instance1.private_ip_address
      end

      it "returns an instance's private hostname as the server name" do
        expect( backend['name'] ).to eq instance1.private_dns_name
      end
    end
  end

  context "configure_backends tests" do
    let(:backend1) { { 'name' => 'foo',  'host' => 'foo.backend.tld',  'port' => '123' } }
    let(:backend2) { { 'name' => 'bar',  'host' => 'bar.backend.tld',  'port' => '456' } }
    let(:fallback) { { 'name' => 'fall', 'host' => 'fall.backend.tld', 'port' => '789' } }

    before(:each) do
      expect(subject.synapse).to receive(:'reconfigure!').at_least(:once)
    end

    it 'runs' do
      expect { subject.send(:configure_backends, []) }.not_to raise_error
    end

    it 'sets backends correctly' do
      subject.send(:configure_backends, [ backend1, backend2 ])
      expect(subject.backends).to eq([ backend1, backend2 ])
    end

    it 'resets to default backends if no instances are found' do
      subject.default_servers = [ fallback ]
      subject.send(:configure_backends, [ backend1 ])
      expect(subject.backends).to eq([ backend1 ])
      subject.send(:configure_backends, [])
      expect(subject.backends).to eq([ fallback ])
    end

    it 'does not reset to default backends if there are no default backends' do
      subject.default_servers = []
      subject.send(:configure_backends, [ backend1 ])
      expect(subject.backends).to eq([ backend1 ])
      subject.send(:configure_backends, [])
      expect(subject.backends).to eq([ backend1 ])
    end
  end
end


text:
public class Adapter {
	// this is a singleton class
	private Adapter() {}

	// just returning the results of the methods from Matrix class
	// which just have different names
	public static Matrix add(Matrix l, Matrix r) {
		return Matrix.plus(l, r);
	}

	public static Matrix sub(Matrix l, Matrix r) {
		return Matrix.minus(l, r);
	}
}


text:
function f = imag(f)
%IMAG   Imaginary part of a SINGFUN.
%   IMAG(F) is the imaginary part of F.
%
% See also REAL, ISREAL, CONJ.

% Copyright 2015 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Check for empty arguments:
if ( isempty(f) )
    return;
end

% Compute the imaginary part of the smooth part:
f.smoothPart = imag(f.smoothPart);

% Return a SMOOTHFUN object if F is smooth:
if ( issmooth(f) )
    f = f.smoothPart;
end

end


text:
namespace GSMove
{
    using System;

    public class Call
    {
        private DateTime date;
        private DateTime time;
        private string dialedNumber;
        private int duration;

        public Call(DateTime date, DateTime time, string dialed, int duration)
        {
            this.date = date;
            this.time = time;
            this.dialedNumber = dialed;
            this.duration = duration;
        }
    }
}


text:
KeyList::KeyList() {
}
KeyList::~KeyList() {
}
void KeyList::insert(CButton* aData, int aIndex) {
	data.insert(data.begin() + aIndex, aData);
}
const int KeyList::size() const {
	return data.size();
}
CButton* KeyList::operator [](const int aIndex) {
	if ((aIndex < 0) && (aIndex > data.size())) {
		throw out_of_range("Index is out of range.");
		return NULL;
	} else {
		return data.at(aIndex);
	}
}
bool KeyList::remove(int aIndex) {
	if ((aIndex >= 0) && (aIndex < data.size())) {
		data.erase(data.begin() + aIndex);
		return true;
	} else {
		return false;
	}
}

void KeyList::clear() {
	data.clear();
}
void KeyList::OnStore(std::ostream& aStream) {
	int size = data.size();
	aStream.write((const char*) &size, sizeof(size));
	for (int i = 0; i < data.size(); i++) {
		data[i]->OnStore(aStream);
	}
}
void KeyList::add(CButton* aData) {
	data.push_back(aData);
}
void KeyList::show() {
	cout << "Collection data:" << endl;
	for (int i = 0; i < data.size(); i++) {
		BaseScreen * view = new CScreen(*data[i]);
		view->display();
		delete view;
		cout << endl;
	}
	cout << "----------------" << endl;
}
void KeyList::OnLoad(std::istream& aStream) {
	int size = 0;
	aStream.read((char*) &size, sizeof(size));

	for (int i = 0; i < size; i++) {
		CButton * tempData;
		tempData = new CButton;
		tempData->OnLoad(aStream);
		data.push_back(tempData);
		tempData = NULL;

		delete tempData;
	}

}


text:
package seccomp

// Seccomp represents syscall restrictions
// By default, only the native architecture of the kernel is allowed to be used
// for syscalls. Additional architectures can be added by specifying them in
// Architectures.
type Seccomp struct {
	DefaultAction Action     `json:"defaultAction"`
	Architectures []string   `json:"architectures"`
	Syscalls      []*Syscall `json:"syscalls"`
}

// Action is taken upon rule match in Seccomp
type Action int

const (
	Kill Action = iota + 1
	Errno
	Trap
	Allow
	Trace
)

// Operator is a comparison operator to be used when matching syscall arguments in Seccomp
type Operator int

const (
	EqualTo Operator = iota + 1
	NotEqualTo
	GreaterThan
	GreaterThanOrEqualTo
	LessThan
	LessThanOrEqualTo
	MaskEqualTo
)

// Arg is a rule to match a specific syscall argument in Seccomp
type Arg struct {
	Index    uint     `json:"index"`
	Value    uint64   `json:"value"`
	ValueTwo uint64   `json:"value_two"`
	Op       Operator `json:"op"`
}

// Syscall is a rule to match a syscall in Seccomp
type Syscall struct {
	Name   string `json:"name"`
	Action Action `json:"action"`
	Args   []*Arg `json:"args"`
}


text:
The **Version** page details the current version of the portal components.

It can be accessed by selecting **Version** from the navigation menu under **AYS Portal**.

![](version.png)

The page specifies the versions of the JumpScale core installation and its portal as well as the version of the used JSCockpit.


text:
'use strict';

module.exports = (ngModule) => {
  require('./sidebar.controller')(ngModule);
  require('./sidebar.directive')(ngModule);
};


text:
using System;
using FluentAssertions;
using Metrolib.Converters;
using NUnit.Framework;

namespace Metrolib.Test
{
	[TestFixture]
	public sealed class DoubleToPercentageConverterTest
	{
		[SetUp]
		public void Setup()
		{
			_converter = new DoubleToPercentageConverter();
		}

		private DoubleToPercentageConverter _converter;

		[Test]
		public void TestConvert1()
		{
			new Action(() => _converter.Convert(null, null, null, null)).ShouldNotThrow();
			new Action(() => _converter.Convert("", null, null, null)).ShouldNotThrow();
			new Action(() => _converter.Convert(42, null, null, null)).ShouldNotThrow();
			new Action(() => _converter.Convert("42", null, null, null)).ShouldNotThrow();
			new Action(() => _converter.Convert(typeof(int), null, null, null)).ShouldNotThrow();
		}

		[Test]
		[Ignore("Find out why this doesn't work on AppVeyor - why isn't my assumption met?!")]
		[SetCulture("en-US")]
		public void TestConvert2()
		{
			_converter.Convert(0.0, typeof(string), null, null).Should().Be("0%");
			_converter.Convert(1.0, typeof(string), null, null).Should().Be("100%");
			_converter.Convert(0.5, typeof(string), null, null).Should().Be("50%");
			_converter.Convert(0.55, typeof(string), null, null).Should().Be("55%");
			_converter.Convert(0.555, typeof(string), null, null).Should().Be("56%");
			_converter.Convert(0.5555, typeof(string), null, null).Should().Be("56%");
		}
	}
}


text:
 Improve this doc

Error Reference

Use the Error Reference manual to find information about error conditions in
your AngularJS app. Errors thrown in production builds of AngularJS will log
links to this site on the console.

Other useful references for debugging your app include:

API Reference for detailed information about specific features

Developer Guide for AngularJS concepts

Tutorial for getting started


text:
Mocks::UserMock::UserMock()
{
    this->getNextID();
    this->add(std::make_pair(std::make_pair("jani", "jelszo"), Models::User("Jani", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("pali", "jelszo"), Models::User("Pali", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("mari", "jelszo"), Models::User("Mari", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("sanyi", "jelszo"), Models::User("Sanyi", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("dani", "jelszo"), Models::User("Dani", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("gipsz", "jelszo"), Models::User("Gipsz Jakab", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("gibbs", "jelszo"), Models::User("Jacob Gibbs", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("izom", "jelszo"), Models::User("Izom Tibor", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("test", "jelszo"), Models::User("Test Eddie", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("bob", "jelszo"), Models::User("Bob", (this->getNextID()))));
    this->add(std::make_pair(std::make_pair("chrys", "jelszo"), Models::User("Chrysantemum", (this->getNextID()))));
}

bool Mocks::UserMock::add(const std::pair<std::pair<std::string, std::string>, Models::User> &user)
{
    try
    {
        users.insert(user);
    }
    catch (std::exception e)
    {
        return false;
    }
    return true;
}

Models::User Mocks::UserMock::getUserByID(const int &id)
{
    for(auto & user : users){
        if(user.second.getID()==id){
            return user.second;
        }
    }
    return Models::User(false);
}

Models::User Mocks::UserMock::getUserByCredentials(const std::pair<std::string, std::string> &credentials)
{
    try
    {
        auto user = users.at(credentials);
        return user;
    }
    catch (std::exception e)
    {
    }
    return Models::User(false);
}

std::vector<Models::User> Mocks::UserMock::getAllUsers()
{
    std::vector<Models::User> vec;
    for (auto it = users.cbegin(); it != users.cend(); ++it)
    {
        vec.push_back((*it).second);
    }
    return vec;
}

int Mocks::UserMock::getNextID()
{
    return ++(this->idcounter);
}


text:
import styled, { css } from 'styled-components'
import type { PaddingProps } from '@looker/design-tokens'
import { padding, reset } from '@looker/design-tokens'
import type { UseOverflowProps } from './useOverflow'

export type OverflowShadowProps = PaddingProps & UseOverflowProps

const OverflowShadowStyle = css`
  border-bottom: 1px solid ${({ theme }) => theme.colors.ui2};
  border-top: 1px solid ${({ theme }) => theme.colors.ui2};
  box-shadow: inset 0 -4px 4px -4px ${({ theme }) => theme.colors.ui2};
`

export const OverflowShadow = styled.div<OverflowShadowProps>`
  ${reset}
  ${({ hasOverflow }) => hasOverflow && OverflowShadowStyle}
  ${padding}
`


text:
<!DOCTYPE html>

	<title>Designing and writing a basic authentication API with Phoenix and Elixir (Auth Part 3) - Encrypted online accounting for freelancers with Sealas</title>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta content="width=device-width, initial-scale=1" name="viewport"/>

  <meta name="robots" content="index,follow">
	<meta name="description" content="Zero Knowledge, Open source, Open development. All data stored encrypted, source code open to everyone, blog journey through the whole development.">

	<link rel="alternate" hreflang="de" href="https://sealas.at/" />
	<link rel="alternate" hreflang="en" href="https://sealas.at/en" />

  <link href="/vendor/open-sans-fontface/open-sans.css" rel="stylesheet" type="text/css"/>
	<link rel="stylesheet" type="text/css" href="/vendor/lato/css/lato.min.css">
	<link rel="stylesheet" type="text/css" href="/fonts/fonts-raleway/css/raleway.min.css">
	<link rel="stylesheet" type="text/css" href="/styles/site/font-icons.css?v=1004">
	<link rel="stylesheet" type="text/css" href="/styles/font/crete/stylesheet.css?v=1004">

	<link rel="icon" href="/images/sealas-logo-yellow.png" />
	<link rel="shortcut icon" href="/images/favicon.ico" />

	<link rel="stylesheet" type="text/css" href="/styles/front.css?v=1004">
	<link rel="stylesheet" type="text/css" href="/styles/site.css?v=1004">

<meta name="twitter:card"       content="summary">
<meta name="twitter:site"       content="@sealasapp">
<meta property="og:url"         content="https://sealas.at/blog/2018-01/designing-and-writing-a-basic-authentication-api-with-phoenix-and-elixir-auth-part-3/">
<meta property="og:title"       content="Designing and writing a basic authentication API with Phoenix and Elixir (Auth Part 3)">
<meta property="og:type"        content="article">
<meta property="og:description" content="Continuing this series on writing and developing an authentication process with Phoenix and Elixir, so far we've covered developing our authentication library <a href="https://github.com/Brainsware/authtoken">authtoken</a> in part <a href="https://sealas.at/blog/2017-12/tokens-cookies-and-sessions-an-auth-story-part-1/">1</a> and <a href="https://sealas.at/blog/2018-01/encrypted-auth-tokens-for-phoenix-auth-part-2/">2</a>.">
<meta property="og:image"       content="https://sealas.at/images/sealas-logo-white-yellow.png">

About us

github

Blog

 en

 de

 en

			« back to blog

Designing and writing a basic authentication API with Phoenix and Elixir (Auth Part 3)

 26.01.2018

Continuing this series on writing and developing an authentication process with Phoenix and Elixir, so far we've covered developing our authentication library authtoken in part 1 and 2.

In this part (#3) we will cover the most basic necessities for a working authentication.
We will cover the basic structure in our app, including a custom ecto type to handle our password hashing and working with our token library.

So, what are we doing here?

APIs provide you with resources you need or want in another part of an application, or in another application entirely.
In the case of Sealas we want to provide our resources through a REST API to our front-end application.
When writing an interface like this, you usually don't want to give everyone access to everything; you want to give each user access specifically to their respective resources.
So let's protect it with a layer of authentication!

Packages and parts

Our users need to identify themselves via some kind of password, which at no point ever should be stored in cleartext.
To that end, we're going to use a password hashing library: Comeonin with Argon2.
For those who don't know, a password hashing library is different from a normal hashing library in that it is as slow as is sensible - depending on the system you're on.
This makes bruteforce attacks, i.e.
trying different combinations of passwords until you find a correct one, a lot harder and more resource intensive.

On a testing environment however that is not necessary, so to our config/test.exs file we can simply add:

config :argon2_elixir,
  t_cost: 2,
  m_cost: 12

With that we have our token storage covered.
To make it a bit easier to read our data, I would suggest using BaseModel, which provides an ActiveRecord like access to your ecto schemas.
It removes a lot of overhead when interacting with your data store.

We're also going to need to include our own authtoken library:

{:argon2_elixir, "~> 1.2"},
{:comeonin, "~> 4.0"},
{:base_model, "~> 0.2"},
{:authtoken, "~> 0.2"},

At some point in the future we may want to add other parts to our authentication system, like two-factor authentication or email confirmations, but we'll leave that for a later step and article.

What does the structure look like?

Part of any authentication are three different processes we're going to have to build:

Registration for new users

Login for existing users

Verification for provided authentication tokens

We're definitely going to need to store some user information, and the way to interface to with said store is via a schema.
But before we can access a store, we need to create it:

mix ecto.gen.migration create_users

I'm going to give the user a few more fields and features than just the bare-bones version, containing just an email and password field, but you can simplify or extend from that depending on your needs.

defmodule SealasSso.Repo.Migrations.CreateUsers do
  use Ecto.Migration

  def change do
    create table(:users) do
      add :email,                :string
      add :password,             :string, null: true
      add :password_hint,        :string, null: true
      add :active,               :bool,   default: false
      add :activation_code,      :string, size: 32, null: true

      timestamps()
    end

    create unique_index(:users, [:email])

  end
end

Let's go over these fields, to make sure we're all on the same page: Ecto's create table automatically adds the field id as a table's primary key, so we have that covered.
That makes it easy to avoid the mistake of using non-permanent data like an e-mail address as the primary key.
We do however use it as a user's identification token, so it's necessary to ensure it is unique; thus the additional unique_index attached to it.

The password is just a normal text field, but will of course never store a cleartext password.
It is allowed to have a null value, because the registration in Sealas is set up as a two-step process.
First you enter your email address, which you then verify and set your password.
This hints at the reason we include fields active and activation_code: By default a user is deactivated and gets an activation code attached and sent out by email on creation.

For simplicity's sake we'll skip this part for now, but keep these fields in mind.
I'll expand on this part in the next post.

With our migration set, we can go ahead and create a corresponding schema definition.

defmodule SealasSso.Accounts.User do
  use BaseModel, repo: SealasSso.Repo
  import Ecto.Changeset

  alias SealasSso.Accounts.User

  schema "users" do
    field :email,                :string
    field :password,             EctoHashedPassword
    field :password_hint,        :string
    field :active,               :boolean, default: false
    field :activation_code,      :string

    timestamps()
  end
end

At the top of the file we use BaseModel and tell it the repo file we're using.
The schema mirrors our migration file except for EctoHashedPassword, which automatically transforms all input into its hashed form.
I wrote another post explaining custom ecto types using another type as an example, so I will only add an abbreviated version here.

Custom password ecto type

The base for our custom type will be a string, since we're going to save the hash as a string to the database.
This makes the whole procedure very simple, as we're going to base our type on the string ecto type.

defmodule SealasSso.EctoHashedPasswordTest do
  use SealasSso.DataCase

  describe "casting custom ecto hashed password" do
    test "type", do: assert EctoHashedPassword.type == :string

    test "cast and verify" do
      assert {:ok, hash} = EctoHashedPassword.cast("test_password")

      assert EctoHashedPassword.checkpw("test_password", hash)
      assert !EctoHashedPassword.checkpw("wrong_password", hash)
    end
  end
end

Since we inherit most functionality from ecto's native type, we can focus on testing what we would add: the cast function hashing our input and an interface to the verification function of the hash of our choice.

defmodule EctoHashedPassword do
  @behaviour Ecto.Type
  def type, do: :string

  @doc """
  Hash password with currenly used hashing algorithm
  """
  def cast(password) when is_binary(password), do: {:ok, Comeonin.Argon2.hashpwsalt(password)}
  def cast(_), do: :error

  def load(password) when is_binary(password), do: {:ok, password}
  def load(_), do: :error

  def dump(password) when is_binary(password), do: {:ok, password}
  def dump(_), do: :error

  @doc """
  Check password against hash with currently used hashing algorithm.
  """
  @spec checkpw(String.t, String.t) :: boolean
  def checkpw(password, hash), do: Comeonin.Argon2.checkpw(password, hash)
end

Since we use Argon2 we implement our type with that.
If at any point we want to change the hashing function to something else, we have it consolidated in one place where we can then simply exchange it.

Well, almost.

To ensure that we're not breaking anything, let's add a test verifying that even in case of a future hash change, our previously stored Argon2 hashes still get verified.
Given the hypothetical case that we panic because Argon2 has been completely broken, and we need to change our algorithm NOW, we secure ourselves against forgetting to include the ability to still accept old Argon2 hashes; even if we only output hashes with a different algorithm.
Aren't tests nifty little buggers?

@argon2_hash "$argon2i$v=19$m=65536,t=6,p=1$79ljDB93b7A3W4LsbyoI2A$yiYBzrw1OaQiS86YESKTrwh8l9NnsUpbugddemKPv0w"

test "verify argon2 hash", do: assert EctoHashedPassword.checkpw("test_password", @argon2_hash)

Authentication Controller

Now that we have our migration, schema and type done, we can move on to the controller part.

Let's write some tests

to find out and define what we're going to expect our authentication to look and behave like.

defmodule SealasSso.AuthControllerTest do
  use SealasSso.ConnCase

  alias SealasSso.Repo
  alias SealasSso.Accounts.User

  @create_attrs %{email: "some@email.com", password: "some password", active: true}
  @valid_login  %{email: "some@email.com", password: "some password"}
  @failed_login %{email: "some@email.com", password: "wrong password"}

  def fixture() do
    {:ok, user} = %User{}
      |> User.create_test_changeset(@create_attrs)
      |> Repo.insert()
    user
  end

  setup %{conn: conn} do
    {:ok, conn: put_req_header(conn, "accept", "application/json")}
  end

  defp create_user(_) do
    user = fixture()
    {:ok, user: user}
  end
end

You'll notice that our passwords are very simple.
The password's complexity-check happens on the frontend, in JavaScript.
The frontend in its finished state will never actually send a cleartext password to the backend to perform any such test on it.
This double hashing reduces the likelihood of a leak at any stage of the process.

With this in place, we can now set some test data and setup functions for creating users to test our access with.
Next we can go on and define our actual use cases.

What do we want a successful login to look like?

  describe "login" do
    setup [:create_user]

    test "successful authentication as a user", %{conn: conn} do
      conn = get conn, auth_path(conn, :index), @create_attrs
      assert %{"auth" => auth_token} = json_response(conn, 201)

      assert {:ok, token} = AuthToken.decrypt_token(auth_token)

      {:ok, token_creatd_at} = DateTime.from_unix(token.fields["ct"])
      assert DateTime.diff(DateTime.utc_now(), token_creatd_at) >= 0

      conn = conn
      |> recycle()
      |> put_req_header("authorization", "bearer: " <> auth_token)
      |> get(user_path(conn, :index))

      assert json_response(conn, 200)
    end
  end

The most important part here is actually the first two lines of the test:

conn = get conn, auth_path(conn, :index), @valid_login
assert %{"auth" => auth_token} = json_response(conn, 201)

Accessing the auth_path route should give us a 201 HTTP code response, which stands for "Resoure created".
That newly created resource is the token it gives us back, which we then use to authenticate further requests.
Then we go on to validate the token with a separate function, and finally go on and try to access a protected route with it.

All that's missing is covering failure states; failed authentication because of bad credentials, and refused access for a protected route.

test "fail to authenticate with wrong password", %{conn: conn} do
  conn = get conn, auth_path(conn, :index), @failed_login
  assert json_response(conn, 401) == %{"error" => "auth fail"}
end

test "get 401 for protected route", %{conn: conn} do
  conn = get conn, user_path(conn, :index)

  assert json_response(conn, 401) == %{"error" => "auth fail"}
end

This covers our basic usage cases for a login, so:

Let's implement it!

Knowing what our authentication controller is supposed to do, this is pretty straight forward:

defmodule SealasSso.AuthController do
  use SealasSso, :controller

  alias SealasSso.Accounts.User
  alias SealasSso.Repo

  @spec index(Plug.Conn.t, %{email: String.t, password: String.t}) :: Plug.Conn.t
  def index(conn, %{"email" => email, "password" => password}) do
    user = User.first(email: email)

    cond do
      user && user.active && EctoHashedPassword.checkpw(password, user.password) ->
        conn
        |> put_status(:created) # http 201
        |> render("auth.json", %{auth: generate_token(user)})
      true ->
        conn
        |> put_status(:unauthorized) # http 401
        |> render("error.json")
  end
end

We only have two conditions here that will suffice our test cases: A successful login, and a catch-all unauthorized error.
If the user exists, is active and has a matching password we can go ahead and generate an authentication token.

Working with Tokens

Our authtoken library is nice enough to prepare us some tokens, but we still have to handle them responsibly in our app.
Two checks are still missing for that: is the token timed out, and is the token stale and needs refreshing?

First, getting a timed out token

conn = get conn, auth_path(conn, :index), @valid_login
assert %{"auth" => auth_token} = json_response(conn, 201)

{:ok, token} = AuthToken.decrypt_token(auth_token)
{:ok, auth_token} = AuthToken.generate_token %{token | "ct" => DateTime.utc_now() |> DateTime.to_unix() |> Kernel.-(864000)}

Requesting the token is analogous to the login.
Next we'll decrypt it, and inject a creation time way in the past so it's going to be timed out -- or at least we expect it to be!

conn = conn
|> recycle()
|> put_req_header("authorization", "bearer: " <> auth_token)
|> get(user_path(conn, :index))

assert json_response(conn, 401) == %{"error" => "timeout"}

The process for creating tokens that need to be refreshed is exactly the same, we just replace "rt" (refresh time) with "ct" (creation time); and we'll test for another message:

conn = conn
|> recycle()
|> put_req_header("authorization", "bearer: " <> stale_token)
|> get(user_path(conn, :index))

assert json_response(conn, 401) == %{"error" => "needs_refresh"}

But we're not done here, needs_refresh is after all a request to refresh the token to be able to continue working with the API.
So let's imagine how we'd go about getting a new token.

conn = get conn, auth_path(conn, :index), %{token: stale_token}
assert %{"auth" => auth_token} = json_response(conn, 201)

And then let's retry the request expecting it to be successful this time.

conn = conn
|> recycle()
|> put_req_header("authorization", "bearer: " <> auth_token)
|> get(user_path(conn, :index))

assert json_response(conn, 200)

The timeout and refresh answer should get handled by the library's router plug verify_token.
What is still missing is the refreshing of stale tokens, which given the easily accessible method `refresh_token`, also shouldn't be much of a problem:

def index(conn, %{"token" => auth_token}) do
  {:ok, token} = AuthToken.decrypt_token(auth_token)

  case AuthToken.refresh_token(auth_token) do
    {:ok, token} ->
      conn
      |> put_status(:created)
      |> render("auth.json", %{auth: token})
    _ ->
      conn
      |> put_status(:unauthorized)
      |> render("error.json")
  end
end

Right on! Either send back a new token, or if it's any error we can just send back a nondescript error.

Ah, but that is not all!

Refreshing tokens has one actually useful purpose: allowing you to check back with the backend in a longer interval to see if the user is still active, has the correct permissions or even still exists.
So what we have is a good starting point, but needs extending.

The test cases for refreshments need an additional one to ensure that if the user is not valid anymore, we don't get a new access token.

test "refuse refreshing of token if user has been deleted or deactivated", %{conn: conn} do
  user = User.first(email: @valid_login.email)

  stale_token = create_stale_token(user)

  User.update(user, active: false)

  conn = get conn, auth_path(conn, :index), %{token: stale_token}
  assert json_response(conn, 401)

  User.delete(user)

  conn = get conn, auth_path(conn, :index), %{token: stale_token}
  assert json_response(conn, 401)
end

Hidden here within create_stale_token/1  is the same method to acquire a stale token as above; other than that, we get the user and assert getting a 401 if the user is either inactive or deleted.

On the implementation side of things we just need to add the same checks we already use for the normal login process.

def index(conn, %{"token" => auth_token}) do
  {:ok, token} = AuthToken.decrypt_token(auth_token)

  user = User.first(id: token["id"])

  {:ok, token} = AuthToken.refresh_token(auth_token)

  cond do
    user && user.active && token ->
      conn
      |> put_status(:created)
      |> render("auth.json", %{auth: token})
    true ->
      conn
      |> put_status(:unauthorized)
      |> render("error.json")
  end
end

This is also where you could implement more advanced security checks, like following a user's IP, device, behaviour, etc.
Implementing such heuristics always comes with certain privacy implications that you need to keep in mind, finding a balance between the ability to track a user for the sake of security, and keeping a user's choices of access anonymous.
Keeping in tune with that, I'll just announce another article about this topic.

That's it for now! Next time we'll tackle verification by email, so stay tuned.

				Share this Post:

						<fb:like href='https://sealas.at/blog/2018-01/designing-and-writing-a-basic-authentication-api-with-phoenix-and-elixir-auth-part-3/'
         send='false'
         layout='button'
         show_faces=''
         width='80'
         action=''
         font=''
         colorscheme=''
         ref='' ></fb:like>

				 Tweet

					 Encrypted auth tokens for Phoenix (Auth part 2)

					Fortifying APIs: timing attacks

			<form action="//sealas.us13.list-manage.com/subscribe/post?u=26cea96bbfb24fbc5f58e314f&id=a92e310c11" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

App development, UX design, business: we're writing about the entire development of Sealas

					<input type="email" value="" required="required" name="EMAIL" class="form-control required email" id="mce-EMAIL" placeholder="Enter your email address here">

						<button class="btn btn-success" type="submit">Subscribe</button>

<input type="text" name="b_26cea96bbfb24fbc5f58e314f_a92e310c11" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

			</form>

The Secure Easy And Lovely Accounting Software for freelancers and small businesses.

								<address class="nobottommargin">
									Imprint:

									Sealas is a service by

									Brainsware OG

									Liechtensteinstraße 119/21

									A-1090 Wien
								</address>

ATU68014409

								HG Wien, FN 330963k

								Email: contact@sealas.at

								Web: https://brainsware.at

Home

About us

Features

Pricing

Sealas Website on Github

Sealas App on Github

Blog

Contact

TOS

Privacy Policy

					© Brainsware OG


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.resourceconnector.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Contains infrastructure information about the Appliance. */
@Fluent
public final class AppliancePropertiesInfrastructureConfig {
    /*
     * Information about the connected appliance.
     */
    @JsonProperty(value = "provider")
    private Provider provider;

    /**
     * Get the provider property: Information about the connected appliance.
     *
     * @return the provider value.
     */
    public Provider provider() {
        return this.provider;
    }

    /**
     * Set the provider property: Information about the connected appliance.
     *
     * @param provider the provider value to set.
     * @return the AppliancePropertiesInfrastructureConfig object itself.
     */
    public AppliancePropertiesInfrastructureConfig withProvider(Provider provider) {
        this.provider = provider;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
<!DOCTYPE html>

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

  <link rel="shortcut icon" href="../../img/favicon.ico">
  <title>Windows Server Firewall Setup - Forge Networking Remastered</title>
  <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" href="../../css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../css/theme_extra.css" type="text/css" />
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css">

         Forge Networking Remastered

  <form id ="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" title="Type search term here" />
  </form>

    Home

    User Manual (Forge Networking Remastered)

    Authoritative Design

    Getting Started

    Getting Started

    Basic Moving Cube Example

    Basic RPC Example

    Basic Instantiation Example

    Jump Start Guide

    Network Contract Wizard (NCW)

    Network Contract Wizard (NCW)

    Extending Generated Classes

    Name Collision Issues

    Network Object

    Changing Ownership

    Destroying the Network Object

    Fields

    Remote Procedure Calls (RPCs)

    Remote Procedure Calls

    Buffered RPCs

    Sending RPC to a Single Player

    RpcArgs and RpcInfo Structs

    RPC Validation by Server

    Replacing Previous Buffered RPCs

    Clearing Buffered RPCs

    Unity Integration

    GameObject Execution Order

    Network Instantiation

    Threading in Unity

    Main Threading RPCs

    Running Unity specific code on the main thread

    Unity Integration Network Start

    Basic Network Samples

    Server Hosting Code

    Client Connecting Code

    Server Disconnect Client Code

    Ban Client Code

    Send Binary Frame

    Send File

    Scene Navigation

    Loading Scenes

    Scene Events

    NetWorker

    Temporarily Blocking Connections

    Thread Safe Player Iteration

    Master Server

    Master Server Quick Start

    Connecting to Master Server

    Getting Host List From Master Server

    Windows Server Firewall Setup

Windows Server Firewall Setup

Done

    Web Server

    Web Server Jumpstart

    Web Server Extending With MVC

    Web Server Command Plugins

    Troubleshooting

    Troubleshooting

    Throttling Network Internal

    Events

    Rewinding

    Debugging

    Working With Multiple Sockets

    NAT Hole Punching

    LAN Discovery

    Offline Mode

    Lobby System

    Contributing

        Forge Networking Remastered

Docs »

Master Server »

Windows Server Firewall Setup

Windows Server Firewall Setup

Sometimes images speak louder than words, so we've compiled a list of images to show you exactly what you need to do in order to allow the Master Server to work on your Windows Server either in your home or in the cloud!

First you need to open your **Advanced Firewall Settings"

Next you need to select Inbound Rules then select New Rule...

Next you will need to select Port and then click Next

Next, make sure that TCP is selected and that you enter the correct port number for your Master Server. The default port is 15940. Then click Next

Next you need to select Allow the connection. Click Next

After that, just keep all the checkboxes at default (checked). Click Next

Lastly give it a good name that is easy to find and click Finish

Done

That is it, you should be ready to go. If you experience any other issues, make sure that your network firewall is allowing the connection to this machine and allowing the specified port number.

        Next

         Previous

  Built with MkDocs using a theme provided by Read the Docs.

        « Previous

        Next »


text:
<component name="libraryTable">
  <library name="scala-compiler">
    <CLASSES>
      <root url="jar://$USER_HOME$/apps/scala-2.10.4/lib/scala-compiler.jar!/" />
      <root url="jar://$USER_HOME$/apps/scala-2.10.4/lib/scala-library.jar!/" />
      <root url="jar://$USER_HOME$/apps/scala-2.10.4/lib/scala-reflect.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
<?php

namespace Magento\Search\Model\Autocomplete;

use Magento\Framework\ObjectManagerInterface;

class ItemFactory
{
    /**
     * @var ObjectManagerInterface
     */
    private $objectManager;

    /**
     * @param ObjectManagerInterface $objectManager
     */
    public function __construct(
        ObjectManagerInterface $objectManager
    ) {
        $this->objectManager = $objectManager;
    }

    /**
     * @param array $data
     * @return Item
     */
    public function create(array $data)
    {
        return $this->objectManager->create('\Magento\Search\Model\Autocomplete\Item', ['data' => $data]);
    }
}


text:
package asm

import (
	"fmt"
)

// Register is the source or destination of most operations.
type Register uint8

// R0 contains return values.
const R0 Register = 0

// Registers for function arguments.
const (
	R1 Register = R0 + 1 + iota
	R2
	R3
	R4
	R5
)

// Callee saved registers preserved by function calls.
const (
	R6 Register = R5 + 1 + iota
	R7
	R8
	R9
)

// Read-only frame pointer to access stack.
const (
	R10 Register = R9 + 1
	RFP          = R10
)

// Pseudo registers used by 64bit loads and jumps
const (
	PseudoMapFD    = R1 // BPF_PSEUDO_MAP_FD
	PseudoMapValue = R2 // BPF_PSEUDO_MAP_VALUE
	PseudoCall     = R1 // BPF_PSEUDO_CALL
)

func (r Register) String() string {
	v := uint8(r)
	if v == 10 {
		return "rfp"
	}
	return fmt.Sprintf("r%d", v)
}


text:
=========
Reference
=========

Commands
========
The `airship` shell command expects the path to `airship_home` as first
argument, then a sub-command which may have additional arguments. If
`airship` is called from the ``bin`` folder in `airship_home`, the first
argument is already provided by the bin/ script.

airship deploy
--------------
Run a full deployment: create new bucket, unpack tarball, install
dependencies, stop old process, start the new one, destroy old bucket.

Expects two arguments: a tarball (not gzipped) containing the
application, and the name of the process to deploy.

::

    $ bin/airship deploy myapp.tar web

airship run
-----------
Open a bash shell in the instance's folder. The ``prerun`` script, if
any, is executed as `rc` file. `run` accepts an optional argument, a
command to be run in the shell. With this option it behaves like ``bash
-c <command>``.

::

    $ bin/airship run web-jCCbfV 'echo "hello from instance in" `pwd`'

airship start
-------------
Start an instance. This simply configures the ``./server`` script,
inside the instance's folder, as a supervisor `program`.

::

    $ bin/airship start web-jCCbfV

airship stop
------------
Stops an instance. This simply removes the relevant `program` from
supervisor.

::

    $ bin/airship stop web-jCCbfV

airship destroy
---------------
Remove the instance (its folder and configuration files). Calls `stop`
first, in case the instance was running.

::

    $ bin/airship destroy web-jCCbfV

supervisord
-----------
Start the `supervisord` daemon. See `the supervisord documentation`_ for
details.

::

    $ bin/supervisord

.. _the supervisord documentation: http://supervisord.org/running.html#running-supervisord

supervisorctl
-------------
Interact with `supervisord`. Type `help` at the prompt to see what it
can do.

::

    $ bin/supervisorctl


text:
class Provide
  def initialize(provide_keys, user = nil)
    @provide_keys, @user = [provide_keys].flatten, user
  end

  def params
    provide_keys.inject({}) do |sum, i|
      provided_value = provide(i)
      sum[i] = provide(i) if provided_value
      sum
    end
  end

  private

  attr_reader :provide_keys, :user

  def provide(providable_item)
    case providable_item
    when "time"
      Time.now.utc.iso8601
    when "login"
      user && user.login
    when "service"
      user && user.service
    end
  rescue
    # Should get more specific safeguards here.
    logger.info "Couldn't provide #{providable_item}"
    nil
  end

end


text:
#region License
// Copyright (c) Amos Voron. All rights reserved.
// Licensed under the Apache 2.0 License. See LICENSE in the project root for license information.
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Diagnostics;

namespace QueryTalk.Wall
{
    /// <summary>
    /// Represents a database table or view.
    /// </summary>
    public abstract class DbTable<TRoot> : DbNode, ISemantic, IPredicate, IRelation, IOpenView, ISemqToSql
        where TRoot : DbRow
    {

        #region Public/Protected

        /// <summary>
        /// Returns a set of all rows in the data source.
        /// </summary>
        public virtual Result<TRoot> Go()
        {
            return Go(System.Reflection.Assembly.GetCallingAssembly());
        }

        /// <summary>
        /// Returns a set of all rows in the data source.
        /// </summary>
        /// <param name="client">A client assembly.</param>
        protected Result<TRoot> Go(System.Reflection.Assembly client)
        {
            return PublicInvoker.Call<Result<TRoot>>(client, (ca) =>
            {
                try
                {
                    var node = (DbNode)this;

                    // for reusability - !
                    var subject = node.RootWithBrokenChain ?? node.Root;

                    var query = ((ISemantic)subject).Translate(new SemqContext(subject), null);
                    query = ((ISelect)query).Select();
                    var proc = ((IEndProc)query).EndProcInternal();
                    var connectable = Reader.GetConnectable(ca, subject, proc);
                    var result = Reader.LoadTable<TRoot>(connectable, null, true);

                    subject.Recover();

                    return result;
                }
                catch (QueryTalkException ex)
                {
                    Loader.TryThrowInvalidSqlOperationException(ex, Name, Text.Method.Go);
                    throw;
                }
            });
        }

        /// <summary>
        /// Returns a set of all rows in the data source asynchronously.
        /// </summary>
        /// <param name="onCompleted">Is a delegate method that is invoked when the asynchronous operation completes.</param>
        /// <returns>The object of the asynchronous operation.</returns>
        public Async<Result<TRoot>> GoAsync(Action<Result<TRoot>> onCompleted = null)
        {
            return PublicInvoker.Call<Async<Result<TRoot>>>(Assembly.GetCallingAssembly(), (ca) =>
            {
                try
                {
                    var node = (DbNode)this;
                    var subject = node.Root;
                    var query = ((ISemantic)subject).Translate(new SemqContext(subject), null);
                    query = ((ISelect)query).Select();
                    var proc = ((IEndProc)query).EndProcInternal();
                    var connectable = Reader.GetConnectable(ca, subject, proc);
                    connectable.OnAsyncCompleted = onCompleted;
                    return Reader.LoadTableAsync<TRoot>(connectable, null);
                }
                catch (QueryTalkException ex)
                {
                    Loader.TryThrowInvalidSqlOperationException(ex, Name, Text.Method.GoAsync);
                    throw;
                }
            });
        }

        /// <summary>
        /// A NOT predicate operator.
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        public DbTable<TRoot> Not
        {
            get
            {
                ((IPredicate)this).HasNot = !((IPredicate)this).HasNot;
                return this;
            }
        }

        /// <summary>
        /// An OR predicate operator.
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        public DbTable<TRoot> Or
        {
            get
            {
                if (_predicates.Count == 0                          // first predicate cannot begin with .Or
                    || ((IPredicate)this).HasNot                    // .Not operator cannot precede .Or
                    || ((IPredicate)this).PredicateGroup != null    // first predicate inside the predicate group cannot begin with .Or
                    )
                {
                    throw new QueryTalkException("DbTable.Or", QueryTalkExceptionType.InvalidOr,
                        null, Text.Method.Or).SetObjectName(Name);
                }

                ((IPredicate)this).HasOr = true;
                return this;
            }
        }

        /// <summary>
        /// Specifies the foreign key that is to be used in relation.
        /// The foreign key should be explicitly given when there is more than one relation between two tables.
        /// </summary>
        /// <param name="foreignKey">A column that is part of a foreign key.</param>
        public DbTable<TRoot> By(DbColumn foreignKey)
        {
            if (foreignKey == null)
            {
                throw new QueryTalkException(".By", QueryTalkExceptionType.ArgumentNull, "foreign key", Text.Method.By);
            }

            ((IRelation)this).FK = foreignKey.ColumnID;

            return this;
        }

        #endregion

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private List<Predicate> _predicates = new List<Predicate>();

        /// <summary>
        /// Initializes a new instance of the DbTable class.
        /// </summary>
        /// <param name="prev"></param>
        protected DbTable(DbNode prev)
            : base(prev)
        { }

        #region IRelation

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        DB3 IRelation.FK { get; set; }

        #endregion

        #region IPredicate

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        List<Predicate> IPredicate.Predicates
        {
            get
            {
                return _predicates;
            }
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        Predicate IPredicate.Predicate { get; set; }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        bool IPredicate.HasNot { get; set; }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        bool IPredicate.HasOr { get; set; }

        void IPredicate.AddPredicate(Predicate predicate)
        {
            _predicates.Add(predicate);
        }

        void IPredicate.AddPredicate(PredicateType predicateType, DbNode sentence)
        {
            _predicates.Add(new Predicate(this, predicateType, true, LogicalOperator.And, (ISemantic)sentence));
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        bool IPredicate.HasPredicate
        {
            get
            {
                return _predicates.Count > 0;
            }
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        PredicateGroup IPredicate.PredicateGroup { get; set; }

        void IPredicate.SetPredicateGroup(PredicateGroupType predicateGroupType)
        {
            PredicateGroup.SetPredicateGroup(this, predicateGroupType);
        }

        void IPredicate.ResetPredicateGroup()
        {
            ((IPredicate)this).PredicateGroup = null;
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        int IPredicate.PredicateGroupLevel { get; set; }

        #endregion

        #region ISemantic

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        bool ISemantic.IsQuery
        {
            get
            {
                return Prev != null
                    || Next != null
                    || ((IPredicate)this).HasPredicate;
            }
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        DbNode ISemantic.Subject
        {
            get
            {
                return Root;
            }
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        DbNode ISemantic.RootSubject { get; set; }

        Chainer ISemantic.Translate(SemqContext context, DbNode predecessor)
        {
            return Translate.TranslateNode(context, predecessor, this);
        }

        #endregion

        #region Not browsable

        /// <summary>
        /// Not intended for public use.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        /// <summary>
        /// Not intended for public use.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        /// <summary>
        /// Not intended for public use.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override string ToString()
        {
            return base.ToString();
        }

        /// <summary>
        /// Not intended for public use.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new Type GetType()
        {
            return base.GetType();
        }

        #endregion

    }

}


text:
package org.apache.geode.internal.cache;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.CancelCriterion;
import org.apache.geode.CancelException;
import org.apache.geode.cache.CacheClosedException;
import org.apache.geode.test.junit.categories.UnitTest;

@Category(UnitTest.class)
public class TXRegionLockRequestImplTest {

  private InternalCache cache;
  private LocalRegion region;
  private CancelCriterion cancelCriterion;

  @Before
  public void setUp() {
    cache = mock(InternalCache.class);
    region = mock(LocalRegion.class);
    cancelCriterion = mock(CancelCriterion.class);

    when(cache.getCancelCriterion()).thenReturn(cancelCriterion);
    doThrow(new CacheClosedException()).when(cancelCriterion).checkCancelInProgress(any());
  }

  @Test
  public void getKeysThrowsCancelExceptionIfCacheIsClosed() {
    TXRegionLockRequestImpl txRegionLockRequest = new TXRegionLockRequestImpl(cache, region);
    assertThatThrownBy(() -> txRegionLockRequest.getKeys()).isInstanceOf(CancelException.class);
  }
}


text:
json_file = command('ls -t /tmp/inspec-*.json').stdout.lines.first.chomp
controls = json(json_file).profiles.first['controls']

# The test fixture has two controls - the first should pass,
# the second should be a skip with a waiver justification

control 'the unwaivered control' do
  describe controls[0]['results'][0]['status'] do
    it { should cmp 'passed' }
  end
end

control 'the waivered control' do
  describe controls[1]['results'][0]['status'] do
    it { should cmp 'skipped' }
  end
end


text:
'use strict';

var expect  = require('chai').expect,
    _       = require('underscore'),
    moment  = require('moment'),
    model   = require('../../../../lib/model/db');

describe('get_automatic_adjustment method', function(){

  describe('Employee start day is in previouse year and no end date',function(){
    var employee = model.User.build({
      start_date : moment('2015-07-14'),
    });

    it('no automatic adjustment', function(){
      expect(employee.get_automatic_adjustment({now : moment('2016-07-20')}))
        .to.be.equal(0)
    });
  });

  describe('Employee start date is in prevouse year but end date is in current year', function(){
    var employee = model.User.build({
      start_date : moment('2015-04-23'),
      end_date : moment('2016-04-01'),
    });
    employee.department = {
      allowence : 20,
    };

    it('ajustment is made based on end date', function(){
      expect(employee.get_automatic_adjustment({now : moment('2016-02-20')}))
        .to.be.equal(-15);
    });
  });

  describe('Employee start date is in previouse year and end date is in next year', function(){
   var employee = model.User.build({
      start_date : moment('2015-04-23'),
      end_date : moment('2017-04-01'),
    });
    employee.department = {
      allowence : 20,
    };

    it('ajustment is made based on end date', function(){
      expect(employee.get_automatic_adjustment({now : moment('2016-07-20')}))
        .to.be.equal(0);
    });
  });

  describe('Start date is in current year, no end date', function(){
    var employee = model.User.build({
      start_date : moment('2017-04-01'),
    });
    employee.department = {
      allowence : 20,
    };

    it('adjustment is made based on start date', function(){
      expect(employee.get_automatic_adjustment({now : moment('2017-07-20')}))
        .to.be.equal(-5);
    });

  });

  describe('Start date is in current year, end date is in current year either',function(){
    var employee = model.User.build({
      start_date : moment('2016-04-01'),
      end_date : moment('2016-10-01'),
    });
    employee.department = {
      allowence : 20,
    };

    it('adjustment is made based on start and end dates', function(){
      expect(employee.get_automatic_adjustment({now : moment('2016-07-20')}))
        .to.be.equal(-10);
    });
  });

  describe('Start date is in current year, end date is in next year', function(){
    var employee = model.User.build({
      start_date : moment('2017-04-01'),
      end_date : moment('2018-10-01'),
    });
    employee.department = {
      allowence : 20,
    };

    it('adjustment is made based on start date', function(){
      expect(employee.get_automatic_adjustment({now : moment('2017-07-20')}))
        .to.be.equal(-5);
    });
  });

  describe('Start date is in next year, no end date', function(){
    var employee = model.User.build({
      start_date : moment('2017-04-01'),
    });
    employee.department = {
      allowence : 20,
    };

    it('No adjustment is needed', function(){
      expect(employee.get_automatic_adjustment({now : moment('2016-07-20')}))
        .to.be.equal(0);
    });
  });

  describe('Start date is in next year, end date is defined',function(){
    var employee = model.User.build({
      start_date : moment('2017-04-01'),
      end_date : moment('2017-10-01'),
    });
    employee.department = {
      allowence : 20,
    };

    it('No adjustment is needed', function(){
      expect(employee.get_automatic_adjustment({now : moment('2016-07-20')}))
        .to.be.equal(0);
    });
  });
});


text:
'use strict';

var should = require('should');
var app = require('../../app');
var request = require('supertest');
var User = require('../user/user.model');
var Lecture = require('../lecture/lecture.model');
var Q = require('q');
var _ = require('lodash');
var Poll = require('../poll/poll.model');
var userId = null;
var lectureId = null;

var user = new User({
  provider: 'local',
  name: 'Fake User',
  email: 'test@test.com',
  password: 'password'
});

var auth = {};

describe('GET /api/lectures/:lecture_id/polls', function() {

  before(function (done) {
    Q.all(_.invoke([Poll, User, Lecture], 'remove')).then(function (products) {
      user.save(function (err, user) {
        userId = user._id;
        Lecture.create({
          name: 'lecture test',
          description: 'lecture test desc',
          speaker: user._id
        }, function (err, lecture) {
          lectureId = lecture._id;
          done();
        });
      });
    });
  });

  it('should sign in', function (done) {
    request(app)
      .post('/auth/local')
      .send({email: user.email, password: user.password})
      .expect(200)
      .end(function (err, res) {
        if(err) done(err);
        res.body.should.have.property('token');
        auth = {Authorization: 'Bearer ' + res.body.token};
        done();
      })
  });

});


text:
package org.apache.pulsar.broker.resourcegroup;

import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class ResourceQuotaCalculatorImplTest extends MockedPulsarServiceBaseTest {
    @BeforeClass
    @Override
    protected void setup() throws Exception {
        super.internalSetup();
        this.rqCalc = new ResourceQuotaCalculatorImpl();
    }

    @AfterClass(alwaysRun = true)
    @Override
    protected void cleanup() throws Exception {
        super.internalCleanup();
    }

    @Test
    public void testRQCalcNegativeConfTest() throws PulsarAdminException {
        final long[] allUsage = { 0 };
        long calculatedQuota = this.rqCalc.computeLocalQuota(-1, 0, allUsage);
        long expectedQuota = -1;
        Assert.assertEquals(calculatedQuota, expectedQuota);
    }

    @Test
    public void testRQCalcNegativeLocalUsageTest() {
        final long[] allUsage = { 0 };
        Assert.assertThrows(PulsarAdminException.class, () -> this.rqCalc.computeLocalQuota(0, -1, allUsage));
    }

    @Test
    public void testRQCalcNegativeAllUsageTest() {
        final long[] allUsage = { -1 };
        Assert.assertThrows(PulsarAdminException.class, () -> this.rqCalc.computeLocalQuota(0, 0, allUsage));
    }

    @Test
    public void testRQCalcGlobUsedLessThanConfigTest() throws PulsarAdminException {
        final long config = 100;
        final long localUsed = 20;
        final long[] allUsage = { 40 };
        final long newQuota = this.rqCalc.computeLocalQuota(config, localUsed, allUsage);
        Assert.assertTrue(newQuota > localUsed);
    }

    @Test
    public void testRQCalcGlobUsedEqualsToConfigTest() throws PulsarAdminException {
        final long config = 100;
        final long localUsed = 20;
        final long[] allUsage = { 100 };
        final long newQuota = this.rqCalc.computeLocalQuota(config, localUsed, allUsage);
        Assert.assertEquals(newQuota, localUsed);
    }

    @Test
    public void testRQCalcGlobUsedGreaterThanConfigTest() throws PulsarAdminException {
        final long config = 100;
        final long localUsed = 20;
        final long[] allUsage = { 150 };
        final long newQuota = this.rqCalc.computeLocalQuota(config, localUsed, allUsage);
        Assert.assertTrue(newQuota < localUsed);
    }

    @Test
    public void testRQCalcProportionalIncrementTest() throws PulsarAdminException {
        final long config = 100;
        final long[] allUsage = { 60 };
        final long localUsed1 = 20;
        final long localUsed2 = 40;

        final float initialUsageRatio = (float) localUsed1 / localUsed2;
        final long newQuota1 = this.rqCalc.computeLocalQuota(config, localUsed1, allUsage);
        final long newQuota2 = this.rqCalc.computeLocalQuota(config, localUsed2, allUsage);
        final float proposedUsageRatio = (float) newQuota1 / newQuota2;
        Assert.assertEquals(initialUsageRatio, proposedUsageRatio);
    }

    @Test
    public void testRQCalcGlobUsedZeroTest() throws PulsarAdminException {
        final long config = 10;  // don't care
        final long localUsed = 0;  // don't care
        final long[] allUsage = { 0 };
        final long newQuota = this.rqCalc.computeLocalQuota(config, localUsed, allUsage);
        Assert.assertEquals(newQuota, config);
    }

    @Test
    public void testNeedToReportLocalUsage() {
        // If the percentage change (increase or decrease) in usage is more than 5% for
        // either bytes or messages, send a report.
        Assert.assertFalse(rqCalc.needToReportLocalUsage(1040, 1000, 104, 100, System.currentTimeMillis()));
        Assert.assertFalse(rqCalc.needToReportLocalUsage(950, 1000, 95, 100, System.currentTimeMillis()));
        Assert.assertTrue(rqCalc.needToReportLocalUsage(1060, 1000, 106, 100, System.currentTimeMillis()));
        Assert.assertTrue(rqCalc.needToReportLocalUsage(940, 1000, 94, 100, System.currentTimeMillis()));
    }

    private ResourceQuotaCalculatorImpl rqCalc;
}


text:
RSpec.shared_examples_for 'cycle analytics event' do
  let(:params) { {} }
  let(:instance) { described_class.new(params) }

  it { expect(described_class.name).to be_a_kind_of(String) }
  it { expect(described_class.identifier).to be_a_kind_of(Symbol) }
  it { expect(instance.object_type.ancestors).to include(ApplicationRecord) }
  it { expect(instance).to respond_to(:timestamp_projection) }
  it { expect(instance.column_list).to be_a_kind_of(Array) }

  describe '#apply_query_customization' do
    it 'expects an ActiveRecord::Relation object as argument and returns a modified version of it' do
      input_query = instance.object_type.all

      output_query = instance.apply_query_customization(input_query)
      expect(output_query).to be_a_kind_of(ActiveRecord::Relation)
    end
  end
end


text: "$CLOUD_REBUILD" Point 32 dll debug same


text:
using namespace std;

#include "google/protobuf/descriptor.h"

namespace google {
namespace protobuf {
namespace compiler {
namespace szl {
namespace sorter {

// Nodes contains message indices using their original order within Proto::File.
typedef set<int> Nodes;
// Map from message index n to the message indices upon which message n depends.
typedef map<int, Nodes> DependencyMap;
// Cycles: sets of strongly connected nodes.
typedef set<Nodes> Cycles;

// Ensures that the messages within file are topogically sorted. This method
// does not modify file, but fills sorted_messages with pointers to message
// descriptors that are sorted topologically. Use sorted_messages only to
// iterate through the messages: you do not have ownership of the elements
// within and the contents will become invalid should file be changed.
// The algorithm is cautious, in that the order of the messages will match
// that of the original file unless achieving a valid ordering requires that
// they be moved.
void EnsureTopologicallySorted(const FileDescriptor& file,
                               vector<const Descriptor*>* sorted_messages);

// Extracts the dependencies between messages within file and the name of each
// message type. Names are qualified using dot-separated package specifiers.
// Self-recursive type dependencies are not added to dependency_map.
void GetDependencyMap(const FileDescriptor& file,
                      DependencyMap* dependency_map,
                      vector<string> *type_names);

// Returns true if dependency_map represents topologically sorted messages.
// That is, for each n, dependency_map[n] contains elements <= n.
bool IsTopologicallySorted(const DependencyMap& dependency_map);

// Returns sets of nodes where each elements within each set are strongly
// connected. A topological ordering is possible only if cycles is empty.
void GetCircularDependencies(const DependencyMap& dependency_map,
                             Cycles* cycles);

// Sorts messages topologically. It is a pre-condition that no mutually
// recursive message types exist. This should be confirmed via
// GetCircularDependencies() before calling this function.
// EnsureTopologicallySorted() provides a higher-level interface that
// will log a warning in this situation, but not attempt to sort the messages.
void SortTopologically(const FileDescriptor& file,
                       const DependencyMap &dependency_map,
                       vector<const Descriptor*> *sorted_messages);

}  // namespace sorter
}  // namespace szl
}  // namespace compiler
}  // namespace protobuf
}  // namespace google

#endif  // _PROTO_SORTER_H__


text:
#ifndef __ZMQ_ROUTER_HPP_INCLUDED__
#define __ZMQ_ROUTER_HPP_INCLUDED__

#include <map>

#include "socket_base.hpp"
#include "session_base.hpp"
#include "stdint.hpp"
#include "blob.hpp"
#include "msg.hpp"
#include "fq.hpp"

namespace zmq
{
class ctx_t;
class pipe_t;

//  TODO: This class uses O(n) scheduling. Rewrite it to use O(1) algorithm.
class router_t : public routing_socket_base_t
{
  public:
    router_t (zmq::ctx_t *parent_, uint32_t tid_, int sid_);
    ~router_t ();

    //  Overrides of functions from socket_base_t.
    void xattach_pipe (zmq::pipe_t *pipe_,
                       bool subscribe_to_all_,
                       bool locally_initiated_);
    int xsetsockopt (int option_, const void *optval_, size_t optvallen_);
    int xsend (zmq::msg_t *msg_);
    int xrecv (zmq::msg_t *msg_);
    bool xhas_in ();
    bool xhas_out ();
    void xread_activated (zmq::pipe_t *pipe_);
    void xpipe_terminated (zmq::pipe_t *pipe_);
    int get_peer_state (const void *routing_id_, size_t routing_id_size_) const;

  protected:
    //  Rollback any message parts that were sent but not yet flushed.
    int rollback ();

  private:
    //  Receive peer id and update lookup map
    bool identify_peer (pipe_t *pipe_, bool locally_initiated_);

    //  Fair queueing object for inbound pipes.
    fq_t _fq;

    //  True iff there is a message held in the pre-fetch buffer.
    bool _prefetched;

    //  If true, the receiver got the message part with
    //  the peer's identity.
    bool _routing_id_sent;

    //  Holds the prefetched identity.
    msg_t _prefetched_id;

    //  Holds the prefetched message.
    msg_t _prefetched_msg;

    //  The pipe we are currently reading from
    zmq::pipe_t *_current_in;

    //  Should current_in should be terminate after all parts received?
    bool _terminate_current_in;

    //  If true, more incoming message parts are expected.
    bool _more_in;

    //  We keep a set of pipes that have not been identified yet.
    std::set<pipe_t *> _anonymous_pipes;

    //  The pipe we are currently writing to.
    zmq::pipe_t *_current_out;

    //  If true, more outgoing message parts are expected.
    bool _more_out;

    //  Routing IDs are generated. It's a simple increment and wrap-over
    //  algorithm. This value is the next ID to use (if not used already).
    uint32_t _next_integral_routing_id;

    // If true, report EAGAIN to the caller instead of silently dropping
    // the message targeting an unknown peer.
    bool _mandatory;
    bool _raw_socket;

    // if true, send an empty message to every connected router peer
    bool _probe_router;

    // If true, the router will reassign an identity upon encountering a
    // name collision. The new pipe will take the identity, the old pipe
    // will be terminated.
    bool _handover;

    router_t (const router_t &);
    const router_t &operator= (const router_t &);
};
}

#endif


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <title>Lightstreamer :: Monitor Console Demo</title>
  <link rel="stylesheet" type="text/css" href="css/monitor.css" />

      NOTE: This is just a demo application. The
    actual Monitoring Dashboard, which is intended for use by Lightstreamer Server's administrators, is
    available from a different URL and with the proper credentials, as
    configured in lightstreamer_conf.xml. In production deployments, all the
    demo applications should be removed from the "pages" folder, including
    this instance of the Monitor Console Demo, as well as the "Demo" folder within "Adapters".

      Server Instance Address:
        -

      Startup Time:
      -

      Total Heap
      Free Heap

      Memory (Bytes)

          -

          -

      Total
      Streaming Mode
      Smart-Polling Mode
      Max

        Sessions

        -

        -

        -

        -

      Total
      Max

        Connections

        -

        -

      Subscribed Items
      Throughput (updates/s)
      Total Received Updates

      Inbound

        -

        -

        -

      Throughput (updates/s)
      Throughput (kbit/s)
      Total Sent Bytes
      Total Sent Updates
      Total Lost Updates

      Outbound

        -

        -

        -

        -

        -

      Throughput (messages/s)
      Throughput (kbit/s)
      Total Processed Bytes
      Total Handled Messages

      Client Messages

        -

        -

        -

        -

      Size
      Active
      Available
      Queued Tasks

      Thread Pool

          -

          -

          -

          -

      Total JVM Threads

        -

      Scroll Controls

          Log Message Filtering Status
          History Limit for the Log Message Panels

              50
              rows

          A red light notifies that some messages in the panels below are being dropped.
          Use the slider to set the depth of the tables below.

      Activities

      Timestamp
      IP
      Hostname
      Message

      Warnings

      Timestamp
      Message
      Thread

      Errors

      Timestamp
      Message
      Thread

      Lightstreamer Server Edition:

          -

      Version:

          -

      Licensed Client ID:

          -

      License Type:

          -

      Local Server Address:

          -

      Local Server IP:

          -

      Local Server Port:

          -

      Socket Name:

          -


text:
class Assessment::MissionsController < Assessment::AssessmentsController
  load_and_authorize_resource :mission, class: "Assessment::Mission", through: :course

  require 'zip/zipfilesystem'

  def show
    @assessment = @mission.assessment
    if curr_user_course.is_student? and !@assessment.can_start?(curr_user_course)
      redirect_to course_assessment_missions_path
      return
    end
    super
    @summary[:allowed_questions] = [Assessment::GeneralQuestion, Assessment::CodingQuestion]
    @summary[:type] = 'mission'
    @summary[:specific] = @mission

    respond_to do |format|
      format.html { render "assessment/assessments/show" }
    end
  end

  def new
    @missions = @course.missions
    @mission.exp = 1000
    @mission.open_at = DateTime.now.beginning_of_day
    @mission.close_at = DateTime.now.end_of_day + 7  # 1 week from now
    @mission.course_id = @course.id

    @tags = @course.tags
    @asm_tags = {}

    respond_to do |format|
      format.html # new.html.erb
    end
  end

  def edit
    @missions = @course.missions
  end

  def create
    @missions = @course.missions
    @mission.position = @course.missions.count + 1
    @mission.creator = current_user
    @mission.course_id = @course.id
    if params[:files]
      @mission.attach_files(params[:files].values)
    end

    if params[:single_question].to_i == 1
      if params[:answer_type] == 'code'
        specific = Assessment::CodingQuestion.new
      else
        specific = Assessment::GeneralQuestion.new
      end
      qn = @mission.questions.build
      qn.creator = current_user
      qn.max_grade = params[:max_grade]
      specific.question = qn
      specific.save
    end

    respond_to do |format|
      if @mission.save
        @mission.create_local_file
        format.html { redirect_to course_assessment_mission_path(@course, @mission),
                                  notice: "The mission #{@mission.title} has been created." }
      else
        format.html { render action: "new" }
      end
    end
  end

  def update
    respond_to do |format|
      if @mission.update_attributes(params[:assessment_mission])
        update_single_question_type
        format.html { redirect_to course_assessment_mission_path(@course, @mission),
                                  notice: "The mission #{@mission.title} has been updated."}
      else
        format.html {redirect_to edit_course_assessment_mission_path(@course, @mission) }
      end
    end
  end

  def update_questions
    if !params[:assessment].nil?
      ques_list = params[:assessment][:question_assessments]
    end
    if (!ques_list.nil?)
      old_list = @mission.as_assessment.question_assessments
      ques_list.each do |q|
        if old_list.where(:question_id => q).count === 0
          qa = QuestionAssessment.new
          qa.question_id = q
          qa.assessment_id =  @mission.assessment.id
          qa.position = @mission.questions.count
          qa.save
        end
      end
      old_list.each do |qa|
        if !ques_list.include? qa.question.id.to_s
          qa.destroy
        end
      end
    end

    @mission.update_max_grade
    respond_to do |format|
      if @mission.save and @mission.update_attributes(params[:assessment_mission])
        format.html { redirect_to course_assessment_mission_url(@course, @mission),
                                  notice: "The mission '#{@mission.title}' has been updated." }
      else
        format.html { render action: "edit" }
      end
    end
  end

  def destroy
    @mission.destroy
    respond_to do |format|
      format.html { redirect_to course_assessment_missions_url,
                                notice: "The mission #{@mission.title} has been removed." }
    end
  end

  def update_single_question_type
    if !@mission.single_question? or @mission.single_question_with_mpq?
      return
    end

    type = params[:answer_type] == 'code' ? Assessment::CodingQuestion : Assessment::GeneralQuestion
    curr_qn = @mission.questions.first
    if type != curr_qn.specific.class
      if curr_qn
        curr_qn.destroy
      end
      if params[:answer_type] == 'code'
        specific = Assessment::CodingQuestion.new
      else
        specific = Assessment::GeneralQuestion.new
      end
      qn = @mission.questions.create({creator_id: current_user.id, max_grade: params[:max_grade]})
      specific.question = qn
      specific.save
    else
      curr_qn.max_grade = params[:max_grade]
      curr_qn.save
    end

    @mission.save
  end

  def bulk_update
    super
    redirect_to overview_course_assessment_missions_path
  end

  def access_denied
    respond_to   do |format|
      format.html # show.html.erb
    end
  end

  def dump_code

    case params[:_type]
      when 'mine'
        std_courses =  curr_user_course.std_courses
      when 'phantom'
        std_courses = @course.user_courses.student.where(is_phantom: true)
      else
        std_courses = @course.user_courses.student.where(is_phantom: false)
    end

    sbms = @mission.submissions.
        where("std_course_id IN (?) and status = 'graded'", std_courses.select("user_courses.id")).includes(:std_coding_answers)

    result = nil

    Dir.mktmpdir("mission-dump-temp-#{Time.now}") { |dir|
      sbms.each do |sbm|
        ans = sbm.std_coding_answers.first
        unless ans
          next
        end

        path = dir

        if sbm.files.count > 0
          title = sbm.std_course.name.gsub(/\//,"_")
          dir_path = File.join(dir, title)
          Dir.mkdir(dir_path) unless Dir.exists?(dir_path)
          sbm.files.each do |file|
            temp_path = File.join(dir_path, file.original_name.gsub(/\//,"_"))
            file.file.copy_to_local_file :original, temp_path
          end
          path = dir_path
        end

        title = "#{sbm.std_course.name.gsub(/\//,"_") }.py"
        file = File.open(File.join(path, title), 'w+')
        file.write(ans.code)
        file.close
      end

      zip_name = File.join(File.dirname(dir),
                           Dir::Tmpname.make_tmpname([@mission.title, ".zip"], nil))
      Zip::ZipFile.open(zip_name, Zip::ZipFile::CREATE) { |zipfile|
        # Add every file in the directory to the zip file, preserving structure.
        Dir[File.join(dir, '**', '**')].each {|file|
          zipfile.add(file.sub(File.join(dir + '/'), ''), file)
        }
      }

      result = zip_name
    }

    respond_to do |format|
      format.zip {
        #filename = build_zip @folder, :recursive => false, :include => params['include']
        send_file(result, {
            :type => "application/zip, application/octet-stream",
            :disposition => "attachment",
            :filename => @mission.title + ".zip"
        }
        )
      }
    end
  end
end


text:
class MonitorBackup
  POLL_INTERVAL = 15
  include Sidekiq::Worker

  def perform(server_id, backup_id, user_id)
    manager = BackupTasks.new
    backup  = manager.perform(:refresh_backup, user_id, server_id, backup_id)

    if backup.built == false
      MonitorBackup.perform_in(MonitorBackup::POLL_INTERVAL.seconds, server_id, backup_id, user_id)
    end
  end
end


text:
/*******************************************************************************
*   $FILE:  eeprom_access.h
*   Atmel Corporation:  http://www.atmel.com \n
*   Support email:  touch@atmel.com
******************************************************************************/

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

#ifndef EEPROM_ACCESS_H
#define EEPROM_ACCESS_H

/*----------------------------------------------------------------------------
nested include files
----------------------------------------------------------------------------*/
#include "touch_api.h"

#if defined ( __ICCAVR__ )
   #include <ioavr.h>
   #if !defined(__XMEGA_CORE__)   // Caution
      #define EEPROM_START_ADDRESS 0x0000u /* User Eeprom address */
   #else /* !defined(__ATxmega128A1_H) */
      #define EEPROM_START_ADDRESS 0x1000u /* User Eeprom address */
      #define _ATXMEGA_DEVICE_ 1u
   #endif /* !defined(__ATxmega128A1_H) */
#elif defined( __GNUC__ ) /* defined ( __ICCAVR__ ) */
   #include <avr/io.h>
   #if !defined(__AVR_XMEGA__)
      #define EEPROM_START_ADDRESS 0x0000u /* User Eeprom address */
   #else /* !defined(__AVR_ATxmega128A1__) */
      #define EEPROM_START_ADDRESS 0x1000u /* User Eeprom address */
      #define _ATXMEGA_DEVICE_ 1u
   #endif /* !defined(__AVR_ATxmega128A1__) */
#endif /* defined( __GNUC__ ) */

/*----------------------------------------------------------------------------
manifest constants
----------------------------------------------------------------------------*/
/* Block start addresses in EEPROM */
#define EEPROM_LIB_CONFIG_START_ADDRESS  (EEPROM_START_ADDRESS + 2u)

/*==============================================================================
Name    : write_global_settings_to_eeprom
--------------------------------------------------------------------------------
Purpose : Save global parameter settings to EEPROM
Input   :
Output  :
Notes   :
==============================================================================*/
void write_global_settings_to_eeprom(void);

/*==============================================================================
Name    : write_sensor_settings_to_eeprom
--------------------------------------------------------------------------------
Purpose : Save sensor parameter settings to EEPROM
Input   :
Output  :
Notes   :
==============================================================================*/
void write_sensor_settings_to_eeprom(void);

#ifdef _QMATRIX_
/*==============================================================================
Name    : write_burst_lenghts_to_eeprom
--------------------------------------------------------------------------------
Purpose : Save burst length settings to EEPROM
Input   :
Output  :
Notes   :
==============================================================================*/
void write_burst_lenghts_to_eeprom(void);
#endif

/*==============================================================================
Name    : read_info_from_eeprom
--------------------------------------------------------------------------------
Purpose : Read Info block from EEPROM
Input   :
Output  :
Notes   :
==============================================================================*/
uint16_t read_info_from_eeprom( void );

/*==============================================================================
Name    : write_info_to_eeprom
--------------------------------------------------------------------------------
Purpose : Save information from library and sign in the EEPROM
Input   :
Output  :
Notes   :
==============================================================================*/
void write_info_to_eeprom( uint16_t lib_version );

/*==============================================================================
Name    : read_settings_from_eeprom
--------------------------------------------------------------------------------
Purpose : Will read settings from EEPROM
Input   :
Output  :
Notes   : Data is stored in 'eeprom_gv_block[]' in the format shown above
==============================================================================*/
void read_settings_from_eeprom( void );

#endif /* EEPROM_ACCESS_H */
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-EOF-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/


text:
select *
from profile
where 1=1
  --*desc and description = :desc


text:
"""Provides parser for index subcommand."""

from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, _SubParsersAction
from pathlib import Path
from typing import List, Optional

from pyani.scripts import subcommands

def build(
    subps: _SubParsersAction, parents: Optional[List[ArgumentParser]] = None
) -> None:
    """Return a command-line parser for the index subcommand.

    :param subps:  collection of subparsers in main parser
    :param parents:  parsers from which arguments are inherited

    The index subcommand takes a single positional argument:

    - indir           (directory containing input genome sequence files)
    """
    parser = subps.add_parser(
        "index", parents=parents, formatter_class=ArgumentDefaultsHelpFormatter
    )
    # Required argument: input directory
    parser.add_argument(
        "-i",
        "--indir",
        action="store",
        dest="indir",
        default=None,
        type=Path,
        help="input directory",
        required=True,
    )
    # Names for output files
    parser.add_argument(
        "--labels",
        dest="labelfname",
        action="store",
        default=Path("labels.txt"),
        type=Path,
        help="Filename for labels file",
    )
    parser.add_argument(
        "--classes",
        dest="classfname",
        action="store",
        default=Path("classes.txt"),
        type=Path,
        help="Filename for classes file",
    )
    parser.set_defaults(func=subcommands.subcmd_index)


text:
import hasDom from './lib/has-dom';

declare const InstallTrigger: any;

export { default as hasDOM } from './lib/has-dom';
export const window = hasDom ? self : null;
export const location = hasDom ? self.location : null;
export const history = hasDom ? self.history : null;
export const userAgent = hasDom ? self.navigator.userAgent : 'Lynx (textmode)';
export const isChrome = hasDom ? Boolean((window as any).chrome) && !(window as any).opera : false;
export const isFirefox = hasDom ? typeof InstallTrigger !== 'undefined' : false;